lexer.py 28 KB

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