Add some comments, fix cleanup, improve tests
[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@> ] 
42  * <@ENDIF@>
43  *
44  * Expression is classical with support following:
45  *    -  ['^'] VARNAME     
46  *              variable defined from C-code. Mark '^' means global 
47  *       variable, not local in loop.
48  *    -  expression (+|-|*|/|%) expression
49  *               ariphmetic operations
50  *    -  expression ( || | && ) expression
51  *               ! expression
52  *       logical OR, AND and NOT
53  *    - expression ( < | <= | == | >= | > | != | <> ) expression 
54  *              compare expression
55  *    - LENGTH(expression)
56  *      computes length of string
57  *    - DEFINED(expression)
58  *      returns true if expression is defined
59  *        - expression ? expression : expression
60  *    - ( expression )
61  *    - USERDEFINEDFUNCTION( [expression[,expression[...]]] )
62  *      User defined function call. Function should be defined at 
63  *      C-level.
64  *
65  * <@LOOP MARKNAME@>
66  *              [ <@ SELF @> ]
67  * <@ENDLOOP@>
68  * Loop has predefined variables:
69  *    __FIRST   - true for first iteration
70  *    __LAST    - true for last iteration
71  *    __COUNTER - iteration's number
72  *    __SIZE    - number of iterations
73  *    __ODD     - true for odd iteraion
74  *    __EVEN    - true for even iteraion
75  *
76  * <& FILENAME &>
77  *
78  * <# comment #>
79  *
80  ******************************************************************************
81  *                                C-Interface                                 *
82  ******************************************************************************
83  * - setTemplateValueInt
84  *   setTemplateValueString
85  *   setTemplateValueTime
86  *   setTemplateValueBool
87  *   setTemplateValueDouble
88  *   setTemplateValueUndefined
89  *   Sets varibale's value
90  * - addTemplateRow
91  *   Add one iteration to the pointed loop. Local variable in loop should 
92  *   pointed with predecence loop's mark(s) separated by dot. Example:
93  *       HTML:
94  *   <@Loop outerLoop@>
95  *              <% var1 %>
96  *      <@Loop innerLoop@>
97  *                      <% var2 %>
98  *              <@endloop@>
99  *       <@endloop@>
100  *      C:
101  *      addTemplateRow("outerLoop");
102  *  setTemplateValueBool("outerLoop.var1");
103  *      addTemplateRow("innerLoop");
104  *  setTemplateValueBool("outerLoop.innerLoop.var2");
105  * - addTemplateNestedLoop
106  *   returnTemplateNestedLoop
107  *   Manage self-nested loops ( ie tree-like structures ).
108  *       Loop's template should contains one <@ SELF @> pointer.
109  *
110  * Examplaes of usage are in data/template.html used for test.
111  *
112  ******************************************************************************
113  *                               Memory management                            * 
114  ******************************************************************************
115  * Unfortunatly, I'm too lazy to unify memory usage by several pieces
116  * in library. So, library uses mixed plain malloc and memory context
117  * concepts (tmalloc.h).
118  * To work with library it's needed to allocate persistent memory context
119  * for initTemplate() call and provide temporary memory context for usual work.
120  * after printTemplate is called it's needed to call resetTemplate() and 
121  * then resetMemoryContext() for second context. 
122  * 
123  ******************************************************************************/
124
125 #ifndef __TEMPLATE_H__
126 #define __TEMPLATE_H__
127
128 #include <sys/types.h>
129 #include <time.h>
130 #include "glist.h"
131 #include "sfxstr.h"
132 #include "tmalloc.h"
133
134 typedef enum TemplateNodeType {
135         /* node tree types */
136         TextNode = 100,
137         VariableNode,
138         IncludeNode,
139         LoopNode,
140         ConditionNode,
141         CollectionNode,
142         ExpressionNode,
143         PrintNode,
144         ConstNode,
145         NestNode,
146
147         /* value's types of variables */
148         valueInt = 200, /* smallest of any values type */
149         valueString,
150         valueTime,
151         valueBool,
152         valueDouble,
153         valuePointer
154 } TemplateNodeType;
155
156 #define TND_HTMLESCAPE          (0x0001)
157 #define TND_URLESCAPE           (0x0002)
158 #define TND_GLOBAL                      (0x0004)
159
160 #define TND___FIRST                     (0x0008)
161 #define TND___LAST                      (0x0010)
162 #define TND___COUNTER           (0x0020)
163 #define TND___SIZE                      (0x0040)
164 #define TND___ODD                       (0x0080)
165 #define TND___EVEN                      (0x0100)
166
167 #define TND_DEFINED                     (0x0200)
168
169 #define TND__SPECIALMASK        (TND___FIRST | TND___LAST | TND___COUNTER | TND___SIZE | TND___ODD | TND___EVEN)
170
171 typedef struct TemplateData *Template;
172
173 typedef struct TemplateNodeData *TemplateNode;
174
175 typedef struct VariableValueData * VariableValue;
176 typedef struct VariableValueData {
177         TemplateNodeType        type; /* should be first, see resetTemplate/freeTemplate */
178         int                                     flags;
179         union {
180                 int                             intValue;
181                 char                    *stringValue;
182                 time_t                  timeValue;
183                 int                             boolValue;
184                 double                  doubleValue;
185                 VariableValue   ptrValue; /* special value to handle loop variables,
186                                                                          points to members of loopValues */
187         } value;
188 } VariableValueData;
189
190
191 typedef struct executeFunctionDescData *executeFunctionDesc;
192 typedef struct executeFunctionDescData {
193         char                    *name;
194         int                             nargs; /* -1 - variable number */
195         VariableValue   (*execFn)(Template, int, VariableValue*);
196 } executeFunctionDescData;
197
198 typedef struct LoopInstanceData * LoopInstance;
199
200 typedef struct LoopRowData *LoopRow;
201
202 typedef struct LoopRowData {
203         TemplateNode            loop;
204         LoopInstance            nestedInstance;
205         VariableValueData       varvals[1];
206 } LoopRowData;
207 #define LRDHDRSZ        (offsetof(LoopRowData, varvals))
208
209 typedef struct LoopInstanceData {
210         int                             nrow;
211         LoopInstance    upperInstance;
212         GList                   *rowValues; /*list of LoopRow */
213 } LoopInstanceData;
214
215 typedef struct  TemplateNodeData {
216         TemplateNodeType        type; /* should be first, see resetTemplate/freeTemplate */
217
218         union {
219                 /* TextNode */
220                 struct {
221                         char    *value;
222                         int             valueLength;
223                 } text;
224
225                 /* VariableNode */
226                 struct {
227                         char                    *varName;
228                         int                             varNameLength;
229                         VariableValue   value;
230                         int                             flags;
231                 } variable;
232
233                 /* ExpressionNode */
234                 struct {
235                         VariableValue           *argsValue;
236                         int                                     nargs;
237                         char                            *functionName;
238                         executeFunctionDesc     function;
239                         GList                           *argsNode; /* list of arguments nodes */ 
240                 } expression;
241
242                 /* ConstNode */
243                 VariableValueData               value;
244
245                 /* PrintNode */
246                 struct {
247                         TemplateNode    expressionNode;
248                         char                    *formatValue;
249                         char                    *defaultValue;
250                         int                             flags;
251                 } print; 
252
253                 /* IncludeNode */
254                 char    *includeFile;
255
256                 /* NestNode */
257                 struct {
258                         TemplateNode    loop;
259                         LoopRow                 savedRowData;
260                         GList                   *childrenLoopAfterSelf; 
261                 } nest;
262
263                 /* LoopNode */
264                 struct {
265                         char                    *varName;
266                         int                     varNameLength;
267                         TemplateNode    bodyNode;
268                         TemplateNode    selfNode; /* pointer to self-nested plase to insert */
269                         GList                   *childrenLoop;  /* to reset loop's instance  */
270                         GList                   *listVarValues; /* list of loop variables */
271                         GList                   *listInstance;
272                         /*      listInstace -+
273                                                          +->instance-+
274                                                                                  +->row
275                                                                                  |
276                                                                                  |
277                                                                                  +->row->currentInstance
278                          */
279                         LoopRow                 lastRow;
280                         LoopInstance    currentInstance;                
281                 } loop;
282
283                 /* ConditionNode */
284                 struct {
285                         TemplateNode    expressionNode;
286                         TemplateNode    ifNode;
287                         TemplateNode    elseNode;
288                 } condition;
289
290                 /* CollectionNode */
291                 GList   *children;
292         } nodeData;
293         
294 } TemplateNodeData;
295
296 /* prints result */
297 typedef void  (*outFn)(char *, int);
298
299 typedef char*   (*urlEscapeFn)(char *, int * /* in/out */);
300 typedef char*   (*htmlEscapeFn)(char *, int * /* in/out */);
301
302 typedef struct TemplateData {
303         TemplateNode            tree;
304         MemoryContext           *templateContext;
305         SFSTree                         variables;
306         outFn                           printString;
307         urlEscapeFn                     urlEscape;
308         htmlEscapeFn            htmlEscape;
309         executeFunctionDesc functions;
310 } TemplateData;
311
312 int parseTemplateFile(Template tmpl, char* filename );  /* return non-zero if error */
313 int initTemplate( Template tmpl, MemoryContext *mc, executeFunctionDesc functions, char *basedir, char *filename );
314 void freeTemplate( Template tmpl );
315 void resetTemplate( Template tmpl );
316 int printTemplate( Template tmpl );
317
318 #define TVAR_OK                 (0)
319 #define TVAR_NOTFOUND   (1)
320 #define TVAR_FORBIDDEN  (2)
321 #define TVAR_NOROW              (3)
322 #define TVAR_LOOPMARK   (4)
323
324 int setTemplateValueInt( Template tmpl, char * key, int val );
325 int setTemplateValueString( Template tmpl, char * key, char * val );
326 int setTemplateValueTime( Template tmpl, char * key, time_t val );
327 int setTemplateValueBool( Template tmpl, char * key, int val );
328 int setTemplateValueUndefined( Template tmpl, char * key );
329 int setTemplateValueDouble( Template tmpl, char * key, double val );
330 int addTemplateRow( Template tmpl, char * key );
331 int addTemplateNestedLoop( Template tmpl, char * key);
332 int returnTemplateNestedLoop( Template tmpl, char * key);
333 void dumpTemplate( Template tmpl );
334 #endif