Imported Upstream version 1.8.8
[platform/upstream/doxygen.git] / src / template.h
1 /******************************************************************************
2  *
3  * Copyright (C) 1997-2014 by Dimitri van Heesch.
4  *
5  * Permission to use, copy, modify, and distribute this software and its
6  * documentation under the terms of the GNU General Public License is hereby
7  * granted. No representations are made about the suitability of this software
8  * for any purpose. It is provided "as is" without express or implied warranty.
9  * See the GNU General Public License for more details.
10  *
11  * Documents produced by Doxygen are derivative works derived from the
12  * input used in their production; they are not affected by this license.
13  *
14  */
15
16 #ifndef TEMPLATE_H
17 #define TEMPLATE_H
18
19 #include <qcstring.h>
20 #include <qvaluelist.h>
21
22 class FTextStream;
23
24 class TemplateListIntf;
25 class TemplateStructIntf;
26 class TemplateEngine;
27
28 /** @defgroup template_api Template API
29  *
30  *  This is the API for a
31  *  <a href="https://docs.djangoproject.com/en/1.6/topics/templates/">Django</a>
32  *  compatible template system written in C++.
33  *  It is somewhat inspired by Stephen Kelly's
34  *  <a href="http://www.gitorious.org/grantlee/pages/Home">Grantlee</a>.
35  *
36  *  A template is simply a text file.
37  *  A template contains \b variables, which get replaced with values when the
38  *  template is evaluated, and \b tags, which control the logic of the template.
39  *
40  *  Variables look like this: `{{ variable }}`
41  *  When the template engine encounters a variable, it evaluates that variable and
42  *  replaces it with the result. Variable names consist of any combination of
43  *  alphanumeric characters and the underscore ("_").
44  *  Use a dot (.) to access attributes of a structured variable.
45  *
46  *  One can modify variables for display by using \b filters, for example:
47  *  `{{ value|default:"nothing" }}`
48  *
49  *  Tags look like this: `{% tag %}`. Tags are more complex than variables:
50  *  Some create text in the output, some control flow by performing loops or logic,
51  *  and some load external information into the template to be used by later variables.
52  *
53  *  To comment-out part of a line in a template, use the comment syntax:
54  *  `{# comment text #}`.
55  *
56  *  Supported Django tags:
57  *  - `for ... empty ... endfor`
58  *  - `if ... else ... endif`
59  *  - `block ... endblock`
60  *  - `extend`
61  *  - `include`
62  *  - `with ... endwith`
63  *  - `spaceless ... endspaceless`
64  *  - `cycle`
65  *
66  *  Extension tags:
67  *  - `create` which instantiates a template and writes the result to a file.
68  *     The syntax is `{% create 'filename' from 'template' %}`.
69  *  - `recursetree`
70  *  - `markers`
71  *  - `msg` ... `endmsg`
72  *  - `set`
73  *
74  *  Supported Django filters:
75  *  - `default`
76  *  - `length`
77  *  - `add`
78  *  - `divisibleby`
79  *
80  *  Extension filters:
81  *  - `stripPath`
82  *  - `nowrap`
83  *  - `prepend`
84  *  - `append`
85  *
86  *  @{
87  */
88
89 /** @brief Variant type which can hold one value of a fixed set of types. */
90 class TemplateVariant
91 {
92   public:
93     /** @brief Helper class to create a delegate that can store a function/method call. */
94     class Delegate
95     {
96       public:
97         /** Callback type to use when creating a delegate from a function. */
98         typedef TemplateVariant (*StubType)(const void *obj, const QValueList<TemplateVariant> &args);
99
100         Delegate() : m_objectPtr(0) , m_stubPtr(0) {}
101
102         /** Creates a delegate given an object. The method to call is passed as a template parameter */
103         template <class T, TemplateVariant (T::*TMethod)(const QValueList<TemplateVariant> &) const>
104         static Delegate fromMethod(const T* objectPtr)
105         {
106           Delegate d;
107           d.m_objectPtr = objectPtr;
108           d.m_stubPtr   = &methodStub<T, TMethod>;
109           return d;
110         }
111         /** Creates a delegate given an object, and a plain function. */
112         static Delegate fromFunction(const void *obj,StubType func)
113         {
114           Delegate d;
115           d.m_objectPtr = obj;
116           d.m_stubPtr = func;
117           return d;
118         }
119
120         /** Invokes the function/method stored in the delegate */
121         TemplateVariant operator()(const QValueList<TemplateVariant> &args) const
122         {
123           return (*m_stubPtr)(m_objectPtr, args);
124         }
125
126       private:
127         const void* m_objectPtr;
128         StubType    m_stubPtr;
129
130         template <class T, TemplateVariant (T::*TMethod)(const QValueList<TemplateVariant> &) const>
131         static TemplateVariant methodStub(const void* objectPtr, const QValueList<TemplateVariant> &args)
132         {
133           T* p = (T*)(objectPtr);
134           return (p->*TMethod)(args);
135         }
136     };
137
138     /** Types of data that can be stored in a TemplateVariant */
139     enum Type { None, Bool, Integer, String, Struct, List, Function };
140
141     /** Returns the type of the value stored in the variant */
142     Type type() const;
143
144     /** Return a string representation of the type of the value stored in the variant */
145     QCString typeAsString() const;
146
147     /** Returns TRUE if the variant holds a valid value, or FALSE otherwise */
148     bool isValid() const;
149
150     /** Constructs an invalid variant. */
151     TemplateVariant();
152
153     /** Constructs a new variant with a boolean value \a b. */
154     explicit TemplateVariant(bool b);
155
156     /** Constructs a new variant with a integer value \a v. */
157     TemplateVariant(int v);
158
159     /** Constructs a new variant with a string value \a s. */
160     TemplateVariant(const char *s,bool raw=FALSE);
161
162     /** Constructs a new variant with a string value \a s. */
163     TemplateVariant(const QCString &s,bool raw=FALSE);
164
165     /** Constructs a new variant with a struct value \a s.
166      *  @note. The variant will hold a reference to the object.
167      */
168     TemplateVariant(TemplateStructIntf *s);
169
170     /** Constructs a new variant with a list value \a l.
171      *  @note. The variant will hold a reference to the object.
172      */
173     TemplateVariant(TemplateListIntf *l);
174
175     /** Constructs a new variant which represents a method call
176      *  @param[in] delegate Delegate object to invoke when
177      *             calling call() on this variant.
178      *  @note Use TemplateVariant::Delegate::fromMethod() and
179      *  TemplateVariant::Delegate::fromFunction() to create
180      *  Delegate objects.
181      */
182     TemplateVariant(const Delegate &delegate);
183
184     /** Destroys the Variant object */
185     ~TemplateVariant();
186
187     /** Constructs a copy of the variant, \a v,
188      *  passed as the argument to this constructor.
189      */
190     TemplateVariant(const TemplateVariant &v);
191
192     /** Assigns the value of the variant \a v to this variant. */
193     TemplateVariant &operator=(const TemplateVariant &v);
194
195     /** Compares this QVariant with v and returns true if they are equal;
196      *  otherwise returns false.
197      */
198     bool operator==(TemplateVariant &other);
199
200     /** Returns the variant as a string. */
201     QCString            toString() const;
202
203     /** Returns the variant as a boolean. */
204     bool                toBool() const;
205
206     /** Returns the variant as an integer. */
207     int                 toInt() const;
208
209     /** Returns the pointer to list referenced by this variant
210      *  or 0 if this variant does not have list type.
211      */
212     TemplateListIntf   *toList() const;
213
214     /** Returns the pointer to struct referenced by this variant
215      *  or 0 if this variant does not have struct type.
216      */
217     TemplateStructIntf *toStruct() const;
218
219     /** Return the result of apply this function with \a args.
220      *  Returns an empty string if the variant type is not a function.
221      */
222     TemplateVariant call(const QValueList<TemplateVariant> &args);
223
224     /** Sets whether or not the value of the Variant should be
225      *  escaped or written as-is (raw).
226      *  @param[in] b TRUE means write as-is, FALSE means apply escaping.
227      */
228     void setRaw(bool b);
229
230     /** Returns whether or not the value of the Value is raw.
231      *  @see setRaw()
232      */
233     bool raw() const;
234
235   private:
236     class Private;
237     Private *p;
238 };
239
240 //------------------------------------------------------------------------
241
242 template<class T> class TemplateAutoRef
243 {
244   public:
245     TemplateAutoRef(T *obj) : m_obj(obj)
246     {
247       m_obj->addRef();
248     }
249    ~TemplateAutoRef()
250     {
251       m_obj->release();
252     }
253     T &operator*() const { return *m_obj; }
254     T *operator->() const { return m_obj; }
255     T *get() const { return m_obj; }
256
257   private:
258    T *m_obj;
259 };
260
261 //------------------------------------------------------------------------
262
263 /** @brief Abstract read-only interface for a context value of type list.
264  *  @note The values of the list are TemplateVariants.
265  */
266 class TemplateListIntf
267 {
268   public:
269     /** @brief Abstract interface for a iterator of a list. */
270     class ConstIterator
271     {
272       public:
273         /** Destructor for the iterator */
274         virtual ~ConstIterator() {}
275         /** Moves iterator to the first element in the list */
276         virtual void toFirst() = 0;
277         /** Moves iterator to the last element in the list */
278         virtual void toLast() = 0;
279         /** Moves iterator to the next element in the list */
280         virtual void toNext() = 0;
281         /** Moves iterator to the previous element in the list */
282         virtual void toPrev() = 0;
283         /* Returns TRUE if the iterator points to a valid element
284          * in the list, or FALSE otherwise.
285          * If TRUE is returned, the value pointed to be the
286          * iterator is assigned to \a v.
287          */
288         virtual bool current(TemplateVariant &v) const = 0;
289     };
290
291     /** Destroys the list */
292     virtual ~TemplateListIntf() {}
293
294     /** Returns the number of elements in the list */
295     virtual int count() const = 0;
296
297     /** Returns the element at index position \a index. */
298     virtual TemplateVariant  at(int index) const = 0;
299
300     /** Creates a new iterator for this list.
301      *  @note the user should call delete on the returned pointer.
302      */
303     virtual TemplateListIntf::ConstIterator *createIterator() const = 0;
304
305     /** Increase object's reference count */
306     virtual int addRef() = 0;
307
308     /** Decreases object's referenc count, destroy object if 0 */
309     virtual int release() = 0;
310 };
311
312 /** @brief Default implementation of a context value of type list. */
313 class TemplateList : public TemplateListIntf
314 {
315   public:
316     // TemplateListIntf methods
317     virtual int  count() const;
318     virtual TemplateVariant at(int index) const;
319     virtual TemplateListIntf::ConstIterator *createIterator() const;
320     virtual int addRef();
321     virtual int release();
322
323     /** Creates an instance with ref count set to 0 */
324     static TemplateList *alloc();
325
326     /** Appends element \a v to the end of the list */
327     virtual void append(const TemplateVariant &v);
328
329   private:
330     /** Creates a list */
331     TemplateList();
332     /** Destroys the list */
333    ~TemplateList();
334
335     friend class TemplateListConstIterator;
336     class Private;
337     Private *p;
338 };
339
340 //------------------------------------------------------------------------
341
342 /** @brief Abstract interface for a context value of type struct. */
343 class TemplateStructIntf
344 {
345   public:
346     /** Destroys the struct */
347     virtual ~TemplateStructIntf() {}
348
349     /** Gets the value for a field name.
350      *  @param[in] name The name of the field.
351      */
352     virtual TemplateVariant get(const char *name) const = 0;
353
354     /** Increase object's reference count */
355     virtual int addRef() = 0;
356
357     /** Decreases object's referenc count, destroy object if 0 */
358     virtual int release() = 0;
359 };
360
361
362 /** @brief Default implementation of a context value of type struct. */
363 class TemplateStruct : public TemplateStructIntf
364 {
365   public:
366     // TemplateStructIntf methods
367     virtual TemplateVariant get(const char *name) const;
368     virtual int addRef();
369     virtual int release();
370
371     /** Creates an instance with ref count set to 0. */
372     static TemplateStruct *alloc();
373
374     /** Sets the value the field of a struct
375      *  @param[in] name The name of the field.
376      *  @param[in] v The value to set.
377      */
378     virtual void set(const char *name,const TemplateVariant &v);
379
380
381   private:
382     /** Creates a struct */
383     TemplateStruct();
384     /** Destroys the struct */
385     virtual ~TemplateStruct();
386
387     class Private;
388     Private *p;
389 };
390
391 //------------------------------------------------------------------------
392
393 /** @brief Interface used to escape characters in a string */
394 class TemplateEscapeIntf
395 {
396   public:
397     /** Returns the \a input after escaping certain characters */
398     virtual QCString escape(const QCString &input) = 0;
399 };
400
401 //------------------------------------------------------------------------
402
403 /** @brief Interface used to remove redundant spaces inside a spaceless block */
404 class TemplateSpacelessIntf
405 {
406   public:
407     /** Returns the \a input after removing redundant whitespace */
408     virtual QCString remove(const QCString &input) = 0;
409     /** Reset filter state */
410     virtual void reset() = 0;
411 };
412
413 //------------------------------------------------------------------------
414
415 /** @brief Abstract interface for a template context.
416  *
417  *  A Context consists of a stack of dictionaries.
418  *  A dictionary consists of a mapping of string keys onto TemplateVariant values.
419  *  A key is searched starting with the dictionary at the top of the stack
420  *  and searching downwards until it is found. The stack is used to create
421  *  local scopes.
422  *  @note This object must be created by TemplateEngine::createContext()
423  */
424 class TemplateContext
425 {
426   public:
427     virtual ~TemplateContext() {}
428
429     /** Push a new scope on the stack. */
430     virtual void push() = 0;
431
432     /** Pop the current scope from the stack. */
433     virtual void pop() = 0;
434
435     /** Sets a value in the current scope.
436      *  @param[in] name The name of the value; the key in the dictionary.
437      *  @param[in] v The value associated with the key.
438      *  @note When a given key is already present,
439      *  its value will be replaced by \a v
440      */
441     virtual void set(const char *name,const TemplateVariant &v) = 0;
442
443     /** Gets the value for a given key
444      *  @param[in] name The name of key.
445      *  @returns The value, which can be an invalid variant in case the
446      *  key was not found.
447      */
448     virtual TemplateVariant get(const QCString &name) const = 0;
449
450     /** Returns a pointer to the value corresponding to a given key.
451      *  @param[in] name The name of key.
452      *  @returns A pointer to the value, or 0 in case the key was not found.
453      */
454     virtual const TemplateVariant *getRef(const QCString &name) const = 0;
455
456     /** When files are create (i.e. by {% create ... %}) they written
457      *  to the directory \a dir.
458      */
459     virtual void setOutputDirectory(const QCString &dir) = 0;
460
461     /** Sets the interface that will be used for escaping the result
462      *  of variable expansion before writing it to the output.
463      */
464     virtual void setEscapeIntf(const QCString &extension, TemplateEscapeIntf *intf) = 0;
465
466     /** Sets the interface that will be used inside a spaceless block
467      *  to remove any redundant whitespace.
468      */
469     virtual void setSpacelessIntf(TemplateSpacelessIntf *intf) = 0;
470 };
471
472 //------------------------------------------------------------------------
473
474 /** @brief Abstract interface for a template.
475  *  @note Must be created and is deleted by the TemplateEngine
476  */
477 class Template
478 {
479   public:
480     /** Destructor */
481     virtual ~Template() {}
482
483     /** Renders a template instance to a stream.
484      *  @param[in] ts The text stream to write the results to.
485      *  @param[in] c The context containing data that can be used
486      *  when instantiating the template.
487      */
488     virtual void render(FTextStream &ts,TemplateContext *c) = 0;
489 };
490
491 //------------------------------------------------------------------------
492
493 /** @brief Engine to create templates and template contexts. */
494 class TemplateEngine
495 {
496   public:
497     /** Create a template engine. */
498     TemplateEngine();
499
500     /** Destroys the template engine. */
501    ~TemplateEngine();
502
503     /** Creates a new context that can be using to render a template.
504      *  @see Template::render()
505      */
506     TemplateContext *createContext() const;
507
508     /** Destroys a context created via createContext().
509      *  @param[in] ctx The context.
510      */
511     void destroyContext(TemplateContext *ctx);
512
513     /** Creates a new template whole contents are in a file.
514      *  @param[in] fileName The name of the file containing the
515      *             template data
516      *  @param[in] fromLine The line number of the statement that triggered the load
517      *  @return the new template, the caller will be the owner.
518      */
519     Template *loadByName(const QCString &fileName,int fromLine);
520
521     /** Indicates that template \a t is no longer needed. The engine
522      *  may decide to delete it.
523      */
524     void unload(Template *t);
525
526     void printIncludeContext(const char *fileName,int line) const;
527
528   private:
529     friend class TemplateNodeBlock;
530     void enterBlock(const QCString &fileName,const QCString &blockName,int line);
531     void leaveBlock();
532
533     class Private;
534     Private *p;
535 };
536
537 /** @} */
538
539 #endif