Class: Mustache::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/mustache/parser.rb

Overview

The Parser is responsible for taking a string template and converting it into an array of tokens and, really, expressions. It raises SyntaxError if there is anything it doesn’t understand and knows which sigil corresponds to which tag type.

For example, given this template:

Hi {{thing}}!

Run through the Parser we’ll get these tokens:

[:multi,
  [:static, "Hi "],
  [:mustache, :etag, "thing"],
  [:static, "!\n"]]

You can see the array of tokens for any template with the mustache(1) command line tool:

$ mustache --tokens test.mustache
[:multi, [:static, "Hi "], [:mustache, :etag, "thing"], [:static, "!\n"]]

Defined Under Namespace

Classes: SyntaxError

Constant Summary collapse

SKIP_WHITESPACE =

After these types of tags, all whitespace will be skipped.

[ '#', '/' ]
ALLOWED_CONTENT =

The content allowed in a tag name.

/(\w|[?!-])*/
ANY_CONTENT =

These types of tags allow any content, the rest only allow ALLOWED_CONTENT.

[ '!', '=' ]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Parser

Accepts an options hash which does nothing but may be used in the future.



62
63
64
# File 'lib/mustache/parser.rb', line 62

def initialize(options = {})
  @options = {}
end

Instance Attribute Details

#ctagObject

The closing tag delimiter. This too may be changed at runtime.



72
73
74
# File 'lib/mustache/parser.rb', line 72

def ctag
  @ctag ||= '}}'
end

#otagObject

The opening tag delimiter. This may be changed at runtime.



67
68
69
# File 'lib/mustache/parser.rb', line 67

def otag
  @otag ||= '{{'
end

#resultObject (readonly)

Returns the value of attribute result.



57
58
59
# File 'lib/mustache/parser.rb', line 57

def result
  @result
end

#scannerObject (readonly)

Returns the value of attribute scanner.



57
58
59
# File 'lib/mustache/parser.rb', line 57

def scanner
  @scanner
end

Instance Method Details

#compile(template) ⇒ Object

Given a string template, returns an array of tokens.



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/mustache/parser.rb', line 77

def compile(template)
  # Keeps information about opened sections.
  @sections = []
  @result = [:multi]
  @scanner = StringScanner.new(template)

  # Scan until the end of the template.
  until @scanner.eos?
    scan_tags || scan_text
  end

  if !@sections.empty?
    # We have parsed the whole file, but there's still opened sections.
    type, pos, result = @sections.pop
    error "Unclosed section #{type.inspect}", pos
  end

  @result
end

#error(message, pos = position) ⇒ Object

Raises a SyntaxError. The message should be the name of the error - other details such as line number and position are handled for you.

Raises:



212
213
214
# File 'lib/mustache/parser.rb', line 212

def error(message, pos = position)
  raise SyntaxError.new(message, pos)
end

#positionObject

Returns [lineno, column, line]



191
192
193
194
195
196
197
198
199
200
201
# File 'lib/mustache/parser.rb', line 191

def position
  # The rest of the current line
  rest = @scanner.check_until(/\n|\Z/).to_s.chomp

  # What we have parsed so far
  parsed = @scanner.string[0...@scanner.pos]

  lines = parsed.split("\n")

  [ lines.size, lines.last.size - 1, lines.last + rest ]
end

#regexp(thing) ⇒ Object

Used to quickly convert a string into a regular expression usable by the string scanner.



205
206
207
# File 'lib/mustache/parser.rb', line 205

def regexp(thing)
  /#{Regexp.escape(thing)}/
end

#scan_tagsObject

Find {mustaches} and add them to the @result array.



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/mustache/parser.rb', line 98

def scan_tags
  # Scan until we hit an opening delimiter.
  return unless @scanner.scan(regexp(otag))

  # Since {{= rewrites ctag, we store the ctag which should be used
  # when parsing this specific tag.
  current_ctag = self.ctag
  type = @scanner.scan(/#|\/|=|!|<|>|&|\{/)
  @scanner.skip(/\s*/)

  # ANY_CONTENT tags allow any character inside of them, while
  # other tags (such as variables) are more strict.
  if ANY_CONTENT.include?(type)
    r = /\s*#{regexp(type)}?#{regexp(current_ctag)}/
    content = scan_until_exclusive(r)
  else
    content = @scanner.scan(ALLOWED_CONTENT)
  end

  # We found {{ but we can't figure out what's going on inside.
  error "Illegal content in tag" if content.empty?

  # Based on the sigil, do what needs to be done.
  case type
  when '#'
    block = [:multi]
    @result << [:mustache, :section, content, block]
    @sections << [content, position, @result]
    @result = block
  when '/'
    section, pos, result = @sections.pop
    @result = result

    if section.nil?
      error "Closing unopened #{content.inspect}"
    elsif section != content
      error "Unclosed section #{section.inspect}", pos
    end
  when '!'
    # ignore comments
  when '='
    self.otag, self.ctag = content.split(' ', 2)
  when '>', '<'
    @result << [:mustache, :partial, content]
  when '{', '&'
    # The closing } in unescaped tags is just a hack for
    # aesthetics.
    type = "}" if type == "{"
    @result << [:mustache, :utag, content]
  else
    @result << [:mustache, :etag, content]
  end

  # Skip whitespace and any balancing sigils after the content
  # inside this tag.
  @scanner.skip(/\s+/)
  @scanner.skip(regexp(type)) if type

  # Try to find the closing tag.
  unless close = @scanner.scan(regexp(current_ctag))
    error "Unclosed tag"
  end

  # Skip whitespace following this tag if we need to.
  @scanner.skip(/\s+/) if SKIP_WHITESPACE.include?(type)
end

#scan_textObject

Try to find static text, e.g. raw HTML with no {mustaches}.



166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/mustache/parser.rb', line 166

def scan_text
  text = scan_until_exclusive(regexp(otag))

  if text.nil?
    # Couldn't find any otag, which means the rest is just static text.
    text = @scanner.rest
    # Mark as done.
    @scanner.clear
  end

  @result << [:static, text]
end

#scan_until_exclusive(regexp) ⇒ Object

Scans the string until the pattern is matched. Returns the substring excluding the end of the match, advancing the scan pointer to that location. If there is no match, nil is returned.



182
183
184
185
186
187
188
# File 'lib/mustache/parser.rb', line 182

def scan_until_exclusive(regexp)
  pos = @scanner.pos
  if @scanner.scan_until(regexp)
    @scanner.pos -= @scanner.matched.size
    @scanner.pre_match[pos..-1]
  end
end