benchs: protect mangle groups of options in `bench_nitg*_options`
[nit.git] / lib / template.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Basic template system
16 #
17 # The recommended usage of this framework is to define specific subclasses of
18 # Template to provide structural elements on the final document
19 module template
20
21 # Templates are simple hierarchical pieces of text used for efficient stream writing.
22 #
23 # # Efficient stream writing
24 #
25 # Templates are more efficient than ever-growing buffers with useless concatenation
26 # and more usable and maintainable than manual arrays of strings.
27 #
28 # The `add` method (and its variations) is used to append new content (like string or
29 # other templates) to a template object.
30 #
31 # Eventually, the `write_to` method (and its variations) is used to write the complete
32 # content of a template in streams (and files, and strings).
33 #
34 # var tmpl = new Template
35 # tmpl.add("A")
36 # tmpl.add("B")
37 # tmpl.add("C")
38 # assert tmpl.write_to_string == "ABC"
39 #
40 # # Non-linear system with sub-templates.
41 #
42 # A template is made of a mix of string, sub-templates and other `Streamable` objects.
43 # A sub-template can be constructed independently of its usages, thus simplifying
44 # the high-level logic.
45 # A single sub-template can be used more than once.
46 #
47 # var main = new Template
48 # var sub = new Template
49 # sub.add("1")
50 # main.add("A")
51 # main.add(sub)
52 # main.add("B")
53 # main.add(sub)
54 # main.add("C")
55 # sub.add("2")
56 # assert main.write_to_string == "A12B12C"
57 #
58 # See also the `new_sub` method.
59 #
60 # # Specific high-level templates
61 #
62 # The advanced, and recommended way, is to subclass Template and provide an autonomous
63 # structural template with its specific attributes and templating logic.
64 #
65 # In such a subclass, the full logic is provided by the `rendering` method that will
66 # be automatically and lazily invoked.
67 #
68 # class LnkTmpl
69 # super Template
70 # var text: Template
71 # var title: nullable String
72 # var href: String
73 # redef fun rendering do
74 # add """<a href="{{{href.html_escape}}}" """
75 # if title != null then add """title="{{{title.html_escape}}}" """
76 # add ">"
77 # add text
78 # add "</a>"
79 # end
80 # # ...
81 # end
82 #
83 class Template
84 super Streamable
85
86 # Service used to render the content of the template.
87 #
88 # Do nothing by default but subclasses should put all their specific
89 # templating code in this method to regroup and simplify their logic
90 #
91 # Note: to avoid inconsistencies, the template is automatically frozen
92 # (see `freeze`) after the invocation of `rendering`.
93 protected fun rendering do end
94
95 # Append an element (`String`, other `Template`, etc.) at the end of the template.
96 #
97 # Should be either used externally to act on basic templates,
98 # or internally in the `rendering` method of specific templates.
99 #
100 # Mixing the internal and external uses should be avoided because
101 # the final behavior will depend on the lazy invocation of `rendering`.
102 #
103 # var t = new Template
104 # t.add("1")
105 # t.add("2")
106 # assert t.write_to_string == "12"
107 fun add(element: Streamable) do
108 assert not is_frozen
109 content.add element
110 end
111
112 # Append a bunch of elements at the end of the template.
113 # See `add`.
114 #
115 # var t = new Template
116 # t.add_all(["1", "2"])
117 # assert t.write_to_string == "12"
118 fun add_all(elements: Collection[Streamable]) do content.add_all elements
119
120 # Append a bunch of elements at the end of the template with separations.
121 # see `add`.
122 #
123 # var t = new Template
124 # t.add_list(["1", "2", "3"], ", ", " and ")
125 # assert t.write_to_string == "1, 2 and 3"
126 fun add_list(elements: Collection[Streamable], sep, last_sep: Streamable) do
127 var last = elements.length - 2
128 var i = 0
129 for e in elements do
130 content.add e
131 if i < last then
132 content.add sep
133 else if i == last then
134 content.add last_sep
135 end
136 i += 1
137 end
138 end
139
140 # Is the template allowing more modification (`add`)
141 var is_frozen = false
142
143 # Disable further modification: no more `add` is allowed
144 fun freeze
145 do
146 if is_frozen then return
147 is_frozen = true
148 end
149
150 # Return a new basic template that is automatically added in `self` (using `add`)
151 #
152 # This is an easy way to provide a free insertion point in an existing template.
153 #
154 # var t = new Template
155 # t.add("""void main(void) {""")
156 # var tdecl = t.new_sub # used to group declarations
157 # tdecl.add("int i; ")
158 # t.add("i = 1; ")
159 # tdecl.add("int j; ")
160 # t.add("j = i + 1; ")
161 # t.add("\}")
162 # assert t.write_to_string == """void main(void) {int i; int j; i = 1; j = i + 1; }"""
163 fun new_sub: Template
164 do
165 var res = new Template
166 add res
167 return res
168 end
169
170 # Each sub-elements
171 private var content = new Array[Streamable]
172
173 # Flag to avoid multiple rendering
174 private var render_done = false
175
176 # Call rendering, if not already done
177 # Then freeze the template
178 #
179 # This method is only required in corner-cases since
180 # `rendering` is automatically called when needed.
181 fun force_render
182 do
183 if render_done then return
184 render_done = true
185 rendering
186 freeze
187 end
188
189 # Do the full rendering and write the final content to a stream
190 redef fun write_to(stream: OStream)
191 do
192 assert not is_writing
193 is_writing = true
194 force_render
195 for e in content do
196 e.write_to(stream)
197 end
198 is_writing = false
199 end
200
201 # Flag to avoid infinite recursivity if a template contains itself
202 private var is_writing = false
203 end