PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/cpython-doc/tools/jinja2/lexer.py

https://bitbucket.org/cfbolz/benchmarks-pypy-phd
Python | 680 lines | 638 code | 2 blank | 40 comment | 2 complexity | 637681f55d39025a44a1d679d5e69dd5 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. # assamble 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)' % (
  371. e(environment.block_start_string),
  372. e(environment.block_start_string),
  373. e(environment.block_end_string)
  374. )] + [
  375. r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, r)
  376. for n, r in root_tag_rules
  377. ])), (TOKEN_DATA, '#bygroup'), '#bygroup'),
  378. # data
  379. (c('.+'), TOKEN_DATA, None)
  380. ],
  381. # comments
  382. TOKEN_COMMENT_BEGIN: [
  383. (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (
  384. e(environment.comment_end_string),
  385. e(environment.comment_end_string),
  386. block_suffix_re
  387. )), (TOKEN_COMMENT, TOKEN_COMMENT_END), '#pop'),
  388. (c('(.)'), (Failure('Missing end of comment tag'),), None)
  389. ],
  390. # blocks
  391. TOKEN_BLOCK_BEGIN: [
  392. (c('(?:\-%s\s*|%s)%s' % (
  393. e(environment.block_end_string),
  394. e(environment.block_end_string),
  395. block_suffix_re
  396. )), TOKEN_BLOCK_END, '#pop'),
  397. ] + tag_rules,
  398. # variables
  399. TOKEN_VARIABLE_BEGIN: [
  400. (c('\-%s\s*|%s' % (
  401. e(environment.variable_end_string),
  402. e(environment.variable_end_string)
  403. )), TOKEN_VARIABLE_END, '#pop')
  404. ] + tag_rules,
  405. # raw block
  406. TOKEN_RAW_BEGIN: [
  407. (c('(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (
  408. e(environment.block_start_string),
  409. e(environment.block_start_string),
  410. e(environment.block_end_string),
  411. e(environment.block_end_string),
  412. block_suffix_re
  413. )), (TOKEN_DATA, TOKEN_RAW_END), '#pop'),
  414. (c('(.)'), (Failure('Missing end of raw directive'),), None)
  415. ],
  416. # line statements
  417. TOKEN_LINESTATEMENT_BEGIN: [
  418. (c(r'\s*(\n|$)'), TOKEN_LINESTATEMENT_END, '#pop')
  419. ] + tag_rules,
  420. # line comments
  421. TOKEN_LINECOMMENT_BEGIN: [
  422. (c(r'(.*?)()(?=\n|$)'), (TOKEN_LINECOMMENT,
  423. TOKEN_LINECOMMENT_END), '#pop')
  424. ]
  425. }
  426. def _normalize_newlines(self, value):
  427. """Called for strings and template data to normlize it to unicode."""
  428. return newline_re.sub(self.newline_sequence, value)
  429. def tokenize(self, source, name=None, filename=None, state=None):
  430. """Calls tokeniter + tokenize and wraps it in a token stream.
  431. """
  432. stream = self.tokeniter(source, name, filename, state)
  433. return TokenStream(self.wrap(stream, name, filename), name, filename)
  434. def wrap(self, stream, name=None, filename=None):
  435. """This is called with the stream as returned by `tokenize` and wraps
  436. every token in a :class:`Token` and converts the value.
  437. """
  438. for lineno, token, value in stream:
  439. if token in ignored_tokens:
  440. continue
  441. elif token == 'linestatement_begin':
  442. token = 'block_begin'
  443. elif token == 'linestatement_end':
  444. token = 'block_end'
  445. # we are not interested in those tokens in the parser
  446. elif token in ('raw_begin', 'raw_end'):
  447. continue
  448. elif token == 'data':
  449. value = self._normalize_newlines(value)
  450. elif token == 'keyword':
  451. token = value
  452. elif token == 'name':
  453. value = str(value)
  454. elif token == 'string':
  455. # try to unescape string
  456. try:
  457. value = self._normalize_newlines(value[1:-1]) \
  458. .encode('ascii', 'backslashreplace') \
  459. .decode('unicode-escape')
  460. except Exception, e:
  461. msg = str(e).split(':')[-1].strip()
  462. raise TemplateSyntaxError(msg, lineno, name, filename)
  463. # if we can express it as bytestring (ascii only)
  464. # we do that for support of semi broken APIs
  465. # as datetime.datetime.strftime. On python 3 this
  466. # call becomes a noop thanks to 2to3
  467. try:
  468. value = str(value)
  469. except UnicodeError:
  470. pass
  471. elif token == 'integer':
  472. value = int(value)
  473. elif token == 'float':
  474. value = float(value)
  475. elif token == 'operator':
  476. token = operators[value]
  477. yield Token(lineno, token, value)
  478. def tokeniter(self, source, name, filename=None, state=None):
  479. """This method tokenizes the text and returns the tokens in a
  480. generator. Use this method if you just want to tokenize a template.
  481. """
  482. source = '\n'.join(unicode(source).splitlines())
  483. pos = 0
  484. lineno = 1
  485. stack = ['root']
  486. if state is not None and state != 'root':
  487. assert state in ('variable', 'block'), 'invalid state'
  488. stack.append(state + '_begin')
  489. else:
  490. state = 'root'
  491. statetokens = self.rules[stack[-1]]
  492. source_length = len(source)
  493. balancing_stack = []
  494. while 1:
  495. # tokenizer loop
  496. for regex, tokens, new_state in statetokens:
  497. m = regex.match(source, pos)
  498. # if no match we try again with the next rule
  499. if m is None:
  500. continue
  501. # we only match blocks and variables if brances / parentheses
  502. # are balanced. continue parsing with the lower rule which
  503. # is the operator rule. do this only if the end tags look
  504. # like operators
  505. if balancing_stack and \
  506. tokens in ('variable_end', 'block_end',
  507. 'linestatement_end'):
  508. continue
  509. # tuples support more options
  510. if isinstance(tokens, tuple):
  511. for idx, token in enumerate(tokens):
  512. # failure group
  513. if token.__class__ is Failure:
  514. raise token(lineno, filename)
  515. # bygroup is a bit more complex, in that case we
  516. # yield for the current token the first named
  517. # group that matched
  518. elif token == '#bygroup':
  519. for key, value in m.groupdict().iteritems():
  520. if value is not None:
  521. yield lineno, key, value
  522. lineno += value.count('\n')
  523. break
  524. else:
  525. raise RuntimeError('%r wanted to resolve '
  526. 'the token dynamically'
  527. ' but no group matched'
  528. % regex)
  529. # normal group
  530. else:
  531. data = m.group(idx + 1)
  532. if data or token not in ignore_if_empty:
  533. yield lineno, token, data
  534. lineno += data.count('\n')
  535. # strings as token just are yielded as it.
  536. else:
  537. data = m.group()
  538. # update brace/parentheses balance
  539. if tokens == 'operator':
  540. if data == '{':
  541. balancing_stack.append('}')
  542. elif data == '(':
  543. balancing_stack.append(')')
  544. elif data == '[':
  545. balancing_stack.append(']')
  546. elif data in ('}', ')', ']'):
  547. if not balancing_stack:
  548. raise TemplateSyntaxError('unexpected \'%s\'' %
  549. data, lineno, name,
  550. filename)
  551. expected_op = balancing_stack.pop()
  552. if expected_op != data:
  553. raise TemplateSyntaxError('unexpected \'%s\', '
  554. 'expected \'%s\'' %
  555. (data, expected_op),
  556. lineno, name,
  557. filename)
  558. # yield items
  559. if data or tokens not in ignore_if_empty:
  560. yield lineno, tokens, data
  561. lineno += data.count('\n')
  562. # fetch new position into new variable so that we can check
  563. # if there is a internal parsing error which would result
  564. # in an infinite loop
  565. pos2 = m.end()
  566. # handle state changes
  567. if new_state is not None:
  568. # remove the uppermost state
  569. if new_state == '#pop':
  570. stack.pop()
  571. # resolve the new state by group checking
  572. elif new_state == '#bygroup':
  573. for key, value in m.groupdict().iteritems():
  574. if value is not None:
  575. stack.append(key)
  576. break
  577. else:
  578. raise RuntimeError('%r wanted to resolve the '
  579. 'new state dynamically but'
  580. ' no group matched' %
  581. regex)
  582. # direct state name given
  583. else:
  584. stack.append(new_state)
  585. statetokens = self.rules[stack[-1]]
  586. # we are still at the same position and no stack change.
  587. # this means a loop without break condition, avoid that and
  588. # raise error
  589. elif pos2 == pos:
  590. raise RuntimeError('%r yielded empty string without '
  591. 'stack change' % regex)
  592. # publish new function and start again
  593. pos = pos2
  594. break
  595. # if loop terminated without break we havn't found a single match
  596. # either we are at the end of the file or we have a problem
  597. else:
  598. # end of text
  599. if pos >= source_length:
  600. return
  601. # something went wrong
  602. raise TemplateSyntaxError('unexpected char %r at %d' %
  603. (source[pos], pos), lineno,
  604. name, filename)