Debian Codegraph @

lib/mustache/parser.rb

raw symbols SCIP
1 require 'strscan'
2
3 class Mustache
4 # The Parser is responsible for taking a string template and
5 # converting it into an array of tokens and, really, expressions. It
6 # raises SyntaxError if there is anything it doesn't understand and
7 # knows which sigil corresponds to which tag type.
8 #
9 # For example, given this template:
10 #
11 # Hi {{thing}}!
12 #
13 # Run through the Parser we'll get these tokens:
14 #
15 # [:multi,
16 # [:static, "Hi "],
17 # [:mustache, :etag, "thing"],
18 # [:static, "!\n"]]
19 #
20 # You can see the array of tokens for any template with the
21 # mustache(1) command line tool:
22 #
23 # $ mustache --tokens test.mustache
24 # [:multi, [:static, "Hi "], [:mustache, :etag, "thing"], [:static, "!\n"]]
25 class Parser
26 # A SyntaxError is raised when the Parser comes across unclosed
27 # tags, sections, illegal content in tags, or anything of that
28 # sort.
29 class SyntaxError < StandardError
30 def initialize(message, position)
31 @message = message
32 @lineno, @column, @line, _ = position
33 @stripped_line = @line.strip
34 @stripped_column = @column - (@line.size - @line.lstrip.size)
35 end
36
37 def to_s
38 <<-EOF
39 #{@message}
40 Line #{@lineno}
41 #{@stripped_line}
42 #{' ' * @stripped_column}^
43 EOF
44 end
45 end
46
47 # The sigil types which are valid after an opening `{{`
48 VALID_TYPES = [ '#', '^', '/', '=', '!', '<', '>', '&', '{' ].map(&:freeze)
49
50 def self.valid_types
51 @valid_types ||= Regexp.new(VALID_TYPES.map { |t| Regexp.escape(t) }.join('|') )
52 end
53
54 # Add a supported sigil type (with optional aliases) to the Parser.
55 #
56 # Requires a block, which will be sent the following parameters:
57 #
58 # * content - The raw content of the tag
59 # * fetch- A mustache context fetch expression for the content
60 # * padding - Indentation whitespace from the currently-parsed line
61 # * pre_match_position - Location of the scanner before a match was made
62 #
63 # The provided block will be evaluated against the current instance of
64 # Parser, and may append to the Parser's @result as needed.
65 def self.add_type(*types, &block)
66 types = types.map(&:to_s)
67 type, *aliases = types
68 method_name = "scan_tag_#{type}".to_sym
69 define_method(method_name, &block)
70 aliases.each { |a| alias_method "scan_tag_#{a}", method_name }
71 types.each { |t| VALID_TYPES << t unless VALID_TYPES.include?(t) }
72 @valid_types = nil
73 end
74
75 # After these types of tags, all whitespace until the end of the line will
76 # be skipped if they are the first (and only) non-whitespace content on
77 # the line.
78 SKIP_WHITESPACE = [ '#', '^', '/', '<', '>', '=', '!' ].map(&:freeze)
79
80 # The content allowed in a tag name.
81 ALLOWED_CONTENT = /(\w|[?!\/.-])*/
82
83 # These types of tags allow any content,
84 # the rest only allow ALLOWED_CONTENT.
85 ANY_CONTENT = [ '!', '=' ].map(&:freeze)
86
87 attr_reader :otag, :ctag
88
89 # Accepts an options hash which does nothing but may be used in
90 # the future.
91 def initialize(options = {})
92 @options = options
93 @option_inline_partials_at_compile_time = options[:inline_partials_at_compile_time]
94 if @option_inline_partials_at_compile_time
95 @partial_resolver = options[:partial_resolver]
96 raise ArgumentError.new "Missing or invalid partial_resolver" unless @partial_resolver.respond_to? :call
97 end
98
99 # Initialize default tags
100 self.otag ||= '{{'
101 self.ctag ||= '}}'
102 end
103
104 # The opening tag delimiter. This may be changed at runtime.
105 def otag=(value)
106 regex = regexp value
107 @otag_regex = /([ \t]*)?#{regex}/
108 @otag_not_regex = /(^[ \t]*)?#{regex}/
109 @otag = value
110 end
111
112 # The closing tag delimiter. This too may be changed at runtime.
113 def ctag=(value)
114 @ctag_regex = regexp value
115 @ctag = value
116 end
117
118 # Given a string template, returns an array of tokens.
119 def compile(template)
120 @encoding = nil
121
122 if template.respond_to?(:encoding)
123 @encoding = template.encoding
124 template = template.dup.force_encoding("BINARY")
125 end
126
127 # Keeps information about opened sections.
128 @sections = []
129 @result = [:multi]
130 @scanner = StringScanner.new(template)
131
132 # Scan until the end of the template.
133 until @scanner.eos?
134 scan_tags || scan_text
135 end
136
137 unless @sections.empty?
138 # We have parsed the whole file, but there's still opened sections.
139 type, pos, _ = @sections.pop
140 error "Unclosed section #{type.inspect}", pos
141 end
142
143 @result
144 end
145
146
147 private
148
149
150 def content_tags type, current_ctag_regex
151 if ANY_CONTENT.include?(type)
152 r = /\s*#{regexp(type)}?#{current_ctag_regex}/
153 scan_until_exclusive(r)
154 else
155 @scanner.scan(ALLOWED_CONTENT)
156 end
157 end
158
159 def dispatch_based_on_type type, content, fetch, padding, pre_match_position
160 send("scan_tag_#{type}", content, fetch, padding, pre_match_position)
161 end
162
163 def find_closing_tag scanner, current_ctag_regex
164 error "Unclosed tag" unless scanner.scan(current_ctag_regex)
165 end
166
167 # Find {{mustaches}} and add them to the @result array.
168 def scan_tags
169 # Scan until we hit an opening delimiter.
170 start_of_line = @scanner.beginning_of_line?
171 pre_match_position = @scanner.pos
172 last_index = @result.length
173
174 return unless @scanner.scan @otag_regex
175 padding = @scanner[1] || ''
176
177 # Don't touch the preceding whitespace unless we're matching the start
178 # of a new line.
179 unless start_of_line
180 @result << [:static, padding] unless padding.empty?
181 pre_match_position += padding.length
182 padding = ''
183 end
184
185 # Since {{= rewrites ctag, we store the ctag which should be used
186 # when parsing this specific tag.
187 current_ctag_regex = @ctag_regex
188 type = @scanner.scan(self.class.valid_types)
189 @scanner.skip(/\s*/)
190
191 # ANY_CONTENT tags allow any character inside of them, while
192 # other tags (such as variables) are more strict.
193 content = content_tags(type, current_ctag_regex)
194
195 # We found {{ but we can't figure out what's going on inside.
196 error "Illegal content in tag" if content.empty?
197
198 fetch = [:mustache, :fetch, content.split('.')]
199 prev = @result
200
201 dispatch_based_on_type(type, content, fetch, padding, pre_match_position)
202
203 # The closing } in unescaped tags is just a hack for
204 # aesthetics.
205 type = "}" if type == "{"
206
207 # Skip whitespace and any balancing sigils after the content
208 # inside this tag.
209 @scanner.skip(/\s+/)
210 @scanner.skip(regexp(type)) if type
211
212 find_closing_tag(@scanner, current_ctag_regex)
213
214 # If this tag was the only non-whitespace content on this line, strip
215 # the remaining whitespace. If not, but we've been hanging on to padding
216 # from the beginning of the line, re-insert the padding as static text.
217 if start_of_line && !@scanner.eos?
218 if @scanner.peek(2) =~ /\r?\n/ && SKIP_WHITESPACE.include?(type)
219 @scanner.skip(/\r?\n/)
220 else
221 prev.insert(last_index, [:static, padding]) unless padding.empty?
222 end
223 end
224
225 # Store off the current scanner position now that we've closed the tag
226 # and consumed any irrelevant whitespace.
227 @sections.last[1] << @scanner.pos unless @sections.empty?
228
229 return unless @result == [:multi]
230 end
231
232 # Try to find static text, e.g. raw HTML with no {{mustaches}}.
233 def scan_text
234 text = scan_until_exclusive @otag_not_regex
235
236 if text.nil?
237 # Couldn't find any otag, which means the rest is just static text.
238 text = @scanner.rest
239 # Mark as done.
240 @scanner.terminate
241 end
242
243 text.force_encoding(@encoding) if @encoding
244
245 @result << [:static, text] unless text.empty?
246 end
247
248 # Scans the string until the pattern is matched. Returns the substring
249 # *excluding* the end of the match, advancing the scan pointer to that
250 # location. If there is no match, nil is returned.
251 def scan_until_exclusive(regexp)
252 pos = @scanner.pos
253 if @scanner.scan_until(regexp)
254 @scanner.pos -= @scanner.matched.size
255 @scanner.pre_match[pos..-1]
256 end
257 end
258
259 def offset
260 position[0, 2]
261 end
262
263 # Returns [lineno, column, line]
264 def position
265 # The rest of the current line
266 rest = @scanner.check_until(/\n|\Z/).to_s.chomp
267
268 # What we have parsed so far
269 parsed = @scanner.string[0...@scanner.pos]
270
271 lines = parsed.split("\n")
272
273 [ lines.size, lines.last.size - 1, lines.last + rest ]
274 end
275
276 # Used to quickly convert a string into a regular expression
277 # usable by the string scanner.
278 def regexp(thing)
279 Regexp.new Regexp.escape(thing) if thing
280 end
281
282 # Raises a SyntaxError. The message should be the name of the
283 # error - other details such as line number and position are
284 # handled for you.
285 def error(message, pos = position)
286 raise SyntaxError.new(message, pos)
287 end
288
289
290 #
291 # Scan tags
292 #
293 # These methods are called in `scan_tags`. Because they contain nonstandard
294 # characters in their method names, they are aliased to
295 # better named methods.
296 #
297
298
299 # This function handles the cases where the scanned tag does not have
300 # a type.
301 def scan_tag_ content, fetch, padding, pre_match_position
302 @result << [:mustache, :etag, fetch, offset]
303 end
304
305
306 def scan_tag_block content, fetch, padding, pre_match_position
307 block = [:multi]
308 @result << [:mustache, :section, fetch, offset, block]
309 @sections << [content, position, @result]
310 @result = block
311 end
312 alias_method :'scan_tag_#', :scan_tag_block
313
314
315 def scan_tag_inverted content, fetch, padding, pre_match_position
316 block = [:multi]
317 @result << [:mustache, :inverted_section, fetch, offset, block]
318 @sections << [content, position, @result]
319 @result = block
320 end
321 alias_method :'scan_tag_^', :scan_tag_inverted
322
323
324 def scan_tag_close content, fetch, padding, pre_match_position
325 section, pos, result = @sections.pop
326 if section.nil?
327 error "Closing unopened #{content.inspect}"
328 end
329
330 raw = @scanner.pre_match[pos[3]...pre_match_position] + padding
331 (@result = result).last << raw << [self.otag, self.ctag]
332
333 if section != content
334 error "Unclosed section #{section.inspect}", pos
335 end
336 end
337 alias_method :'scan_tag_/', :scan_tag_close
338
339
340 def scan_tag_comment content, fetch, padding, pre_match_position
341 end
342 alias_method :'scan_tag_!', :scan_tag_comment
343
344
345 def scan_tag_delimiter content, fetch, padding, pre_match_position
346 self.otag, self.ctag = content.split(' ', 2)
347 end
348 alias_method :'scan_tag_=', :scan_tag_delimiter
349
350
351 def scan_tag_open_partial content, fetch, padding, pre_match_position
352 @result << if @option_inline_partials_at_compile_time
353 partial = @partial_resolver.call content
354 partial.gsub!(/^/, padding) unless padding.empty?
355 self.class.new(@options).compile partial
356 else
357 [:mustache, :partial, content, offset, padding]
358 end
359 end
360 alias_method :'scan_tag_<', :scan_tag_open_partial
361 alias_method :'scan_tag_>', :scan_tag_open_partial
362
363
364 def scan_tag_unescaped content, fetch, padding, pre_match_position
365 @result << [:mustache, :utag, fetch, offset]
366 end
367 alias_method :'scan_tag_{', :'scan_tag_unescaped'
368 alias_method :'scan_tag_&', :'scan_tag_unescaped'
369
370 end
371 end