add .gitignore
[tedtools.git] / template.c
index 45b366b..fbc971e 100644 (file)
 #include "tlog.h"
 #include "template.h"
 
+/*
+ * Simple list implementation
+ */
+#define        TListPush(l,c)  do      {                                               \
+       (c)->nextCell = NULL;                                                   \
+       if ( (l)->tailList == NULL ) {                                  \
+               (l)->headList = (l)->tailList = (c);            \
+       } else {                                                                                \
+               (l)->tailList->nextCell = (c);                          \
+               (l)->tailList = (c);                                            \
+       }                                                                                               \
+} while(0)
+
+#define TListUnShift(l,c)  do  {                                       \
+       (c)->nextCell = (l)->headList;                                  \
+       if ( (l)->headList == NULL ) {                                  \
+               (l)->headList = (l)->tailList = (c);            \
+       } else {                                                                                \
+               (l)->headList = (c);                                            \
+       }                                                                                               \
+} while(0)
+
+#define TListShift(l,c)  do  {                                         \
+       (c) = (l)->headList;                                                    \
+       if ( (c) != NULL )      {                                                       \
+               (l)->headList = (c)->nextCell;                          \
+               if ( (l)->headList == NULL )                            \
+                       (l)->tailList = NULL;                                   \
+       }                                                                                               \
+} while(0)
+
+#define TListIsEmpty(l)                ( (l)->headList == NULL )
+
 /*
  * Default operations and functions
  */
