Debian Codegraph @

lib/mustache/generator.rb

raw symbols SCIP
1 class Mustache
2 # The Generator is in charge of taking an array of Mustache tokens,
3 # usually assembled by the Parser, and generating an interpolatable
4 # Ruby string. This string is considered the "compiled" template
5 # because at that point we're relying on Ruby to do the parsing and
6 # run our code.
7 #
8 # For example, let's take this template:
9 #
10 # Hi {{thing}}!
11 #
12 # If we run this through the Parser we'll get these tokens:
13 #
14 # [:multi,
15 # [:static, "Hi "],
16 # [:mustache, :etag, "thing"],
17 # [:static, "!\n"]]
18 #
19 # Now let's hand that to the Generator:
20 #
21 # >> puts Mustache::Generator.new.compile(tokens)
22 # "Hi #{CGI.escapeHTML(ctx[:thing].to_s)}!\n"
23 #
24 # You can see the generated Ruby string for any template with the
25 # mustache(1) command line tool:
26 #
27 # $ mustache --compile test.mustache
28 # "Hi #{CGI.escapeHTML(ctx[:thing].to_s)}!\n"
29 class Generator
30 # Options can be used to manipulate the resulting ruby code string behavior.
31 def initialize(options = {})
32 @options = options
33 @option_static_lambdas = options[:static_lambdas] == true
34 end
35
36 # Given an array of tokens, returns an interpolatable Ruby string.
37 def compile(exp)
38 "\"#{compile!(exp)}\""
39 end
40
41
42 private
43
44
45 # Given an array of tokens, converts them into Ruby code. In
46 # particular there are three types of expressions we are concerned
47 # with:
48 #
49 # :multi
50 # Mixed bag of :static, :mustache, and whatever.
51 #
52 # :static
53 # Normal HTML, the stuff outside of {{mustaches}}.
54 #
55 # :mustache
56 # Any Mustache tag, from sections to partials.
57 #
58 # To give you an idea of what you'll be dealing with take this
59 # template:
60 #
61 # Hello {{name}}
62 # You have just won ${{value}}!
63 # {{#in_ca}}
64 # Well, ${{taxed_value}}, after taxes.
65 # {{/in_ca}}
66 #
67 # If we run this through the Parser, we'll get back this array of
68 # tokens:
69 #
70 # [:multi,
71 # [:static, "Hello "],
72 # [:mustache, :etag,
73 # [:mustache, :fetch, ["name"]]],
74 # [:static, "\nYou have just won $"],
75 # [:mustache, :etag,
76 # [:mustache, :fetch, ["value"]]],
77 # [:static, "!\n"],
78 # [:mustache,
79 # :section,
80 # [:mustache, :fetch, ["in_ca"]],
81 # [:multi,
82 # [:static, "Well, $"],
83 # [:mustache, :etag,
84 # [:mustache, :fetch, ["taxed_value"]]],
85 # [:static, ", after taxes.\n"]],
86 # "Well, ${{taxed_value}}, after taxes.\n",
87 # ["{{", "}}"]]]
88 def compile!(exp)
89 case exp.first
90 when :multi
91 exp[1..-1].reduce("".dup) { |sum, e| sum << compile!(e) }
92 when :static
93 str(exp[1])
94 when :mustache
95 send("on_#{exp[1]}", *exp[2..-1])
96 else
97 raise "Unhandled exp: #{exp.first}"
98 end
99 end
100
101 # Callback fired when the compiler finds a section token. We're
102 # passed the section name and the array of tokens.
103 def on_section(name, offset, content, raw, delims)
104 # Convert the tokenized content of this section into a Ruby
105 # string we can use.
106 code = compile(content)
107
108 # Lambda handling - default handling is to dynamically interpret
109 # the returned lambda result as mustache source
110 proc_handling = if @option_static_lambdas
111 <<-compiled
112 v.call(lambda {|v| #{code}}.call(v)).to_s
113 compiled
114 else
115 <<-compiled
116 t = Mustache::Template.new(v.call(#{raw.inspect}).to_s)
117 def t.tokens(src=@source)
118 p = Mustache::Parser.new
119 p.otag, p.ctag = #{delims.inspect}
120 p.compile(src)
121 end
122 t.render(ctx.dup)
123 compiled
124 end
125
126 # Compile the Ruby for this section now that we know what's
127 # inside the section.
128 ev(<<-compiled)
129 case v = #{compile!(name)}
130 when NilClass, FalseClass
131 when TrueClass
132 #{code}
133 when Proc
134 #{proc_handling}
135 when Array, Enumerator, Mustache::Enumerable
136 v.map { |_| ctx.push(_); r = #{code}; ctx.pop; r }.join
137 else
138 ctx.push(v); r = #{code}; ctx.pop; r
139 end
140 compiled
141 end
142
143 # Fired when we find an inverted section. Just like `on_section`,
144 # we're passed the inverted section name and the array of tokens.
145 def on_inverted_section(name, offset, content, raw, delims)
146 # Convert the tokenized content of this section into a Ruby
147 # string we can use.
148 code = compile(content)
149
150 # Compile the Ruby for this inverted section now that we know
151 # what's inside.
152 ev(<<-compiled)
153 v = #{compile!(name)}
154 if v.nil? || v == false || v.respond_to?(:empty?) && v.empty?
155 #{code}
156 end
157 compiled
158 end
159
160 # Fired when the compiler finds a partial. We want to return code
161 # which calls a partial at runtime instead of expanding and
162 # including the partial's body to allow for recursive partials.
163 def on_partial(name, offset, indentation)
164 ev("ctx.partial(#{name.to_sym.inspect}, #{indentation.inspect})")
165 end
166
167 # An unescaped tag.
168 def on_utag(name, offset)
169 ev(<<-compiled)
170 v = #{compile!(name)}
171 if v.is_a?(Proc)
172 v = #{@option_static_lambdas ? 'v.call' : 'Mustache::Template.new(v.call.to_s).render(ctx.dup)'}
173 end
174 v.to_s
175 compiled
176 end
177
178 # An escaped tag.
179 def on_etag(name, offset)
180 ev(<<-compiled)
181 v = #{compile!(name)}
182 if v.is_a?(Proc)
183 v = #{@option_static_lambdas ? 'v.call' : 'Mustache::Template.new(v.call.to_s).render(ctx.dup)'}
184 end
185 ctx.escape(v)
186 compiled
187 end
188
189 def on_fetch(names)
190 return "ctx.current" if names.empty?
191
192 names = names.map { |n| n.to_sym }
193
194 initial, *rest = names
195 if rest.any?
196 <<-compiled
197 #{rest.inspect}.reduce(ctx[#{initial.inspect}]) { |value, key| value && ctx.find(value, key) }
198 compiled
199 else
200 <<-compiled
201 ctx[#{initial.inspect}]
202 compiled
203 end
204 end
205
206 # An interpolation-friendly version of a string, for use within a
207 # Ruby string.
208 def ev(s)
209 "#\{#{s}}"
210 end
211
212 def str(s)
213 s.inspect[1..-2]
214 end
215 end
216 end