Add <@ elsif expression @>
[tedtools.git] / template.h
1 /*
2  * Copyright (c) 2008 Teodor Sigaev <teodor@sigaev.ru>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *        notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *        notice, this list of conditions and the following disclaimer in the
12  *        documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the author nor the names of any co-contributors
14  *        may be used to endorse or promote products derived from this software
15  *        without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY CONTRIBUTORS ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
23  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
27  * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 /******************************************************************************
31  *                         Html template library                              *
32  ******************************************************************************
33  ******************************************************************************
34  *                                  SYNTAX                                    *
35  ******************************************************************************
36  * <% EXPRESSION , "FORMAT"] [# "DEFAULTVALUE"] [|(h|u)]%>
37  *    - format value should be as in strftime for time value and printf
38  *      for all other. Currently, bool values have only "true"/"false"
39  *      string values
40  * <@IF EXPRESSION @>
41  * [<@ ELSE IF EXPRESSION | ELSIF EXPRESSION @>]
42  * [ <@ELSE@> ] 
43  * <@ENDIF@>
44  *
45  * Expression is classical with support following:
46  *    -  ['^'] VARNAME     
47  *              variable defined from C-code. Mark '^' means global 
48  *       variable, not local in loop.
49  *    -  expression (+|-|*|/|%) expression
50  *               ariphmetic operations
51  *    -  expression ( || | && ) expression
52  *               ! expression
53  *       logical OR, AND and NOT
54  *    - expression ( < | <= | == | >= | > | != | <> ) expression 
55  *              compare expression
56  *    - LENGTH(expression)
57  *      computes length of string
58  *    - DEFINED(expression)
59  *      returns true if expression is defined
60  *        - expression ? expression : expression
61  *    - ( expression )
62  *    - USERDEFINEDFUNCTION( [expression[,expression[...]]] )
63  *      User defined function call. Function should be defined at 
64  *      C-level.
65  *
66  * <@LOOP MARKNAME@>
67  *              [ <@ SELF @> ]
68  * <@ENDLOOP@>
69  * Loop has predefined variables:
70  *    __FIRST   - true for first iteration
71  *    __LAST    - true for last iteration
72  *    __COUNTER - iteration's number
73  *    __SIZE    - number of iterations
74  *    __ODD     - true for odd iteraion
75  *    __EVEN    - true for even iteraion
76  *
77  * <& FILENAME &>
78  *
79  * <# comment #>
80  *
81  ******************************************************************************
82  *                                C-Interface                                 *
83  ******************************************************************************
84  * - setTemplateValueInt
85  *   setTemplateValueString
86  *   setTemplateValueTime
87  *   setTemplateValueBool
88  *   setTemplateValueDouble
89  *   setTemplateValueUndefined
90  *   Sets varibale's value
91  * - addTemplateRow
92  *   Add one iteration to the pointed loop. Local variable in loop should 
93  *   pointed with predecence loop's mark(s) separated by dot. Example:
94  *       HTML:
95  *   <@Loop outerLoop@>
96  *              <% var1 %>
97  *      <@Loop innerLoop@>
98  *                      <% var2 %>
99  *              <@endloop@>
100  *       <@endloop@>
101  *      C:
102  *      addTemplateRow("outerLoop");
103  *  setTemplateValueBool("outerLoop.var1");
104  *      addTemplateRow("innerLoop");
105  *  setTemplateValueBool("outerLoop.innerLoop.var2");
106  * - addTemplateNestedLoop
107  *   returnTemplateNestedLoop
108  *   Manage self-nested loops ( ie tree-like structures ).
109  *       Loop's template should contains one <@ SELF @> pointer.
110  *
111  * Examplaes of usage are in data/template.html used for test.
112  *
113  ******************************************************************************
114  *                               Memory management                            * 
115  ******************************************************************************
116  * Unfortunatly, I'm too lazy to unify memory usage by several pieces
117  * in library. So, library uses mixed plain malloc and memory context
118  * concepts (tmalloc.h).
119  * To work with library it's needed to allocate persistent memory context
120  * for initTemplate().
121  * To work with template it's needed to get template's instance by 
122  * newTemplateInstance() call with separated memory context. In any time
123  * that memory context can be reseted or freeed and it will be enough
124  * to free template's instance.
125  * 
126  ******************************************************************************/
127
128 #ifndef __TEMPLATE_H__
129 #define __TEMPLATE_H__
130
131 #include <sys/types.h>
132 #include <time.h>
133 #include "glist.h"
134 #include "sfxstr.h"
135 #include "tmalloc.h"
136
137 typedef enum TemplateNodeType {
138         /* node tree types */
139         TextNode = 100,
140         VariableNode,
141         IncludeNode,
142         LoopNode,
143         ConditionNode,
144         CollectionNode,
145         ExpressionNode,
146         PrintNode,
147         ConstNode,
148         NestNode,
149         LoopData,
150
151         /* value's types of variables */
152         valueInt = 200, /* smallest of any values type */
153         valueString,
154         valueTime,
155         valueBool,
156         valueDouble,
157         valuePointer
158 } TemplateNodeType;
159
160 #define TND_HTMLESCAPE          (0x0001)
161 #define TND_URLESCAPE           (0x0002)
162 #define TND_GLOBAL                      (0x0004)
163
164 #define TND___FIRST                     (0x0008)
165 #define TND___LAST                      (0x0010)
166 #define TND___COUNTER           (0x0020)
167 #define TND___SIZE                      (0x0040)
168 #define TND___ODD                       (0x0080)
169 #define TND___EVEN                      (0x0100)
170
171 #define TND_DEFINED                     (0x0200)
172
173 #define TND__SPECIALMASK        (TND___FIRST | TND___LAST | TND___COUNTER | TND___SIZE | TND___ODD | TND___EVEN)
174
175 typedef struct TemplateData *Template;
176
177 typedef struct TemplateInstanceData *TemplateInstance;
178
179 typedef struct TemplateNodeData *TemplateNode;
180
181 typedef struct VariableValueData * VariableValue;
182 typedef struct VariableValueData {
183         TemplateNodeType        type; /* should be first, see resetTemplate/freeTemplate */
184         int                                     flags;
185         union {
186                 int                             intValue;
187                 char                    *stringValue;
188                 time_t                  timeValue;
189                 int                             boolValue;
190                 double                  doubleValue;
191                 VariableValue   ptrValue; /* special value to handle loop variables,
192                                                                          points to members of loopValues */
193         } value;
194 } VariableValueData;
195
196
197 typedef struct executeFunctionDescData *executeFunctionDesc;
198 typedef struct executeFunctionDescData {
199         char                    *name;
200         int                             nargs; /* -1 - variable number */
201         VariableValue   (*execFn)(TemplateInstance, int, VariableValue*);
202 } executeFunctionDescData;
203
204 typedef struct LoopInstanceData * LoopInstance;
205
206 typedef struct LoopRowData *LoopRow;
207
208 typedef struct LoopRowData {
209         TemplateNode            loop;
210         LoopInstance            nestedInstance;
211         LoopRow                         nextCell;
212         VariableValueData       varvals[1];
213 } LoopRowData;
214 #define LRDHDRSZ        (offsetof(LoopRowData, varvals))
215
216 typedef struct LoopInstanceData {
217         int                             nrow;
218         LoopInstance    upperInstance;
219
220         LoopInstance    nextCell;
221         LoopRow                 headList;
222         LoopRow                 tailList;
223         /* GList                        *rowValues; */ /*list of LoopRow */
224 } LoopInstanceData;
225
226 typedef struct LoopTemplateInstanceData *LoopTemplateInstance;
227 typedef struct LoopTemplateInstanceData {
228         TemplateNodeType        type; /* LoopData */
229         TemplateNode            loopNode;
230         LoopRow                         lastRow;
231         LoopInstance            currentInstance;
232         LoopInstance            headList;
233         LoopInstance            tailList;
234         /*GList                         *listInstance;*/
235 }       LoopTemplateInstanceData;
236
237 typedef long Offset; 
238
239 typedef struct  TemplateNodeData {
240         TemplateNodeType        type; /* should be first, see resetTemplate/freeTemplate */
241
242         union {
243                 /* TextNode */
244                 struct {
245                         char    *value;
246                         int             valueLength;
247                 } text;
248
249                 /* VariableNode */
250                 struct {
251                         char                    *varName;
252                         int                             varNameLength;
253                         Offset                  varValueOffset;
254                         /* VariableValue        value; */
255                         int                             flags;
256                 } variable;
257
258                 /* ExpressionNode */
259                 struct {
260                         VariableValue           *argsValue;
261                         int                                     nargs;
262                         char                            *functionName;
263                         executeFunctionDesc     function;
264                         GList                           *argsNode; /* list of arguments nodes */ 
265                 } expression;
266
267                 /* ConstNode */
268                 VariableValueData               value;
269
270                 /* PrintNode */
271                 struct {
272                         TemplateNode    expressionNode;
273                         char                    *formatValue;
274                         char                    *defaultValue;
275                         int                             flags;
276                 } print; 
277
278                 /* IncludeNode */
279                 char    *includeFile;
280
281                 /* NestNode */
282                 struct {
283                         TemplateNode    loop;
284                         LoopRow                 savedRowData;
285                         GList                   *childrenLoopAfterSelf; 
286                 } nest;
287
288                 /* LoopNode */
289                 struct {
290                         char                    *varName;
291                         int                     varNameLength;
292                         TemplateNode    bodyNode;
293                         TemplateNode    selfNode; /* pointer to self-nested plase to insert */
294                         GList                   *childrenLoop;  /* to reset loop's instance  */
295                         GList                   *listVarValues; /* list of loop variables */
296                         Offset                  loopDataOffset;
297                 } loop;
298
299                 /* ConditionNode */
300                 struct {
301                         TemplateNode    expressionNode;
302                         TemplateNode    ifNode;
303                         TemplateNode    elseNode;
304                 } condition;
305
306                 /* CollectionNode */
307                 GList   *children;
308         } nodeData;
309         
310 } TemplateNodeData;
311
312 /* prints result */
313 typedef void  (*outFn)(char *, int);
314
315 typedef char*   (*urlEscapeFn)(char *, int * /* in/out */);
316 typedef char*   (*htmlEscapeFn)(char *, int * /* in/out */);
317
318 typedef struct TemplateData {
319         TemplateNode            tree;
320         MemoryContext           *templateContext;
321         SFSTree                         variables;
322         outFn                           printString;
323         urlEscapeFn                     urlEscape;
324         htmlEscapeFn            htmlEscape;
325         executeFunctionDesc functions;
326
327         Offset                          templateInstanceSize;
328         char                            *templateInstance;
329 } TemplateData;
330
331 typedef struct TemplateInstanceData {
332         Template                        tmpl;
333         MemoryContext           *templateContext;
334         char                            instanceData[1];
335 } TemplateInstanceData;
336
337 int parseTemplateFile(Template tmpl, char* filename );  /* return non-zero if error */
338 int initTemplate( Template tmpl, MemoryContext *mc, executeFunctionDesc functions, char *basedir, char *filename );
339 void freeTemplate( Template tmpl );
340 TemplateInstance        newTemplateInstance(Template tmpl, MemoryContext *mc);
341 int printTemplate( TemplateInstance tmpl );
342
343 #define TVAR_OK                 (0)
344 #define TVAR_NOTFOUND   (1)
345 #define TVAR_FORBIDDEN  (2)
346 #define TVAR_NOROW              (3)
347 #define TVAR_LOOPMARK   (4)
348
349 int setTemplateValueInt( TemplateInstance tmpl, char * key, int val );
350 int setTemplateValueString( TemplateInstance tmpl, char * key, char * val );
351 int setTemplateValueTime( TemplateInstance tmpl, char * key, time_t val );
352 int setTemplateValueBool( TemplateInstance tmpl, char * key, int val );
353 int setTemplateValueUndefined( TemplateInstance tmpl, char * key );
354 int setTemplateValueDouble( TemplateInstance tmpl, char * key, double val );
355 int addTemplateRow( TemplateInstance tmpl, char * key );
356 int addTemplateNestedLoop( TemplateInstance tmpl, char * key);
357 int returnTemplateNestedLoop( TemplateInstance tmpl, char * key);
358 void dumpTemplate( Template tmpl );
359 #endif