blob: f472d4ba56631e93318b886b14b96f36fae48d49 [file] [log] [blame]
Armin Ronacher92f572f2007-02-26 22:17:32 +01001# -*- coding: utf-8 -*-
2"""
Armin Ronacher07bc6842008-03-31 14:18:49 +02003 jinja2.lexer
4 ~~~~~~~~~~~~
Armin Ronacher3b65b8a2007-02-27 20:21:45 +01005
Armin Ronacher5a8e4972007-04-05 11:21:38 +02006 This module implements a Jinja / Python combination lexer. The
7 `Lexer` class provided by this module is used to do some preprocessing
8 for Jinja.
9
10 On the one hand it filters out invalid operators like the bitshift
11 operators we don't allow in templates. On the other hand it separates
12 template code and python code in expressions.
13
Armin Ronacher1d51f632008-03-25 14:34:45 +010014 :copyright: 2007-2008 by Armin Ronacher.
Armin Ronacher3b65b8a2007-02-27 20:21:45 +010015 :license: BSD, see LICENSE for more details.
Armin Ronacher92f572f2007-02-26 22:17:32 +010016"""
17import re
Armin Ronacher1cc232c2007-09-07 17:52:41 +020018import unicodedata
Armin Ronacher4325e372008-05-01 22:59:47 +020019from operator import itemgetter
20from collections import deque
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020021from jinja2.exceptions import TemplateSyntaxError
Armin Ronacherb5124e62008-04-25 00:36:14 +020022from jinja2.utils import LRUCache
Armin Ronacher92f572f2007-02-26 22:17:32 +010023
24
Armin Ronacher21580912007-04-17 17:13:10 +020025# cache for the lexers. Exists in order to be able to have multiple
26# environments with the same lexer
Armin Ronacher187bde12008-05-01 18:19:16 +020027_lexer_cache = LRUCache(50)
Armin Ronacher21580912007-04-17 17:13:10 +020028
Armin Ronacher92f572f2007-02-26 22:17:32 +010029# static regular expressions
Armin Ronacher0949e4d2007-10-07 18:53:29 +020030whitespace_re = re.compile(r'\s+(?um)')
Armin Ronacher92f572f2007-02-26 22:17:32 +010031string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')
Armin Ronacher1cc232c2007-09-07 17:52:41 +020033integer_re = re.compile(r'\d+')
Armin Ronacherb5365482008-05-11 00:18:35 +020034name_re = re.compile(r'\b[^\W\d]\w*\b(?u)')
Armin Ronacher1cc232c2007-09-07 17:52:41 +020035float_re = re.compile(r'\d+\.\d+')
Armin Ronacher92f572f2007-02-26 22:17:32 +010036
Armin Ronacher1cc232c2007-09-07 17:52:41 +020037# bind operators to token types
38operators = {
39 '+': 'add',
40 '-': 'sub',
41 '/': 'div',
42 '//': 'floordiv',
43 '*': 'mul',
44 '%': 'mod',
45 '**': 'pow',
46 '~': 'tilde',
Armin Ronacher1cc232c2007-09-07 17:52:41 +020047 '[': 'lbracket',
48 ']': 'rbracket',
49 '(': 'lparen',
50 ')': 'rparen',
51 '{': 'lbrace',
52 '}': 'rbrace',
53 '==': 'eq',
54 '!=': 'ne',
55 '>': 'gt',
56 '>=': 'gteq',
57 '<': 'lt',
58 '<=': 'lteq',
59 '=': 'assign',
60 '.': 'dot',
61 ':': 'colon',
62 '|': 'pipe',
Armin Ronacher07bc6842008-03-31 14:18:49 +020063 ',': 'comma',
64 ';': 'semicolon'
Armin Ronacher1cc232c2007-09-07 17:52:41 +020065}
66
67reverse_operators = dict([(v, k) for k, v in operators.iteritems()])
68assert len(operators) == len(reverse_operators), 'operators dropped'
Armin Ronachere791c2a2008-04-07 18:39:54 +020069operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in
70 sorted(operators, key=lambda x: -len(x))))
Armin Ronacher1cc232c2007-09-07 17:52:41 +020071
Armin Ronacher1d51f632008-03-25 14:34:45 +010072simple_escapes = {
73 'a': '\a',
74 'n': '\n',
75 'r': '\r',
76 'f': '\f',
77 't': '\t',
78 'v': '\v',
79 '\\': '\\',
80 '"': '"',
81 "'": "'",
82 '0': '\x00'
83}
84unicode_escapes = {
85 'x': 2,
86 'u': 4,
87 'U': 8
88}
89
Armin Ronacher1cc232c2007-09-07 17:52:41 +020090
Armin Ronacherb5365482008-05-11 00:18:35 +020091def _trystr(s):
92 try:
93 return str(s)
94 except UnicodeError:
95 return s
96
97
Armin Ronacher1cc232c2007-09-07 17:52:41 +020098def unescape_string(lineno, filename, s):
Armin Ronacherb5124e62008-04-25 00:36:14 +020099 r"""Unescape a string. Supported escapes:
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200100 \a, \n, \r\, \f, \v, \\, \", \', \0
101
102 \x00, \u0000, \U00000000, \N{...}
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200103 """
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200104 try:
Armin Ronacherb5365482008-05-11 00:18:35 +0200105 return _trystr(s.encode('ascii', 'backslashreplace')
106 .decode('unicode-escape'))
Armin Ronacherb5124e62008-04-25 00:36:14 +0200107 except UnicodeError, e:
108 msg = str(e).split(':')[-1].strip()
109 raise TemplateSyntaxError(msg, lineno, filename)
Armin Ronacher2894f222007-03-19 22:39:55 +0100110
Armin Ronacher92f572f2007-02-26 22:17:32 +0100111
112class Failure(object):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200113 """Class that raises a `TemplateSyntaxError` if called.
Armin Ronacher92f572f2007-02-26 22:17:32 +0100114 Used by the `Lexer` to specify known errors.
115 """
116
117 def __init__(self, message, cls=TemplateSyntaxError):
118 self.message = message
119 self.error_class = cls
120
Armin Ronacher720e55b2007-05-30 00:57:49 +0200121 def __call__(self, lineno, filename):
122 raise self.error_class(self.message, lineno, filename)
Armin Ronacher92f572f2007-02-26 22:17:32 +0100123
124
Armin Ronacher4325e372008-05-01 22:59:47 +0200125class Token(tuple):
126 """Token class."""
127 __slots__ = ()
128 lineno, type, value = (property(itemgetter(x)) for x in range(3))
129
130 def __new__(cls, lineno, type, value):
131 return tuple.__new__(cls, (lineno, intern(str(type)), value))
132
133 def __str__(self):
134 from jinja.lexer import keywords, reverse_operators
135 if self.type in keywords:
136 return self.type
137 elif self.type in reverse_operators:
138 return reverse_operators[self.type]
139 elif self.type is 'name':
140 return self.value
141 return self.type
142
143 def test(self, expr):
144 """Test a token against a token expression. This can either be a
Armin Ronacher023b5e92008-05-08 11:03:10 +0200145 token type or ``'token_type:token_value'``. This can only test
146 against string values and types.
Armin Ronacher4325e372008-05-01 22:59:47 +0200147 """
Armin Ronachercda43df2008-05-03 17:10:05 +0200148 # here we do a regular string equality check as test_any is usually
Armin Ronacher4325e372008-05-01 22:59:47 +0200149 # passed an iterable of not interned strings.
150 if self.type == expr:
151 return True
152 elif ':' in expr:
153 return expr.split(':', 1) == [self.type, self.value]
154 return False
155
Armin Ronachercda43df2008-05-03 17:10:05 +0200156 def test_any(self, *iterable):
Armin Ronacher4325e372008-05-01 22:59:47 +0200157 """Test against multiple token expressions."""
158 for expr in iterable:
159 if self.test(expr):
160 return True
161 return False
162
163 def __repr__(self):
164 return 'Token(%r, %r, %r)' % (
165 self.lineno,
166 self.type,
167 self.value
168 )
169
170
171class TokenStreamIterator(object):
172 """The iterator for tokenstreams. Iterate over the stream
173 until the eof token is reached.
174 """
175
176 def __init__(self, stream):
177 self._stream = stream
178
179 def __iter__(self):
180 return self
181
182 def next(self):
183 token = self._stream.current
184 if token.type == 'eof':
185 self._stream.close()
186 raise StopIteration()
187 self._stream.next(False)
188 return token
189
190
191class TokenStream(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200192 """A token stream is an iterable that yields :class:`Token`\s. The
193 parser however does not iterate over it but calls :meth:`next` to go
194 one token ahead. The current active token is stored as :attr:`current`.
Armin Ronacher4325e372008-05-01 22:59:47 +0200195 """
196
197 def __init__(self, generator, filename):
198 self._next = generator.next
199 self._pushed = deque()
200 self.current = Token(1, 'initial', '')
201 self.filename = filename
202 self.next()
203
204 def __iter__(self):
205 return TokenStreamIterator(self)
206
207 def __nonzero__(self):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200208 """Are we at the end of the stream?"""
Armin Ronacher4325e372008-05-01 22:59:47 +0200209 return bool(self._pushed) or self.current.type != 'eof'
210
211 eos = property(lambda x: not x.__nonzero__(), doc=__nonzero__.__doc__)
212
213 def push(self, token):
214 """Push a token back to the stream."""
215 self._pushed.append(token)
216
217 def look(self):
218 """Look at the next token."""
219 old_token = self.next()
220 result = self.current
221 self.push(result)
222 self.current = old_token
223 return result
224
Armin Ronacherea847c52008-05-02 20:04:32 +0200225 def skip(self, n=1):
Armin Ronacher4325e372008-05-01 22:59:47 +0200226 """Got n tokens ahead."""
227 for x in xrange(n):
228 self.next()
229
230 def next(self, skip_eol=True):
231 """Go one token ahead and return the old one"""
232 rv = self.current
233 while 1:
234 if self._pushed:
235 self.current = self._pushed.popleft()
236 elif self.current.type is not 'eof':
237 try:
238 self.current = self._next()
239 except StopIteration:
240 self.close()
241 if not skip_eol or self.current.type is not 'eol':
242 break
243 return rv
244
245 def close(self):
246 """Close the stream."""
247 self.current = Token(self.current.lineno, 'eof', '')
248 self._next = None
249
250 def expect(self, expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200251 """Expect a given token type and return it. This accepts the same
252 argument as :meth:`jinja2.lexer.Token.test`.
253 """
Armin Ronacher4325e372008-05-01 22:59:47 +0200254 if not self.current.test(expr):
255 if ':' in expr:
256 expr = expr.split(':')[1]
257 if self.current.type is 'eof':
258 raise TemplateSyntaxError('unexpected end of template, '
259 'expected %r.' % expr,
260 self.current.lineno,
261 self.filename)
262 raise TemplateSyntaxError("expected token %r, got %r" %
263 (expr, str(self.current)),
264 self.current.lineno,
265 self.filename)
266 try:
267 return self.current
268 finally:
269 self.next()
270
271
Armin Ronacher21580912007-04-17 17:13:10 +0200272class LexerMeta(type):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200273 """Metaclass for the lexer that caches instances for
Armin Ronacher21580912007-04-17 17:13:10 +0200274 the same configuration in a weak value dictionary.
275 """
276
277 def __call__(cls, environment):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200278 key = (environment.block_start_string,
279 environment.block_end_string,
280 environment.variable_start_string,
281 environment.variable_end_string,
282 environment.comment_start_string,
283 environment.comment_end_string,
284 environment.line_statement_prefix,
285 environment.trim_blocks)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200286 lexer = _lexer_cache.get(key)
287 if lexer is None:
288 lexer = type.__call__(cls, environment)
289 _lexer_cache[key] = lexer
Armin Ronacher21580912007-04-17 17:13:10 +0200290 return lexer
291
292
Armin Ronacher92f572f2007-02-26 22:17:32 +0100293class Lexer(object):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200294 """Class that implements a lexer for a given environment. Automatically
Armin Ronacher92f572f2007-02-26 22:17:32 +0100295 created by the environment class, usually you don't have to do that.
Armin Ronacher21580912007-04-17 17:13:10 +0200296
297 Note that the lexer is not automatically bound to an environment.
298 Multiple environments can share the same lexer.
Armin Ronacher92f572f2007-02-26 22:17:32 +0100299 """
300
Armin Ronacher21580912007-04-17 17:13:10 +0200301 __metaclass__ = LexerMeta
302
Armin Ronacher92f572f2007-02-26 22:17:32 +0100303 def __init__(self, environment):
304 # shortcuts
305 c = lambda x: re.compile(x, re.M | re.S)
306 e = re.escape
307
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200308 # lexing rules for tags
Armin Ronacher92f572f2007-02-26 22:17:32 +0100309 tag_rules = [
310 (whitespace_re, None, None),
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200311 (float_re, 'float', None),
312 (integer_re, 'integer', None),
Armin Ronacher92f572f2007-02-26 22:17:32 +0100313 (name_re, 'name', None),
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200314 (string_re, 'string', None),
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200315 (operator_re, 'operator', None)
Armin Ronacher92f572f2007-02-26 22:17:32 +0100316 ]
317
Armin Ronacherd874fbe2007-02-27 20:51:59 +0100318 # assamble the root lexing rule. because "|" is ungreedy
319 # we have to sort by length so that the lexer continues working
320 # as expected when we have parsing rules like <% for block and
321 # <%= for variables. (if someone wants asp like syntax)
Armin Ronacher33d528a2007-05-14 18:21:44 +0200322 # variables are just part of the rules if variable processing
323 # is required.
Armin Ronacherd874fbe2007-02-27 20:51:59 +0100324 root_tag_rules = [
325 ('comment', environment.comment_start_string),
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200326 ('block', environment.block_start_string),
327 ('variable', environment.variable_start_string)
Armin Ronacherd874fbe2007-02-27 20:51:59 +0100328 ]
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200329 root_tag_rules.sort(key=lambda x: -len(x[1]))
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200330
331 # now escape the rules. This is done here so that the escape
332 # signs don't count for the lengths of the tags.
333 root_tag_rules = [(a, e(b)) for a, b in root_tag_rules]
334
335 # if we have a line statement prefix we need an extra rule for
336 # that. We add this rule *after* all the others.
337 if environment.line_statement_prefix is not None:
338 prefix = e(environment.line_statement_prefix)
339 root_tag_rules.insert(0, ('linestatement', '^\s*' + prefix))
Armin Ronacherd874fbe2007-02-27 20:51:59 +0100340
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200341 # block suffix if trimming is enabled
342 block_suffix_re = environment.trim_blocks and '\\n?' or ''
343
344 # global lexing rules
Armin Ronacher92f572f2007-02-26 22:17:32 +0100345 self.rules = {
346 'root': [
Armin Ronacher523bf4c2007-11-17 23:45:04 +0100347 # directives
348 (c('(.*?)(?:%s)' % '|'.join(
349 ['(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*%s)' % (
350 e(environment.block_start_string),
351 e(environment.block_start_string),
352 e(environment.block_end_string)
353 )] + [
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200354 '(?P<%s_begin>\s*%s\-|%s)' % (n, r, r)
Armin Ronacher523bf4c2007-11-17 23:45:04 +0100355 for n, r in root_tag_rules
356 ])), ('data', '#bygroup'), '#bygroup'),
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200357 # data
Armin Ronacher92f572f2007-02-26 22:17:32 +0100358 (c('.+'), 'data', None)
359 ],
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200360 # comments
Armin Ronacher92f572f2007-02-26 22:17:32 +0100361 'comment_begin': [
Armin Ronachera5c8d582007-03-31 20:40:38 +0200362 (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (
Armin Ronacher1151fbc2007-03-28 21:44:04 +0200363 e(environment.comment_end_string),
Armin Ronachera5c8d582007-03-31 20:40:38 +0200364 e(environment.comment_end_string),
365 block_suffix_re
Armin Ronacher1151fbc2007-03-28 21:44:04 +0200366 )), ('comment', 'comment_end'), '#pop'),
Armin Ronacher92f572f2007-02-26 22:17:32 +0100367 (c('(.)'), (Failure('Missing end of comment tag'),), None)
368 ],
Armin Ronacher21580912007-04-17 17:13:10 +0200369 # blocks
Armin Ronacher92f572f2007-02-26 22:17:32 +0100370 'block_begin': [
Armin Ronachera5c8d582007-03-31 20:40:38 +0200371 (c('(?:\-%s\s*|%s)%s' % (
Armin Ronacher1151fbc2007-03-28 21:44:04 +0200372 e(environment.block_end_string),
Armin Ronachera5c8d582007-03-31 20:40:38 +0200373 e(environment.block_end_string),
374 block_suffix_re
Armin Ronacher1151fbc2007-03-28 21:44:04 +0200375 )), 'block_end', '#pop'),
Armin Ronacher92f572f2007-02-26 22:17:32 +0100376 ] + tag_rules,
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200377 # variables
378 'variable_begin': [
379 (c('\-%s\s*|%s' % (
380 e(environment.variable_end_string),
381 e(environment.variable_end_string)
382 )), 'variable_end', '#pop')
383 ] + tag_rules,
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200384 # raw block
Armin Ronacher523bf4c2007-11-17 23:45:04 +0100385 'raw_begin': [
Armin Ronacher1151fbc2007-03-28 21:44:04 +0200386 (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (
387 e(environment.block_start_string),
388 e(environment.block_start_string),
389 e(environment.block_end_string),
390 e(environment.block_end_string),
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200391 block_suffix_re
Armin Ronacher523bf4c2007-11-17 23:45:04 +0100392 )), ('data', 'raw_end'), '#pop'),
Armin Ronachera6c3ac52007-03-27 22:51:51 +0200393 (c('(.)'), (Failure('Missing end of raw directive'),), None)
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200394 ],
395 # line statements
396 'linestatement_begin': [
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200397 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')
398 ] + tag_rules
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200399 }
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200400
Armin Ronacher21580912007-04-17 17:13:10 +0200401 def tokenize(self, source, filename=None):
Armin Ronacher71082072008-04-12 14:19:36 +0200402 """Works like `tokeniter` but returns a tokenstream of tokens and not
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200403 a generator or token tuples. Additionally all token values are already
Armin Ronacher115de2e2008-05-01 22:20:05 +0200404 converted into types and postprocessed. For example comments are removed,
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200405 integers and floats converted, strings unescaped etc.
Armin Ronacher92f572f2007-02-26 22:17:32 +0100406 """
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200407 source = unicode(source)
Armin Ronacher5a8e4972007-04-05 11:21:38 +0200408 def generate():
Armin Ronacher21580912007-04-17 17:13:10 +0200409 for lineno, token, value in self.tokeniter(source, filename):
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200410 if token in ('comment_begin', 'comment', 'comment_end'):
411 continue
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200412 elif token == 'linestatement_begin':
413 token = 'block_begin'
414 elif token == 'linestatement_end':
415 token = 'block_end'
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200416 # we are not interested in those tokens in the parser
417 elif token in ('raw_begin', 'raw_end'):
418 continue
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200419 elif token == 'data':
Armin Ronacherb5365482008-05-11 00:18:35 +0200420 value = _trystr(value)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200421 elif token == 'keyword':
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200422 token = value
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200423 elif token == 'name':
Armin Ronacherb5365482008-05-11 00:18:35 +0200424 value = _trystr(value)
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200425 elif token == 'string':
426 value = unescape_string(lineno, filename, value[1:-1])
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200427 elif token == 'integer':
428 value = int(value)
429 elif token == 'float':
430 value = float(value)
431 elif token == 'operator':
432 token = operators[value]
Armin Ronacher1cc232c2007-09-07 17:52:41 +0200433 yield Token(lineno, token, value)
Armin Ronacher21580912007-04-17 17:13:10 +0200434 return TokenStream(generate(), filename)
Armin Ronacher92f572f2007-02-26 22:17:32 +0100435
Armin Ronacher21580912007-04-17 17:13:10 +0200436 def tokeniter(self, source, filename=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200437 """This method tokenizes the text and returns the tokens in a
438 generator. Use this method if you just want to tokenize a template.
439 The output you get is not compatible with the input the jinja parser
440 wants. The parser uses the `tokenize` function with returns a
441 `TokenStream` and postprocessed tokens.
Armin Ronacher92f572f2007-02-26 22:17:32 +0100442 """
Armin Ronacher5a8e4972007-04-05 11:21:38 +0200443 source = '\n'.join(source.splitlines())
Armin Ronacher7977e5c2007-03-12 07:22:17 +0100444 pos = 0
445 lineno = 1
Armin Ronacher92f572f2007-02-26 22:17:32 +0100446 stack = ['root']
447 statetokens = self.rules['root']
448 source_length = len(source)
449
Armin Ronacher21580912007-04-17 17:13:10 +0200450 balancing_stack = []
451
Armin Ronacher71082072008-04-12 14:19:36 +0200452 while 1:
Armin Ronacher92f572f2007-02-26 22:17:32 +0100453 # tokenizer loop
454 for regex, tokens, new_state in statetokens:
455 m = regex.match(source, pos)
Armin Ronacher21580912007-04-17 17:13:10 +0200456 # if no match we try again with the next rule
Armin Ronacher71082072008-04-12 14:19:36 +0200457 if m is None:
Armin Ronacher21580912007-04-17 17:13:10 +0200458 continue
459
460 # we only match blocks and variables if brances / parentheses
461 # are balanced. continue parsing with the lower rule which
462 # is the operator rule. do this only if the end tags look
463 # like operators
464 if balancing_stack and \
Armin Ronacher71082072008-04-12 14:19:36 +0200465 tokens in ('variable_end', 'block_end',
466 'linestatement_end'):
Armin Ronacher21580912007-04-17 17:13:10 +0200467 continue
468
469 # tuples support more options
470 if isinstance(tokens, tuple):
471 for idx, token in enumerate(tokens):
472 # hidden group
473 if token is None:
474 g = m.group(idx)
475 if g:
476 lineno += g.count('\n')
477 continue
478 # failure group
Armin Ronacherecc051b2007-06-01 18:25:28 +0200479 elif token.__class__ is Failure:
Armin Ronacher720e55b2007-05-30 00:57:49 +0200480 raise token(lineno, filename)
Armin Ronacher21580912007-04-17 17:13:10 +0200481 # bygroup is a bit more complex, in that case we
482 # yield for the current token the first named
483 # group that matched
484 elif token == '#bygroup':
Armin Ronacher92f572f2007-02-26 22:17:32 +0100485 for key, value in m.groupdict().iteritems():
486 if value is not None:
Armin Ronacher21580912007-04-17 17:13:10 +0200487 yield lineno, key, value
488 lineno += value.count('\n')
Armin Ronacher92f572f2007-02-26 22:17:32 +0100489 break
490 else:
Armin Ronacher21580912007-04-17 17:13:10 +0200491 raise RuntimeError('%r wanted to resolve '
492 'the token dynamically'
493 ' but no group matched'
494 % regex)
495 # normal group
Armin Ronacher92f572f2007-02-26 22:17:32 +0100496 else:
Armin Ronacher21580912007-04-17 17:13:10 +0200497 data = m.group(idx + 1)
498 if data:
499 yield lineno, token, data
500 lineno += data.count('\n')
501
Armin Ronacher71082072008-04-12 14:19:36 +0200502 # strings as token just are yielded as it.
Armin Ronacher21580912007-04-17 17:13:10 +0200503 else:
504 data = m.group()
505 # update brace/parentheses balance
506 if tokens == 'operator':
507 if data == '{':
508 balancing_stack.append('}')
509 elif data == '(':
510 balancing_stack.append(')')
511 elif data == '[':
512 balancing_stack.append(']')
513 elif data in ('}', ')', ']'):
Armin Ronacherf750daa2007-05-29 23:22:38 +0200514 if not balancing_stack:
515 raise TemplateSyntaxError('unexpected "%s"' %
516 data, lineno,
517 filename)
518 expected_op = balancing_stack.pop()
519 if expected_op != data:
520 raise TemplateSyntaxError('unexpected "%s", '
521 'expected "%s"' %
522 (data, expected_op),
Armin Ronacher21580912007-04-17 17:13:10 +0200523 lineno, filename)
524 # yield items
525 if tokens is not None:
Armin Ronacher71082072008-04-12 14:19:36 +0200526 yield lineno, tokens, data
Armin Ronacher21580912007-04-17 17:13:10 +0200527 lineno += data.count('\n')
528
529 # fetch new position into new variable so that we can check
530 # if there is a internal parsing error which would result
531 # in an infinite loop
532 pos2 = m.end()
533
534 # handle state changes
535 if new_state is not None:
536 # remove the uppermost state
537 if new_state == '#pop':
538 stack.pop()
539 # resolve the new state by group checking
540 elif new_state == '#bygroup':
541 for key, value in m.groupdict().iteritems():
542 if value is not None:
543 stack.append(key)
544 break
545 else:
546 raise RuntimeError('%r wanted to resolve the '
547 'new state dynamically but'
548 ' no group matched' %
549 regex)
550 # direct state name given
551 else:
552 stack.append(new_state)
553 statetokens = self.rules[stack[-1]]
554 # we are still at the same position and no stack change.
555 # this means a loop without break condition, avoid that and
556 # raise error
557 elif pos2 == pos:
558 raise RuntimeError('%r yielded empty string without '
559 'stack change' % regex)
560 # publish new function and start again
561 pos = pos2
562 break
Armin Ronacher92f572f2007-02-26 22:17:32 +0100563 # if loop terminated without break we havn't found a single match
564 # either we are at the end of the file or we have a problem
565 else:
566 # end of text
567 if pos >= source_length:
568 return
569 # something went wrong
570 raise TemplateSyntaxError('unexpected char %r at %d' %
Armin Ronacher21580912007-04-17 17:13:10 +0200571 (source[pos], pos), lineno,
572 filename)