PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/jinja2/jinja2/lexer.py

https://bitbucket.org/cfbolz/benchmarks-pypy-phd
Python | 681 lines | 639 code | 2 blank | 40 comment | 2 complexity | aadf76864e8f9eb79950117f04dbadb8 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, Apache-2.0
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.lexer
  4. ~~~~~~~~~~~~
  5. This module implements a Jinja / Python combination lexer. The
  6. `Lexer` class provided by this module is used to do some preprocessing
  7. for Jinja.
  8. On the one hand it filters out invalid operators like the bitshift
  9. operators we don't allow in templates. On the other hand it separates
  10. template code and python code in expressions.
  11. :copyright: (c) 2010 by the Jinja Team.
  12. :license: BSD, see LICENSE for more details.
  13. """
  14. import re
  15. from operator import itemgetter
  16. from collections import deque
  17. from jinja2.exceptions import TemplateSyntaxError
  18. from jinja2.utils import LRUCache, next
  19. # cache for the lexers. Exists in order to be able to have multiple
  20. # environments with the same lexer
  21. _lexer_cache = LRUCache(50)
  22. # static regular expressions
  23. whitespace_re = re.compile(r'\s+', re.U)
  24. string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
  25. r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)
  26. integer_re = re.compile(r'\d+')
  27. # we use the unicode identifier rule if this python version is able
  28. # to handle unicode identifiers, otherwise the standard ASCII one.
  29. try:
  30. compile('fÜÜ', '<unknown>', 'eval')
  31. except SyntaxError:
  32. name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')
  33. else:
  34. from jinja2 import _stringdefs
  35. name_re = re.compile(r'[%s][%s]*' % (_stringdefs.xid_start,
  36. _stringdefs.xid_continue))
  37. float_re = re.compile(r'(?<!\.)\d+\.\d+')
  38. newline_re = re.compile(r'(\r\n|\r|\n)')
  39. # internal the tokens and keep references to them
  40. TOKEN_ADD = intern('add')
  41. TOKEN_ASSIGN = intern('assign')
  42. TOKEN_COLON = intern('colon')
  43. TOKEN_COMMA = intern('comma')
  44. TOKEN_DIV = intern('div')
  45. TOKEN_DOT = intern('dot')
  46. TOKEN_EQ = intern('eq')
  47. TOKEN_FLOORDIV = intern('floordiv')
  48. TOKEN_GT = intern('gt')
  49. TOKEN_GTEQ = intern('gteq')
  50. TOKEN_LBRACE = intern('lbrace')
  51. TOKEN_LBRACKET = intern('lbracket')
  52. TOKEN_LPAREN = intern('lparen')
  53. TOKEN_LT = intern('lt')
  54. TOKEN_LTEQ = intern('lteq')
  55. TOKEN_MOD = intern('mod')
  56. TOKEN_MUL = intern('mul')
  57. TOKEN_NE = intern('ne')
  58. TOKEN_PIPE = intern('pipe')
  59. TOKEN_POW = intern('pow')
  60. TOKEN_RBRACE = intern('rbrace')
  61. TOKEN_RBRACKET = intern('rbracket')
  62. TOKEN_RPAREN = intern('rparen')
  63. TOKEN_SEMICOLON = intern('semicolon')
  64. TOKEN_SUB = intern('sub')
  65. TOKEN_TILDE = intern('tilde')
  66. TOKEN_WHITESPACE = intern('whitespace')
  67. TOKEN_FLOAT = intern('float')
  68. TOKEN_INTEGER = intern('integer')
  69. TOKEN_NAME = intern('name')
  70. TOKEN_STRING = intern('string')
  71. TOKEN_OPERATOR = intern('operator')
  72. TOKEN_BLOCK_BEGIN = intern('block_begin')
  73. TOKEN_BLOCK_END = intern('block_end')
  74. TOKEN_VARIABLE_BEGIN = intern('variable_begin')
  75. TOKEN_VARIABLE_END = intern('variable_end')
  76. TOKEN_RAW_BEGIN = intern('raw_begin')
  77. TOKEN_RAW_END = intern('raw_end')
  78. TOKEN_COMMENT_BEGIN = intern('comment_begin')
  79. TOKEN_COMMENT_END = intern('comment_end')
  80. TOKEN_COMMENT = intern('comment')
  81. TOKEN_LINESTATEMENT_BEGIN = intern('linestatement_begin')
  82. TOKEN_LINESTATEMENT_END = intern('linestatement_end')
  83. TOKEN_LINECOMMENT_BEGIN = intern('linecomment_begin')
  84. TOKEN_LINECOMMENT_END = intern('linecomment_end')
  85. TOKEN_LINECOMMENT = intern('linecomment')
  86. TOKEN_DATA = intern('data')
  87. TOKEN_INITIAL = intern('initial')
  88. TOKEN_EOF = intern('eof')
  89. # bind operators to token types
  90. operators = {
  91. '+': TOKEN_ADD,
  92. '-': TOKEN_SUB,
  93. '/': TOKEN_DIV,
  94. '//': TOKEN_FLOORDIV,
  95. '*': TOKEN_MUL,
  96. '%': TOKEN_MOD,
  97. '**': TOKEN_POW,
  98. '~': TOKEN_TILDE,
  99. '[': TOKEN_LBRACKET,
  100. ']': TOKEN_RBRACKET,
  101. '(': TOKEN_LPAREN,
  102. ')': TOKEN_RPAREN,
  103. '{': TOKEN_LBRACE,
  104. '}': TOKEN_RBRACE,
  105. '==': TOKEN_EQ,
  106. '!=': TOKEN_NE,
  107. '>': TOKEN_GT,
  108. '>=': TOKEN_GTEQ,
  109. '<': TOKEN_LT,
  110. '<=': TOKEN_LTEQ,
  111. '=': TOKEN_ASSIGN,
  112. '.': TOKEN_DOT,
  113. ':': TOKEN_COLON,
  114. '|': TOKEN_PIPE,
  115. ',': TOKEN_COMMA,
  116. ';': TOKEN_SEMICOLON
  117. }
  118. reverse_operators = dict([(v, k) for k, v in operators.iteritems()])
  119. assert len(operators) == len(reverse_operators), 'operators dropped'
  120. operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in
  121. sorted(operators, key=lambda x: -len(x))))
  122. ignored_tokens = frozenset([TOKEN_COMMENT_BEGIN, TOKEN_COMMENT,
  123. TOKEN_COMMENT_END, TOKEN_WHITESPACE,
  124. TOKEN_WHITESPACE, TOKEN_LINECOMMENT_BEGIN,
  125. TOKEN_LINECOMMENT_END, TOKEN_LINECOMMENT])
  126. ignore_if_empty = frozenset([TOKEN_WHITESPACE, TOKEN_DATA,
  127. TOKEN_COMMENT, TOKEN_LINECOMMENT])
  128. def _describe_token_type(token_type):
  129. if token_type in reverse_operators:
  130. return reverse_operators[token_type]
  131. return {
  132. TOKEN_COMMENT_BEGIN: 'begin of comment',
  133. TOKEN_COMMENT_END: 'end of comment',
  134. TOKEN_COMMENT: 'comment',
  135. TOKEN_LINECOMMENT: 'comment',
  136. TOKEN_BLOCK_BEGIN: 'begin of statement block',
  137. TOKEN_BLOCK_END: 'end of statement block',
  138. TOKEN_VARIABLE_BEGIN: 'begin of print statement',
  139. TOKEN_VARIABLE_END: 'end of print statement',
  140. TOKEN_LINESTATEMENT_BEGIN: 'begin of line statement',
  141. TOKEN_LINESTATEMENT_END: 'end of line statement',
  142. TOKEN_DATA: 'template data / text',
  143. TOKEN_EOF: 'end of template'
  144. }.get(token_type, token_type)
  145. def describe_token(token):
  146. """Returns a description of the token."""
  147. if token.type == 'name':
  148. return token.value
  149. return _describe_token_type(token.type)
  150. def describe_token_expr(expr):
  151. """Like `describe_token` but for token expressions."""
  152. if ':' in expr:
  153. type, value = expr.split(':', 1)
  154. if type == 'name':
  155. return value
  156. else:
  157. type = expr
  158. return _describe_token_type(type)
  159. def count_newlines(value):
  160. """Count the number of newline characters in the string. This is
  161. useful for extensions that filter a stream.
  162. """
  163. return len(newline_re.findall(value))
  164. def compile_rules(environment):
  165. """Compiles all the rules from the environment into a list of rules."""
  166. e = re.escape
  167. rules = [
  168. (len(environment.comment_start_string), 'comment',
  169. e(environment.comment_start_string)),
  170. (len(environment.block_start_string), 'block',
  171. e(environment.block_start_string)),
  172. (len(environment.variable_start_string), 'variable',
  173. e(environment.variable_start_string))
  174. ]
  175. if environment.line_statement_prefix is not None:
  176. rules.append((len(environment.line_statement_prefix), 'linestatement',
  177. r'^\s*' + e(environment.line_statement_prefix)))
  178. if environment.line_comment_prefix is not None:
  179. rules.append((len(environment.line_comment_prefix), 'linecomment',
  180. r'(?:^|(?<=\S))[^\S\r\n]*' +
  181. e(environment.line_comment_prefix)))
  182. return [x[1:] for x in sorted(rules, reverse=True)]
  183. class Failure(object):
  184. """Class that raises a `TemplateSyntaxError` if called.
  185. Used by the `Lexer` to specify known errors.
  186. """
  187. def __init__(self, message, cls=TemplateSyntaxError):
  188. self.message = message
  189. self.error_class = cls
  190. def __call__(self, lineno, filename):
  191. raise self.error_class(self.message, lineno, filename)
  192. class Token(tuple):
  193. """Token class."""
  194. __slots__ = ()
  195. lineno, type, value = (property(itemgetter(x)) for x in range(3))
  196. def __new__(cls, lineno, type, value):
  197. return tuple.__new__(cls, (lineno, intern(str(type)), value))
  198. def __str__(self):
  199. if self.type in reverse_operators:
  200. return reverse_operators[self.type]
  201. elif self.type == 'name':
  202. return self.value
  203. return self.type
  204. def test(self, expr):
  205. """Test a token against a token expression. This can either be a
  206. token type or ``'token_type:token_value'``. This can only test
  207. against string values and types.
  208. """
  209. # here we do a regular string equality check as test_any is usually
  210. # passed an iterable of not interned strings.
  211. if self.type == expr:
  212. return True
  213. elif ':' in expr:
  214. return expr.split(':', 1) == [self.type, self.value]
  215. return False
  216. def test_any(self, *iterable):
  217. """Test against multiple token expressions."""
  218. for expr in iterable:
  219. if self.test(expr):
  220. return True
  221. return False
  222. def __repr__(self):
  223. return 'Token(%r, %r, %r)' % (
  224. self.lineno,
  225. self.type,
  226. self.value
  227. )
  228. class TokenStreamIterator(object):
  229. """The iterator for tokenstreams. Iterate over the stream
  230. until the eof token is reached.
  231. """
  232. def __init__(self, stream):
  233. self.stream = stream
  234. def __iter__(self):
  235. return self
  236. def next(self):
  237. token = self.stream.current
  238. if token.type is TOKEN_EOF:
  239. self.stream.close()
  240. raise StopIteration()
  241. next(self.stream)
  242. return token
  243. class TokenStream(object):
  244. """A token stream is an iterable that yields :class:`Token`\s. The
  245. parser however does not iterate over it but calls :meth:`next` to go
  246. one token ahead. The current active token is stored as :attr:`current`.
  247. """
  248. def __init__(self, generator, name, filename):
  249. self._next = iter(generator).next
  250. self._pushed = deque()
  251. self.name = name
  252. self.filename = filename
  253. self.closed = False
  254. self.current = Token(1, TOKEN_INITIAL, '')
  255. next(self)
  256. def __iter__(self):
  257. return TokenStreamIterator(self)
  258. def __nonzero__(self):
  259. return bool(self._pushed) or self.current.type is not TOKEN_EOF
  260. eos = property(lambda x: not x, doc="Are we at the end of the stream?")
  261. def push(self, token):
  262. """Push a token back to the stream."""
  263. self._pushed.append(token)
  264. def look(self):
  265. """Look at the next token."""
  266. old_token = next(self)
  267. result = self.current
  268. self.push(result)
  269. self.current = old_token
  270. return result
  271. def skip(self, n=1):
  272. """Got n tokens ahead."""
  273. for x in xrange(n):
  274. next(self)
  275. def next_if(self, expr):
  276. """Perform the token test and return the token if it matched.
  277. Otherwise the return value is `None`.
  278. """
  279. if self.current.test(expr):
  280. return next(self)
  281. def skip_if(self, expr):
  282. """Like :meth:`next_if` but only returns `True` or `False`."""
  283. return self.next_if(expr) is not None
  284. def next(self):
  285. """Go one token ahead and return the old one"""
  286. rv = self.current
  287. if self._pushed:
  288. self.current = self._pushed.popleft()
  289. elif self.current.type is not TOKEN_EOF:
  290. try:
  291. self.current = self._next()
  292. except StopIteration:
  293. self.close()
  294. return rv
  295. def close(self):
  296. """Close the stream."""
  297. self.current = Token(self.current.lineno, TOKEN_EOF, '')
  298. self._next = None
  299. self.closed = True
  300. def expect(self, expr):
  301. """Expect a given token type and return it. This accepts the same
  302. argument as :meth:`jinja2.lexer.Token.test`.
  303. """
  304. if not self.current.test(expr):
  305. expr = describe_token_expr(expr)
  306. if self.current.type is TOKEN_EOF:
  307. raise TemplateSyntaxError('unexpected end of template, '
  308. 'expected %r.' % expr,
  309. self.current.lineno,
  310. self.name, self.filename)
  311. raise TemplateSyntaxError("expected token %r, got %r" %
  312. (expr, describe_token(self.current)),
  313. self.current.lineno,
  314. self.name, self.filename)
  315. try:
  316. return self.current
  317. finally:
  318. next(self)
  319. def get_lexer(environment):
  320. """Return a lexer which is probably cached."""
  321. key = (environment.block_start_string,
  322. environment.block_end_string,
  323. environment.variable_start_string,
  324. environment.variable_end_string,
  325. environment.comment_start_string,
  326. environment.comment_end_string,
  327. environment.line_statement_prefix,
  328. environment.line_comment_prefix,
  329. environment.trim_blocks,
  330. environment.newline_sequence)
  331. lexer = _lexer_cache.get(key)
  332. if lexer is None:
  333. lexer = Lexer(environment)
  334. _lexer_cache[key] = lexer
  335. return lexer
  336. class Lexer(object):
  337. """Class that implements a lexer for a given environment. Automatically
  338. created by the environment class, usually you don't have to do that.
  339. Note that the lexer is not automatically bound to an environment.
  340. Multiple environments can share the same lexer.
  341. """
  342. def __init__(self, environment):
  343. # shortcuts
  344. c = lambda x: re.compile(x, re.M | re.S)
  345. e = re.escape
  346. # lexing rules for tags
  347. tag_rules = [
  348. (whitespace_re, TOKEN_WHITESPACE, None),
  349. (float_re, TOKEN_FLOAT, None),
  350. (integer_re, TOKEN_INTEGER, None),
  351. (name_re, TOKEN_NAME, None),
  352. (string_re, TOKEN_STRING, None),
  353. (operator_re, TOKEN_OPERATOR, None)
  354. ]
  355. # assemble the root lexing rule. because "|" is ungreedy
  356. # we have to sort by length so that the lexer continues working
  357. # as expected when we have parsing rules like <% for block and
  358. # <%= for variables. (if someone wants asp like syntax)
  359. # variables are just part of the rules if variable processing
  360. # is required.
  361. root_tag_rules = compile_rules(environment)
  362. # block suffix if trimming is enabled
  363. block_suffix_re = environment.trim_blocks and '\\n?' or ''
  364. self.newline_sequence = environment.newline_sequence
  365. # global lexing rules
  366. self.rules = {
  367. 'root': [
  368. # directives
  369. (c('(.*?)(?:%s)' % '|'.join(
  370. [r'(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*(?:\-%s\s*|%s))' % (
  371. e(environment.block_start_string),
  372. e(environment.block_start_string),
  373. e(environment.block_end_string),
  374. e(environment.block_end_string)
  375. )] + [
  376. r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, r)
  377. for n, r in root_tag_rules
  378. ])), (TOKEN_DATA, '#bygroup'), '#bygroup'),
  379. # data
  380. (c('.+'), TOKEN_DATA, None)
  381. ],
  382. # comments
  383. TOKEN_COMMENT_BEGIN: [
  384. (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (
  385. e(environment.comment_end_string),
  386. e(environment.comment_end_string),
  387. block_suffix_re
  388. )), (TOKEN_COMMENT, TOKEN_COMMENT_END), '#pop'),
  389. (c('(.)'), (Failure('Missing end of comment tag'),), None)
  390. ],
  391. # blocks
  392. TOKEN_BLOCK_BEGIN: [
  393. (c('(?:\-%s\s*|%s)%s' % (
  394. e(environment.block_end_string),
  395. e(environment.block_end_string),
  396. block_suffix_re
  397. )), TOKEN_BLOCK_END, '#pop'),
  398. ] + tag_rules,
  399. # variables
  400. TOKEN_VARIABLE_BEGIN: [
  401. (c('\-%s\s*|%s' % (
  402. e(environment.variable_end_string),
  403. e(environment.variable_end_string)
  404. )), TOKEN_VARIABLE_END, '#pop')
  405. ] + tag_rules,
  406. # raw block
  407. TOKEN_RAW_BEGIN: [
  408. (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (
  409. e(environment.block_start_string),
  410. e(environment.block_start_string),
  411. e(environment.block_end_string),
  412. e(environment.block_end_string),
  413. block_suffix_re
  414. )), (TOKEN_DATA, TOKEN_RAW_END), '#pop'),
  415. (c('(.)'), (Failure('Missing end of raw directive'),), None)
  416. ],
  417. # line statements
  418. TOKEN_LINESTATEMENT_BEGIN: [
  419. (c(r'\s*(\n|$)'), TOKEN_LINESTATEMENT_END, '#pop')
  420. ] + tag_rules,
  421. # line comments
  422. TOKEN_LINECOMMENT_BEGIN: [
  423. (c(r'(.*?)()(?=\n|$)'), (TOKEN_LINECOMMENT,
  424. TOKEN_LINECOMMENT_END), '#pop')
  425. ]
  426. }
  427. def _normalize_newlines(self, value):
  428. """Called for strings and template data to normalize it to unicode."""
  429. return newline_re.sub(self.newline_sequence, value)
  430. def tokenize(self, source, name=None, filename=None, state=None):
  431. """Calls tokeniter + tokenize and wraps it in a token stream.
  432. """
  433. stream = self.tokeniter(source, name, filename, state)
  434. return TokenStream(self.wrap(stream, name, filename), name, filename)
  435. def wrap(self, stream, name=None, filename=None):
  436. """This is called with the stream as returned by `tokenize` and wraps
  437. every token in a :class:`Token` and converts the value.
  438. """
  439. for lineno, token, value in stream:
  440. if token in ignored_tokens:
  441. continue
  442. elif token == 'linestatement_begin':
  443. token = 'block_begin'
  444. elif token == 'linestatement_end':
  445. token = 'block_end'
  446. # we are not interested in those tokens in the parser
  447. elif token in ('raw_begin', 'raw_end'):
  448. continue
  449. elif token == 'data':
  450. value = self._normalize_newlines(value)
  451. elif token == 'keyword':
  452. token = value
  453. elif token == 'name':
  454. value = str(value)
  455. elif token == 'string':
  456. # try to unescape string
  457. try:
  458. value = self._normalize_newlines(value[1:-1]) \
  459. .encode('ascii', 'backslashreplace') \
  460. .decode('unicode-escape')
  461. except Exception, e:
  462. msg = str(e).split(':')[-1].strip()
  463. raise TemplateSyntaxError(msg, lineno, name, filename)
  464. # if we can express it as bytestring (ascii only)
  465. # we do that for support of semi broken APIs
  466. # as datetime.datetime.strftime. On python 3 this
  467. # call becomes a noop thanks to 2to3
  468. try:
  469. value = str(value)
  470. except UnicodeError:
  471. pass
  472. elif token == 'integer':
  473. value = int(value)
  474. elif token == 'float':
  475. value = float(value)
  476. elif token == 'operator':
  477. token = operators[value]
  478. yield Token(lineno, token, value)
  479. def tokeniter(self, source, name, filename=None, state=None):
  480. """This method tokenizes the text and returns the tokens in a
  481. generator. Use this method if you just want to tokenize a template.
  482. """
  483. source = '\n'.join(unicode(source).splitlines())
  484. pos = 0
  485. lineno = 1
  486. stack = ['root']
  487. if state is not None and state != 'root':
  488. assert state in ('variable', 'block'), 'invalid state'
  489. stack.append(state + '_begin')
  490. else:
  491. state = 'root'
  492. statetokens = self.rules[stack[-1]]
  493. source_length = len(source)
  494. balancing_stack = []
  495. while 1:
  496. # tokenizer loop
  497. for regex, tokens, new_state in statetokens:
  498. m = regex.match(source, pos)
  499. # if no match we try again with the next rule
  500. if m is None:
  501. continue
  502. # we only match blocks and variables if braces / parentheses
  503. # are balanced. continue parsing with the lower rule which
  504. # is the operator rule. do this only if the end tags look
  505. # like operators
  506. if balancing_stack and \
  507. tokens in ('variable_end', 'block_end',
  508. 'linestatement_end'):
  509. continue
  510. # tuples support more options
  511. if isinstance(tokens, tuple):
  512. for idx, token in enumerate(tokens):
  513. # failure group
  514. if token.__class__ is Failure:
  515. raise token(lineno, filename)
  516. # bygroup is a bit more complex, in that case we
  517. # yield for the current token the first named
  518. # group that matched
  519. elif token == '#bygroup':
  520. for key, value in m.groupdict().iteritems():
  521. if value is not None:
  522. yield lineno, key, value
  523. lineno += value.count('\n')
  524. break
  525. else:
  526. raise RuntimeError('%r wanted to resolve '
  527. 'the token dynamically'
  528. ' but no group matched'
  529. % regex)
  530. # normal group
  531. else:
  532. data = m.group(idx + 1)
  533. if data or token not in ignore_if_empty:
  534. yield lineno, token, data
  535. lineno += data.count('\n')
  536. # strings as token just are yielded as it.
  537. else:
  538. data = m.group()
  539. # update brace/parentheses balance
  540. if tokens == 'operator':
  541. if data == '{':
  542. balancing_stack.append('}')
  543. elif data == '(':
  544. balancing_stack.append(')')
  545. elif data == '[':
  546. balancing_stack.append(']')
  547. elif data in ('}', ')', ']'):
  548. if not balancing_stack:
  549. raise TemplateSyntaxError('unexpected \'%s\'' %
  550. data, lineno, name,
  551. filename)
  552. expected_op = balancing_stack.pop()
  553. if expected_op != data:
  554. raise TemplateSyntaxError('unexpected \'%s\', '
  555. 'expected \'%s\'' %
  556. (data, expected_op),
  557. lineno, name,
  558. filename)
  559. # yield items
  560. if data or tokens not in ignore_if_empty:
  561. yield lineno, tokens, data
  562. lineno += data.count('\n')
  563. # fetch new position into new variable so that we can check
  564. # if there is a internal parsing error which would result
  565. # in an infinite loop
  566. pos2 = m.end()
  567. # handle state changes
  568. if new_state is not None:
  569. # remove the uppermost state
  570. if new_state == '#pop':
  571. stack.pop()
  572. # resolve the new state by group checking
  573. elif new_state == '#bygroup':
  574. for key, value in m.groupdict().iteritems():
  575. if value is not None:
  576. stack.append(key)
  577. break
  578. else:
  579. raise RuntimeError('%r wanted to resolve the '
  580. 'new state dynamically but'
  581. ' no group matched' %
  582. regex)
  583. # direct state name given
  584. else:
  585. stack.append(new_state)
  586. statetokens = self.rules[stack[-1]]
  587. # we are still at the same position and no stack change.
  588. # this means a loop without break condition, avoid that and
  589. # raise error
  590. elif pos2 == pos:
  591. raise RuntimeError('%r yielded empty string without '
  592. 'stack change' % regex)
  593. # publish new function and start again
  594. pos = pos2
  595. break
  596. # if loop terminated without break we haven't found a single match
  597. # either we are at the end of the file or we have a problem
  598. else:
  599. # end of text
  600. if pos >= source_length:
  601. return
  602. # something went wrong
  603. raise TemplateSyntaxError('unexpected char %r at %d' %
  604. (source[pos], pos), lineno,
  605. name, filename)