@@ -48,7 +81,7 @@ isVariable(VariableValue value) {
        } else {
                switch (value->type) {
                        case valueInt:
-                               return value->value.intValue;
+                               return (value->value.intValue == 0) ? 0 : 1;
                        case valueString:
                                if ( value->value.stringValue == NULL || *value->value.stringValue == '\0' )
                                        return 0;
@@ -69,7 +102,7 @@ isVariable(VariableValue value) {
 }
 
 static VariableValue
-makeBoolValue(Template tmpl, int v) {
+makeBoolValue(TemplateInstance tmpl, int v) {
        VariableValue   outvalue = mcalloc(tmpl->templateContext, sizeof(VariableValueData));
 
        outvalue->type = valueBool;
@@ -79,7 +112,7 @@ makeBoolValue(Template tmpl, int v) {
 }
 
 static VariableValue
-copyValue(Template tmpl, VariableValue in) {
+copyValue(TemplateInstance tmpl, VariableValue in) {
        VariableValue   out= mcalloc(tmpl->templateContext, sizeof(VariableValueData));
 
        if (in)
@@ -92,7 +125,7 @@ copyValue(Template tmpl, VariableValue in) {
 }
 
 static VariableValue
-isDefinedFn(Template tmpl, int n, VariableValue *vals) {
+isDefinedFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        return makeBoolValue(tmpl, vals[0]->flags & TND_DEFINED );
 }
 
@@ -113,7 +146,7 @@ strmblen(char *str) {
 }
 
 static VariableValue
-LengthFn(Template tmpl, int n, VariableValue *vals) {
+LengthFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        VariableValue   outvalue = NULL;
 
        outvalue = copyValue( tmpl, NULL );
@@ -130,27 +163,27 @@ LengthFn(Template tmpl, int n, VariableValue *vals) {
 }
 
 static VariableValue
-NotFn(Template tmpl, int n, VariableValue *vals) {
+NotFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        return makeBoolValue(tmpl, !isVariable(vals[0]));
 }
 
 static VariableValue
-AndFn(Template tmpl, int n, VariableValue *vals) {
+AndFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        return makeBoolValue(tmpl, isVariable(vals[0]) && isVariable(vals[1]) );
 }
 
 static VariableValue
-OrFn(Template tmpl, int n, VariableValue *vals) {
+OrFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        return makeBoolValue(tmpl, isVariable(vals[0]) || isVariable(vals[1]) );
 }
 
 static VariableValue
-CondFn(Template tmpl, int n, VariableValue *vals) {
+CondFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        return isVariable(vals[0]) ? vals[1] : vals[2]; 
 }
 
 static VariableValue
-ModFn(Template tmpl, int n, VariableValue *vals) {
+ModFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        VariableValue   outvalue = copyValue( tmpl, NULL );
 
        outvalue->type = valueInt;
@@ -167,7 +200,7 @@ ModFn(Template tmpl, int n, VariableValue *vals) {
 }
 
 static VariableValue
-UnaryMinesFn(Template tmpl, int n, VariableValue *vals) {
+UnaryMinesFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        VariableValue   outvalue = copyValue( tmpl, vals[0] );
 
        if (outvalue->type == valueInt)
@@ -204,25 +237,25 @@ UnaryMinesFn(Template tmpl, int n, VariableValue *vals) {
        }
 
 static VariableValue
-PlusFn(Template tmpl, int n, VariableValue *vals) {
+PlusFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        ARIPHACT(+)
        return outvalue;
 }
 
 static VariableValue
-MinesFn(Template tmpl, int n, VariableValue *vals) {
+MinesFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        ARIPHACT(-)
        return outvalue;
 }
 
 static VariableValue
-MulFn(Template tmpl, int n, VariableValue *vals) {
+MulFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        ARIPHACT(*)
        return outvalue;
 }
 
 static VariableValue
-DivFn(Template tmpl, int n, VariableValue *vals) {
+DivFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        ARIPHACT(/)
        return outvalue;
 }
@@ -249,37 +282,37 @@ DivFn(Template tmpl, int n, VariableValue *vals) {
        }
 
 static VariableValue
-LtFn(Template tmpl, int n, VariableValue *vals) {
+LtFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        CMPACT(<)
        return outvalue;
 }
 
 static VariableValue
-LeFn(Template tmpl, int n, VariableValue *vals) {
+LeFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        CMPACT(<=)
        return outvalue;
 }
 
 static VariableValue
-EqFn(Template tmpl, int n, VariableValue *vals) {
+EqFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        CMPACT(==)
        return outvalue;
 }
 
 static VariableValue
-GeFn(Template tmpl, int n, VariableValue *vals) {
+GeFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        CMPACT(>=)
        return outvalue;
 }
 
 static VariableValue
-GtFn(Template tmpl, int n, VariableValue *vals) {
+GtFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        CMPACT(>)
        return outvalue;
 }
 
 static VariableValue
-NeFn(Template tmpl, int n, VariableValue *vals) {
+NeFn(TemplateInstance tmpl, int n, VariableValue *vals) {
        CMPACT(!=)
        return outvalue;
 }
@@ -366,12 +399,14 @@ findIncludes(ParseState *state, TemplateNode *node) {
                        *node = tmp.tree;
                        break;
                case    LoopNode:
+                       state->tmpl->templateInstanceSize += sizeof( LoopTemplateInstanceData );
                        if ( findIncludes(state, &( (*node)->nodeData.loop.bodyNode )) != 0 )
                                return 1;
                        break;
                case    ConditionNode:
                        if ( findIncludes(state, &( (*node)->nodeData.condition.ifNode )) != 0 ||
-                                       findIncludes(state, &( (*node)->nodeData.condition.elseNode )) != 0 )
+                                       findIncludes(state, &( (*node)->nodeData.condition.elseNode )) != 0  || 
+                                       findIncludes(state, &( (*node)->nodeData.condition.expressionNode )) != 0 )
                                return 1;
                        break;
                case    CollectionNode:
@@ -384,11 +419,25 @@ findIncludes(ParseState *state, TemplateNode *node) {
                                GLCELL_DATA(cell) = chld;
                        }
                        break;
-               case    ExpressionNode: /* any expression node can not include files */
+               case    VariableNode:
+                       state->tmpl->templateInstanceSize += sizeof( VariableValueData );
+                       break;
+               case    ExpressionNode:
+                       GListForeach(cell, (*node)->nodeData.expression.argsNode) {
+                               TemplateNode    chld = (TemplateNode)GLCELL_DATA(cell);
+
+                               if ( findIncludes(state, &chld) != 0 )
+                                       return 1;
+                               GLCELL_DATA(cell) = chld;
+                       }
+                       break;
                case    PrintNode:
+                       if ( findIncludes(state, &( (*node)->nodeData.print.expressionNode )) )
+                               return 1;
+                       break;
                case    ConstNode:
-               case    VariableNode:
                case    TextNode:
+               case    NestNode:
                        break;
                default:
                        tlog(TL_CRIT|TL_EXIT, "unknown node type: %d", (*node)->type);
@@ -464,51 +513,55 @@ checkSpecialVariable(int flags, char *varName) {
        } else if ( strcmp(varName, "__size") == 0 ) {
                flags &= ~TND_GLOBAL; /* special vars cannot be global */
                flags |= TND___SIZE;
+       } else if ( strcmp(varName, "__level") == 0 ) {
+               flags &= ~TND_GLOBAL; /* special vars cannot be global */
+               flags |= TND___LEVEL;
        }
 
        return flags;
 }
 
-static VariableValue
+static Offset
 findVariable( Template tmpl, TemplateNode loopParentNode, int flags, char *varName, int varNameLength ) {
-       VariableValue   *pvarval;
+       Offset                  *pOffset;
 
-       if ( (pvarval = SFSFindData(&tmpl->variables, varName, varNameLength)) == NULL ) {
-               VariableValue           pdata = mc0alloc(tmpl->templateContext, sizeof(VariableValueData));
+       if ( (pOffset = SFSFindData(&tmpl->variables, varName, varNameLength)) == NULL ) {
+               Offset                          offset = tmpl->templateInstanceSize;
+               VariableValue           pdata = (VariableValue)(tmpl->templateInstance + tmpl->templateInstanceSize);
                SFSDataIO                       in;
 
                in.key = varName;
                in.keylen = varNameLength;
-               in.data = &pdata;
+               in.data = &offset;
+
+               tmpl->templateInstanceSize += sizeof(VariableValueData);
 
                SFSAdd(&tmpl->variables, &in);
 
+               pdata->flags = 0;
+
                if ( loopParentNode && (flags & TND_GLOBAL) == 0 ) {
                        /*
-                        * copy special flags to support new inform loopParentNode
+                        * copy special flags to support loopParentNode
                         */
                        pdata->flags |=  flags & TND__SPECIALMASK;
-
-                       if ( flags & ( TND___FIRST | TND___LAST | TND___ODD | TND___EVEN ) )
-                               pdata->type = valueBool;
-                       else if ( flags & (TND___COUNTER | TND___SIZE) )
-                               pdata->type = valueInt;
-                       else
-                               pdata->type = valuePointer;
+                       pdata->type = valuePointer;
+                       pdata->value.ptrValue = NULL;
 
                        loopParentNode->nodeData.loop.listVarValues = 
-                                       GListPush( loopParentNode->nodeData.loop.listVarValues, pdata ); 
+                                       GListPush( loopParentNode->nodeData.loop.listVarValues, (void*)offset ); 
                }
 
-               return pdata;
+               return offset;
        }
 
-       return *pvarval;
+       return *pOffset;
 }
 
 static int
 addLoop(Template tmpl, TemplateNode node, TemplateNode loopParentNode) {
-       SFSDataIO               in;
+       SFSDataIO                               in;
+       LoopTemplateInstance    lti;
 
        if ( SFSFindData(&tmpl->variables, node->nodeData.loop.varName, node->nodeData.loop.varNameLength) != NULL ) {
                tlog(TL_CRIT,"Loop marked '%s' is already defined", node->nodeData.loop.varName);
@@ -517,14 +570,27 @@ addLoop(Template tmpl, TemplateNode node, TemplateNode loopParentNode) {
 
        in.key = node->nodeData.loop.varName;
        in.keylen = node->nodeData.loop.varNameLength;
-       in.data = &node;
+       in.data = &tmpl->templateInstanceSize;
 
        SFSAdd(&tmpl->variables, &in);
 
-       if ( loopParentNode ) 
+       node->nodeData.loop.loopDataOffset = tmpl->templateInstanceSize; 
+       lti = (LoopTemplateInstance)(tmpl->templateInstance + tmpl->templateInstanceSize);
+       memset(lti, 0, sizeof( LoopTemplateInstanceData ));
+       lti->type = LoopData;
+       lti->loopNode = node;
+
+       tmpl->templateInstanceSize += sizeof( LoopTemplateInstanceData );
+
+       if ( loopParentNode ) { 
                loopParentNode->nodeData.loop.childrenLoop = 
                        GListPush( loopParentNode->nodeData.loop.childrenLoop, node );
 
+               if ( loopParentNode->nodeData.loop.selfNode )
+                       loopParentNode->nodeData.loop.selfNode->nodeData.nest.childrenLoopAfterSelf =
+                               GListPush( loopParentNode->nodeData.loop.selfNode->nodeData.nest.childrenLoopAfterSelf, node );
+       }
+
        return 0;
 }
 
@@ -567,6 +633,16 @@ compileTree( Template tmpl, TemplateNode node, TemplateNode loopParentNode ) {
                        if ( addLoop( tmpl, node, loopParentNode ) )
                                return 1;
                        break;
+               case NestNode:
+                       node->nodeData.nest.loop = loopParentNode;
+                       if ( loopParentNode ) {
+                               if ( loopParentNode->nodeData.loop.selfNode )
+                                       tlog(TL_WARN,"Loop '%s' has duplicated nested call", node->nodeData.loop.varName);
+                               else
+                                       loopParentNode->nodeData.loop.selfNode = node;
+                       } else
+                               tlog(TL_WARN,"SELF tag without loop");
+                       break;
                case ConditionNode:
                        if ( compileTree(tmpl, node->nodeData.condition.expressionNode, loopParentNode) )
                                        return 1;
@@ -593,7 +669,7 @@ compileTree( Template tmpl, TemplateNode node, TemplateNode loopParentNode ) {
                                                                                                        node->nodeData.variable.varName,
                                                                                                        &node->nodeData.variable.varNameLength);
 
-                       node->nodeData.variable.value = findVariable( tmpl, loopParentNode,
+                       node->nodeData.variable.varValueOffset = findVariable( tmpl, loopParentNode,
                                                                                                node->nodeData.variable.flags,
                                                                                                node->nodeData.variable.varName, 
                                                                                                node->nodeData.variable.varNameLength );
@@ -637,7 +713,7 @@ initTemplate( Template tmpl, MemoryContext *mc, executeFunctionDesc functions, c
 
        memset(tmpl, 0, sizeof(TemplateData));
        tmpl->templateContext = mc;
-       SFSInit_dp(&tmpl->variables, sizeof(void*), NULL);
+       SFSInit_dp(&tmpl->variables, sizeof(Offset), NULL);
 
        if ( functions ) {
                executeFunctionDesc     ptr = functions;
@@ -657,6 +733,9 @@ initTemplate( Template tmpl, MemoryContext *mc, executeFunctionDesc functions, c
 
        if ( (err=recursiveReadTemplate(&state, NULL, filename))!=0 )
                return err;
+
+       tmpl->templateInstance = mcalloc( tmpl->templateContext, tmpl->templateInstanceSize );
+       tmpl->templateInstanceSize = 0;
        if ( (err=compileTree( tmpl, tmpl->tree, NULL ))!=0 )
                return err;
 
@@ -664,41 +743,9 @@ initTemplate( Template tmpl, MemoryContext *mc, executeFunctionDesc functions, c
 }
 
 /*
- * Reset/cleanup
+ * cleanup
  */
 
-void
-resetTemplate( Template tmpl ) {
-       SFSDataIO       out;
-       GListCell       *cell;
-
-       SFSIteratorStart( &tmpl->variables );
-
-       while( SFSIterate( &tmpl->variables, &out ) ) {
-               VariableValue   varval = *(VariableValue*) out.data;
-
-               if ( varval->type >= valueInt ) 
-                       varval->flags &= ~TND_DEFINED;
-               else if ( varval->type == LoopNode ) {
-                       TemplateNode    node = (TemplateNode) varval; 
-
-                       GListForeach( cell, node->nodeData.loop.listVarValues ) {
-                               varval = (VariableValue) GLCELL_DATA(cell);
-
-                               if ( varval->type == valuePointer )
-                                       varval->value.ptrValue = NULL;
-                       }
-
-                       GListForeach( cell, node->nodeData.loop.listInstance ) {
-                               LoopInstance instance = GLCELL_DATA(cell);
-
-                               GListFree(instance->rowValues );
-                       }
-                       GListTruncate( node->nodeData.loop.listInstance, 0 ); 
-               }
-       }
-}
-
 static void
 freeNode( TemplateNode node ) {
        GListCell   *cell;
@@ -708,16 +755,9 @@ freeNode( TemplateNode node ) {
 
        switch (node->type) {
                case    LoopNode:
-                       freeNode( node->nodeData.loop.bodyNode );
+                       freeNode( node->nodeData.loop.bodyNode ); /* selfNode is somewhere inside bodyNode */
                        GListFree( node->nodeData.loop.childrenLoop );
                        GListFree( node->nodeData.loop.listVarValues );
-
-                       GListForeach( cell, node->nodeData.loop.listInstance ) {
-                               LoopInstance instance = GLCELL_DATA(cell);
-
-                               GListFree(instance->rowValues );
-                       }
-                       GListFree( node->nodeData.loop.listInstance );
                        break;
                case    CollectionNode:
                        GListForeach( cell, node->nodeData.children ) 
@@ -737,6 +777,9 @@ freeNode( TemplateNode node ) {
                                freeNode( GLCELL_DATA(cell) );
                        GListFree( node->nodeData.expression.argsNode );
                        break;
+               case    NestNode:
+                       GListFree( node->nodeData.nest.childrenLoopAfterSelf ); 
+                       break;  
                case    VariableNode:
                case    IncludeNode:
                case    TextNode:
@@ -756,75 +799,194 @@ freeTemplate( Template tmpl ) {
  * Set value routines
  */
 
+TemplateInstance
+newTemplateInstance(Template tmpl, MemoryContext *mc) {
+       TemplateInstance        ti;
+
+       if (mc == NULL)
+               mc = tmpl->templateContext;
+
+       ti = mcalloc(mc, sizeof(TemplateInstanceData) + tmpl->templateInstanceSize);
+       ti->tmpl = tmpl;
+       ti->templateContext = mc;
+       memcpy( ti->instanceData, tmpl->templateInstance, tmpl->templateInstanceSize);
+
+       return ti;
+}
+
 static void
-newLoopInstance( Template tmpl, TemplateNode node ) {
-       node->nodeData.loop.listInstance = GListPush( 
-                               node->nodeData.loop.listInstance,
-                               mc0alloc(tmpl->templateContext, sizeof(LoopInstanceData) ) ); 
+newLoopInstance( TemplateInstance tmpl, TemplateNode node ) {
+       LoopInstance                    upper = NULL;
+       LoopTemplateInstance    loopData = (LoopTemplateInstance)
+                                                       (tmpl->instanceData + node->nodeData.loop.loopDataOffset);
+
+       if ( loopData->currentInstance )
+               upper = loopData->currentInstance->upperInstance;
+
+       loopData->currentInstance = 
+                               mc0alloc(tmpl->templateContext, sizeof(LoopInstanceData) );
+       loopData->currentInstance->upperInstance = upper;
+
+       TListPush( loopData, loopData->currentInstance );
+
+       loopData->lastRow = NULL;
 }
 
 int
-addTemplateRow( Template tmpl, char * key ) {
-       TemplateNode    *pnode, node;
+addTemplateRow( TemplateInstance tmpl, char * key) {
+       Offset                  *pOffset;
+       TemplateNode    node;
+       LoopTemplateInstance    loopData;
        char            *lkey = strlower(mcstrdup(tmpl->templateContext, key));
        GListCell               *cell;
-       VariableValue   varvals;
        int                             i=0, nvar;
-       LoopInstance    instance;
+       LoopRow                 rowData;
 
-       pnode = SFSFindData(&tmpl->variables, lkey, 0);
+       pOffset = SFSFindData(&tmpl->tmpl->variables, lkey, 0);
        mcfree(lkey);
 
-       if ( pnode == NULL )
+       if ( pOffset == NULL )
                return TVAR_NOTFOUND;
 
-       node = *pnode;
+       loopData = (LoopTemplateInstance)(tmpl->instanceData + *pOffset);
 
-       if ( node->type != LoopNode )
+       if ( loopData->type != LoopData )
                return TVAR_FORBIDDEN;
+       node = loopData->loopNode;
+
+       tassert( *pOffset == node->nodeData.loop.loopDataOffset );
 
        nvar = GLIST_LENGTH( node->nodeData.loop.listVarValues );
        if ( nvar == 0 )
                /* loop without vars can not be looped */
                return TVAR_NOROW;
 
-       if ( GLIST_LENGTH(node->nodeData.loop.listInstance) == 0 )
+       if ( TListIsEmpty(loopData) )
                newLoopInstance(tmpl, node);
 
        GListForeach( cell, node->nodeData.loop.childrenLoop )
                newLoopInstance( tmpl, GLCELL_DATA(cell) );
 
-       varvals = mcalloc( tmpl->templateContext, sizeof(VariableValueData) * nvar );
+       loopData->lastRow = rowData = mcalloc( tmpl->templateContext, LRDHDRSZ + sizeof(VariableValueData) * nvar );
+       rowData->loop = node;
+       rowData->nestedInstance = NULL;
+
        GListForeach( cell, node->nodeData.loop.listVarValues ) {       
-               VariableValue   vv = GLCELL_DATA(cell);
+               VariableValue   vv = (VariableValue) (tmpl->instanceData + ((Offset)GLCELL_DATA(cell)));
 
-               vv->value.ptrValue = varvals + i;
-               varvals[i].flags = 0;
+               vv->value.ptrValue = rowData->varvals + i;
+               rowData->varvals[i].flags = 0;
                i++;
        }
 
-       instance = GLCELL_DATA(GLIST_TAIL(node->nodeData.loop.listInstance));
+       loopData->currentInstance->nrow++;
+       TListPush( loopData->currentInstance, rowData );
 
-       instance->nrow++;
-       instance->rowValues = GListPush( instance->rowValues, varvals );
+       return TVAR_OK;
+}
+
+int 
+addTemplateNestedLoop( TemplateInstance tmpl, char * key) {
+       Offset                  *pOffset;
+       TemplateNode    node;
+       LoopTemplateInstance    loopData;
+       char            *lkey = strlower(mcstrdup(tmpl->templateContext, key));
+       GListCell               *cell;
+
+       pOffset = SFSFindData(&tmpl->tmpl->variables, lkey, 0);
+       mcfree(lkey);
+
+       if ( pOffset == NULL )
+               return TVAR_NOTFOUND;
+
+       loopData = (LoopTemplateInstance)(tmpl->instanceData + *pOffset);
+
+       if ( loopData->type != LoopData )
+               return TVAR_FORBIDDEN;
+       node = loopData->loopNode;
+
+       if ( node->nodeData.loop.selfNode == NULL )
+               return TVAR_FORBIDDEN;
+
+       if ( TListIsEmpty(loopData) || loopData->lastRow == NULL )
+               return TVAR_NOROW;
+
+       GListForeach( cell, node->nodeData.loop.childrenLoop ) {
+               LoopTemplateInstance    childData = (LoopTemplateInstance)
+                               (tmpl->instanceData + ((TemplateNode)GLCELL_DATA(cell))->nodeData.loop.loopDataOffset); 
+                                                                                       
+               childData->lastRow = NULL;
+       }
+
+       loopData->lastRow->nestedInstance = 
+                               mc0alloc(tmpl->templateContext, sizeof(LoopInstanceData) );
+       loopData->lastRow->nestedInstance->upperInstance = 
+                               loopData->currentInstance;
+       loopData->currentInstance =  
+                               loopData->lastRow->nestedInstance;
+       loopData->lastRow = NULL;
 
        return TVAR_OK;
 }
 
+int
+returnTemplateNestedLoop( TemplateInstance tmpl, char * key) {
+       Offset                  *pOffset;
+       TemplateNode    node;
+       LoopTemplateInstance    loopData;
+       char            *lkey = strlower(mcstrdup(tmpl->templateContext, key));
+       GListCell               *cell;
+
+       pOffset = SFSFindData(&tmpl->tmpl->variables, lkey, 0);
+       mcfree(lkey);
+
+       if ( pOffset == NULL )
+               return TVAR_NOTFOUND;
+
+       loopData = (LoopTemplateInstance)(tmpl->instanceData + *pOffset);
+
+       if ( loopData->type != LoopData )
+               return TVAR_FORBIDDEN;
+       node = loopData->loopNode;
+
+       if ( node->nodeData.loop.selfNode == NULL )
+               return TVAR_FORBIDDEN;
+
+       if ( TListIsEmpty(loopData) )
+               return TVAR_NOROW;
+
+       if ( loopData->currentInstance == NULL )
+               return TVAR_NOROW;
+
+       GListForeach( cell, node->nodeData.loop.childrenLoop ) {
+               LoopTemplateInstance    childData = (LoopTemplateInstance)
+                               (tmpl->instanceData + ((TemplateNode)GLCELL_DATA(cell))->nodeData.loop.loopDataOffset); 
+                                                                                       
+               childData->lastRow = NULL;
+       }
+
+       loopData->currentInstance = loopData->currentInstance->upperInstance; 
+       loopData->lastRow = NULL;
+
+       return TVAR_OK;
+
+}
+
 static VariableValueData storage;
        
 static int
-setTemplateValue( Template tmpl, char *key) {
-       VariableValue   *pvarval, varval;
+setTemplateValue( TemplateInstance tmpl, char *key) {
+       Offset                  *pOffset;
+       VariableValue   varval;
        char                    *lkey = strlower(mcstrdup(tmpl->templateContext, key));
        
-       pvarval = SFSFindData(&tmpl->variables, lkey, 0);
+       pOffset = SFSFindData(&tmpl->tmpl->variables, lkey, 0);
        mcfree(lkey);
 
-       if ( pvarval == NULL )
+       if ( pOffset == NULL )
                return TVAR_NOTFOUND;
 
-       varval = *pvarval;
+       varval = (VariableValue)(tmpl->instanceData + *pOffset);
 
        if ( varval->type != 0 && varval->type < valueInt ) {
                return TVAR_LOOPMARK;
@@ -854,7 +1016,7 @@ setTemplateValue( Template tmpl, char *key) {
 
 
 int
-setTemplateValueInt( Template tmpl, char * key, int val ) {
+setTemplateValueInt( TemplateInstance tmpl, char * key, int64_t val ) {
        storage.flags = TND_DEFINED;
        storage.type = valueInt;
        storage.value.intValue = val;
@@ -862,7 +1024,7 @@ setTemplateValueInt( Template tmpl, char * key, int val ) {
 }
 
 int
-setTemplateValueString( Template tmpl, char * key, char * val ) {
+setTemplateValueString( TemplateInstance tmpl, char * key, char * val ) {
        storage.flags = TND_DEFINED;
        storage.type = valueString;
        storage.value.stringValue = val;
@@ -870,7 +1032,7 @@ setTemplateValueString( Template tmpl, char * key, char * val ) {
 }
 
 int
-setTemplateValueTime( Template tmpl, char * key, time_t val ) {
+setTemplateValueTime( TemplateInstance tmpl, char * key, time_t val ) {
        storage.flags = TND_DEFINED;
        storage.type = valueTime;
        storage.value.timeValue = val;
@@ -878,7 +1040,7 @@ setTemplateValueTime( Template tmpl, char * key, time_t val ) {
 }
 
 int
-setTemplateValueBool( Template tmpl, char * key, int val ) {
+setTemplateValueBool( TemplateInstance tmpl, char * key, int val ) {
        storage.flags = TND_DEFINED;
        storage.type = valueBool;
        storage.value.boolValue = val;
@@ -886,15 +1048,15 @@ setTemplateValueBool( Template tmpl, char * key, int val ) {
 }
 
 int
-setTemplateValueDouble( Template tmpl, char * key, double val ) {
+setTemplateValueDouble( TemplateInstance tmpl, char * key, double val ) {
        storage.flags = TND_DEFINED;
        storage.type = valueDouble;
-       storage.value.boolValue = val;
+       storage.value.doubleValue = val;
        return setTemplateValue( tmpl, key );
 }
 
 int
-setTemplateValueUndefined( Template tmpl, char * key ) {
+setTemplateValueUndefined( TemplateInstance tmpl, char * key ) {
        storage.flags = 0;
        return setTemplateValue( tmpl, key );
 }
@@ -904,7 +1066,7 @@ setTemplateValueUndefined( Template tmpl, char * key ) {
  */
 
 static char *
-printVal( Template tmpl, VariableValue value, int *len, char *format ) {
+printVal( TemplateInstance tmpl, VariableValue value, int *len, char *format ) {
        int             printedlen;
        char    *res;
 
@@ -926,7 +1088,7 @@ printVal( Template tmpl, VariableValue value, int *len, char *format ) {
 
        switch (value->type) {
                case valueInt:
-                       printedlen = snprintf(NULL, 0, (format) ? format : "%d", value->value.intValue);
+                       printedlen = snprintf(NULL, 0, (format) ? format : "%lld", value->value.intValue);
                        break;
                case valueString:
                        if ( value->value.stringValue == NULL || *value->value.stringValue == '\0' )
@@ -949,7 +1111,7 @@ printVal( Template tmpl, VariableValue value, int *len, char *format ) {
 
        switch (value->type) {
                case valueInt:
-                       printedlen = snprintf(res, printedlen+1, (format) ? format : "%d", value->value.intValue);
+                       printedlen = snprintf(res, printedlen+1, (format) ? format : "%lld", value->value.intValue);
                        break;
                case valueString:
                        printedlen = snprintf(res, printedlen+1, (format) ? format : "%s", value->value.stringValue);
@@ -973,7 +1135,7 @@ printVal( Template tmpl, VariableValue value, int *len, char *format ) {
 
 
 static VariableValue
-executeExpression( Template tmpl, TemplateNode node ) {
+executeExpression( TemplateInstance tmpl, TemplateNode node ) {
        VariableValue   outvalue = NULL;
        GListCell               *cell;
        int                             i = 0;
@@ -984,10 +1146,12 @@ executeExpression( Template tmpl, TemplateNode node ) {
                        outvalue = &node->nodeData.value;
                        break;
                case VariableNode:
-                       if ( node->nodeData.variable.value->type == valuePointer )
-                               outvalue = node->nodeData.variable.value->value.ptrValue;
-                       else
-                               outvalue = node->nodeData.variable.value;
+                       outvalue = (VariableValue)(tmpl->instanceData + node->nodeData.variable.varValueOffset);
+
+                       tassert( (outvalue->flags & TND_DEFINED) == 0 || (outvalue->type >= valueInt && outvalue->type <= valuePointer) );
+
+                       if ( outvalue->type == valuePointer )
+                               outvalue = outvalue->value.ptrValue;
                        break;
                case ExpressionNode:
                        GListForeach(cell, node->nodeData.expression.argsNode)
@@ -1004,6 +1168,7 @@ executeExpression( Template tmpl, TemplateNode node ) {
                case ConditionNode:
                case CollectionNode:
                case PrintNode:
+               case NestNode:
                        tlog(TL_CRIT|TL_EXIT, "Unexpected node type: %d", node->type); 
                        break;
                default:
@@ -1017,9 +1182,10 @@ executeExpression( Template tmpl, TemplateNode node ) {
 }
 
 static void
-printNode( Template tmpl, TemplateNode node ) {
-       GListCell   *cell;
+printNode( TemplateInstance tmpl, TemplateNode node, LoopInstance loopInstance, int level ) {
+       GListCell       *cell;
        VariableValue   value;
+       int                             i;
 
        if (!node)
                return;
@@ -1027,79 +1193,144 @@ printNode( Template tmpl, TemplateNode node ) {
        switch (node->type) {
                case    LoopNode:
                        {
-                               GListCell               *cell = GListShift( node->nodeData.loop.listInstance );
+                               LoopTemplateInstance    loopData = (LoopTemplateInstance)
+                                                                               (tmpl->instanceData + node->nodeData.loop.loopDataOffset);
+                               GListCell               *cell;
                                LoopInstance    instance;
-                               int                             i;
-
-                               if ( cell == NULL )
-                                       return;
 
-                               instance = GLCELL_DATA(cell);
-                               GListFreeCell( node->nodeData.loop.listInstance, cell );
+                               if ( loopInstance ) {
+                                       instance = loopInstance;
+                               } else {
+                                       TListShift( loopData, instance );
+                                       if ( instance == NULL )
+                                               return;
+                               }
 
                                for(i=0; i<instance->nrow;i++) {
-                                       VariableValue   varvals;
+                                       LoopRow                 rowData;
                                        int                             j = 0;
+                                       VariableValue   realValue;
 
-                                       cell = GListShift( instance->rowValues );
-                                       varvals = GLCELL_DATA(cell);
-                                       GListFreeCell( instance->rowValues, cell );
+                                       TListShift( instance, rowData );
 
                                        GListForeach( cell, node->nodeData.loop.listVarValues ) {
-                                               value = (VariableValue)GLCELL_DATA(cell);
+                                               value = (VariableValue) (tmpl->instanceData + ((Offset)GLCELL_DATA(cell)));
                                
+                                               tassert( value->type == valuePointer );
+                                               realValue = value->value.ptrValue = rowData->varvals+j;
+
                                                if ( value->flags & TND___FIRST ) {
+                                                       realValue->type = valueInt;
                                                        if ( i==0 ) {
-                                                               value->flags |= TND_DEFINED;
-                                                               value->value.intValue = 1; 
+                                                               realValue->flags |= TND_DEFINED;
+                                                               realValue->value.intValue = 1; 
                                                        }  else {
-                                                               value->flags &= ~TND_DEFINED;
-                                                               value->value.intValue = 0;
+                                                               realValue->flags &= ~TND_DEFINED;
+                                                               realValue->value.intValue = 0;
                                                        }
                                                } else if ( value->flags & TND___LAST ) {
+                                                       realValue->type = valueInt;
                                                        if ( i==instance->nrow - 1 ) {
-                                                               value->flags |= TND_DEFINED;
-                                                               value->value.intValue = 1; 
+                                                               realValue->flags |= TND_DEFINED;
+                                                               realValue->value.intValue = 1; 
                                                        }  else {
-                                                               value->flags &= ~TND_DEFINED;
-                                                               value->value.intValue = 0;
+                                                               realValue->flags &= ~TND_DEFINED;
+                                                               realValue->value.intValue = 0;
                                                        }
                                                } else if ( value->flags & TND___COUNTER ) {
-                                                       value->flags |= TND_DEFINED;
-                                                       value->value.intValue = i+1;
+                                                       realValue->type = valueInt;
+                                                       realValue->flags |= TND_DEFINED;
+                                                       realValue->value.intValue = i+1;
+                                               } else if ( value->flags & TND___LEVEL ) {
+                                                       realValue->type = valueInt;
+                                                       realValue->flags |= TND_DEFINED;
+                                                       realValue->value.intValue = level;
                                                } else if ( value->flags & TND___SIZE ) {
-                                                       value->flags |= TND_DEFINED;
-                                                       value->value.intValue = instance->nrow;
+                                                       realValue->type = valueInt;
+                                                       realValue->flags |= TND_DEFINED;
+                                                       realValue->value.intValue = instance->nrow;
                                                } else if ( value->flags & TND___ODD ) {
-                                                       value->flags |= TND_DEFINED;
-                                                       value->value.boolValue = (i%2) ? 0 : 1 ;
+                                                       realValue->type = valueBool;
+                                                       realValue->flags |= TND_DEFINED;
+                                                       realValue->value.boolValue = (i%2) ? 0 : 1 ;
                                                } else if ( value->flags & TND___EVEN ) {
-                                                       value->flags |= TND_DEFINED;
-                                                       value->value.boolValue = (i%2) ? 1 : 0 ;
-                                               } else {
-                                                       tassert( value->type == valuePointer );
-                                                       value->value.ptrValue = varvals+j;
+                                                       realValue->type = valueBool;
+                                                       realValue->flags |= TND_DEFINED;
+                                                       realValue->value.boolValue = (i%2) ? 1 : 0 ;
                                                }
 
                                                j++;
                                        }
-                                       printNode( tmpl, node->nodeData.loop.bodyNode );
+
+                                       if ( node->nodeData.loop.selfNode ) 
+                                               node->nodeData.loop.selfNode->nodeData.nest.savedRowData = rowData;
+
+                                       printNode( tmpl, node->nodeData.loop.bodyNode, NULL, level );
+                               }
+                       }
+                       break;
+               case    NestNode:
+                       if ( node->nodeData.nest.loop && node->nodeData.nest.savedRowData ) {
+                               LoopRow                 savedRowData = node->nodeData.nest.savedRowData; /* save current row */
+                               LoopInstance    *savedChildrenInstance = NULL;
+
+                               /*
+                                *   Save child's instances for current loop
+                                */
+                               if ( GLIST_LENGTH(node->nodeData.nest.childrenLoopAfterSelf) ) {
+                                       savedChildrenInstance = mcalloc(tmpl->templateContext, sizeof(LoopInstance) * 
+                                                                                                       GLIST_LENGTH(node->nodeData.nest.childrenLoopAfterSelf));
+
+                                       i=0;
+                                       GListForeach( cell, node->nodeData.nest.childrenLoopAfterSelf) {
+                                               TemplateNode    chld = GLCELL_DATA(cell);
+                                               LoopTemplateInstance    loopData = (LoopTemplateInstance)
+                                                                                                       (tmpl->instanceData + chld->nodeData.loop.loopDataOffset);
+                                               LoopInstance    cellInstance;
+
+                                               TListShift( loopData, cellInstance );
+
+                                               savedChildrenInstance[i++] = cellInstance;
+                                       }
                                }
 
-                               GListFree( instance->rowValues );
+                               printNode( tmpl, node->nodeData.nest.loop, savedRowData->nestedInstance, level+1 );
+
+                               /*
+                                * Restore saved datas
+                                */
+                               i=0;
+                               GListForeach( cell, node->nodeData.nest.loop->nodeData.loop.listVarValues ) {
+                                       value = (VariableValue) (tmpl->instanceData + ((Offset)GLCELL_DATA(cell)));
+                                       value->value.ptrValue = savedRowData->varvals + i;
+                                       i++;
+                               }
+
+                               if ( GLIST_LENGTH(node->nodeData.nest.childrenLoopAfterSelf) ) {
+                                       i=0;
+                                       GListForeach( cell, node->nodeData.nest.childrenLoopAfterSelf) {
+                                               TemplateNode    chld = GLCELL_DATA(cell);
+                                               LoopTemplateInstance    loopData = (LoopTemplateInstance)
+                                                                                                       (tmpl->instanceData + chld->nodeData.loop.loopDataOffset);
+
+                                               if ( savedChildrenInstance[i] )
+                                                       TListUnShift( loopData, savedChildrenInstance[i] );
+                                               i++;
+                                       }
+                               }
                        }
                        break;
                case    ConditionNode:
                        value = executeExpression( tmpl, node->nodeData.condition.expressionNode );
 
                        if ( isVariable(value) ) 
-                               printNode( tmpl, node->nodeData.condition.ifNode );
+                               printNode( tmpl, node->nodeData.condition.ifNode, loopInstance, level );
                        else
-                               printNode( tmpl, node->nodeData.condition.elseNode );
+                               printNode( tmpl, node->nodeData.condition.elseNode, loopInstance, level );
                        break;
                case    CollectionNode:
                        GListForeach( cell, node->nodeData.children ) 
-                               printNode( tmpl, (TemplateNode)GLCELL_DATA(cell) );
+                               printNode( tmpl, (TemplateNode)GLCELL_DATA(cell), loopInstance, level );
                        break;
                case    PrintNode:
                        value = executeExpression( tmpl, node->nodeData.condition.expressionNode ); 
@@ -1110,22 +1341,22 @@ printNode( Template tmpl, TemplateNode node ) {
 
                                res = printVal(tmpl, value, &len, node->nodeData.print.formatValue);
 
-                               if ( (node->nodeData.variable.flags & TND_HTMLESCAPE) && tmpl->htmlEscape )
-                                       res = tmpl->htmlEscape(res, &len);
-                               if ( (node->nodeData.variable.flags & TND_URLESCAPE) && tmpl->urlEscape )
-                                       res = tmpl->urlEscape(res, &len);
+                               if ( (node->nodeData.variable.flags & TND_HTMLESCAPE) && tmpl->tmpl->htmlEscape )
+                                       res = tmpl->tmpl->htmlEscape(res, &len);
+                               if ( (node->nodeData.variable.flags & TND_URLESCAPE) && tmpl->tmpl->urlEscape )
+                                       res = tmpl->tmpl->urlEscape(res, &len);
 
                                if ( res && len>0  ) {
-                                       tmpl->printString( res, len );
+                                       tmpl->tmpl->printString( res, len );
                                        mcfree(res);
                                }
                        } else if ( node->nodeData.print.defaultValue ) {
-                               tmpl->printString( node->nodeData.print.defaultValue,
+                               tmpl->tmpl->printString( node->nodeData.print.defaultValue,
                                                                        strlen( node->nodeData.print.defaultValue ) );
                        }
                        break;
                case    TextNode:
-                       tmpl->printString( node->nodeData.text.value,  node->nodeData.text.valueLength );
+                       tmpl->tmpl->printString( node->nodeData.text.value,  node->nodeData.text.valueLength );
                        break;
                case    IncludeNode:
                case    VariableNode:
@@ -1140,11 +1371,11 @@ printNode( Template tmpl, TemplateNode node ) {
 }
 
 int
-printTemplate( Template tmpl ) {
-       if (!tmpl->printString)
+printTemplate( TemplateInstance tmpl ) {
+       if (!tmpl->tmpl->printString)
                return 1;
 
-       printNode(tmpl, tmpl->tree);
+       printNode(tmpl, tmpl->tmpl->tree, NULL, 0);
 
        return 0;
 }
@@ -1201,6 +1432,9 @@ recursiveDump(Template tmpl,  TemplateNode node, int level) {
                case    ConstNode:
                        printf("ConstNode\n");
                        break;
+               case    NestNode:
+                       printf("NestNode\n");
+                       break;
                default:
                        tlog(TL_CRIT|TL_EXIT, "unknown node type: %d", node->type);
        }