lexer.py 28 KB

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