Skip to content
Myr

lexer.py

This file

Path

src/jinja2/lexer.py

868 lines · 29.0 KiB · Python

Last changed by

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

History of this file

Take it

The walk stopped after 200 commits: lines older than c580dd0 point at it.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 1–5why, one step back
1"""Implements a Jinja / Python combination lexer. The ``Lexer`` class
2is used to do some preprocessing. It filters out invalid operators like3the bitshift operators we don't allow in templates. It separates4template code and python code in expressions.5"""

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 6why, one step back
6

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 7why, one step back
7import re

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 8why, one step back
8import typing as t

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 9–16why, one step back
9from ast import literal_eval
10from collections import deque11from sys import intern1213from ._identifier import pattern as name_re14from .exceptions import TemplateSyntaxError15from .utils import LRUCache16

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 17why, one step back
17if t.TYPE_CHECKING:

Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0

line 18why, one step back
18 import typing_extensions as te

Merge branch '3.1.x'David Lordbefore adoptionde61312

line 19why, one step back
19

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 20–21why, one step back
20 from .environment import Environment
21

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 22–23why, one step back
22# cache for the lexers. Exists in order to be able to have multiple
23# environments with the same lexer

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 24why, one step back
24_lexer_cache: t.MutableMapping[tuple, "Lexer"] = LRUCache(50) # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 25–31why, one step back
25
26# static regular expressions27whitespace_re = re.compile(r"\s+")28newline_re = re.compile(r"(\r\n|\r|\n)")29string_re = re.compile(30 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S31)

Merge pull request #1171 from amykyta3/feature/base-integer-literalsDavid Lordbefore adoptionfd001b2

lines 32–47why, one step back
32integer_re = re.compile(
33 r"""34 (35 0b(_?[0-1])+ # binary36 |37 0o(_?[0-7])+ # octal38 |39 0x(_?[\da-f])+ # hex40 |41 [1-9](_?\d)* # decimal42 |43 0(_?0)* # decimal zero44 )45 """,46 re.IGNORECASE | re.VERBOSE,47)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 48–164why, one step back
48float_re = re.compile(
49 r"""50 (?<!\.) # doesn't start with a .51 (\d+_)*\d+ # digits, possibly _ separated52 (53 (\.(\d+_)*\d+)? # optional fractional part54 e[+\-]?(\d+_)*\d+ # exponent part55 |56 \.(\d+_)*\d+ # required fractional part57 )58 """,59 re.IGNORECASE | re.VERBOSE,60)6162# internal the tokens and keep references to them63TOKEN_ADD = intern("add")64TOKEN_ASSIGN = intern("assign")65TOKEN_COLON = intern("colon")66TOKEN_COMMA = intern("comma")67TOKEN_DIV = intern("div")68TOKEN_DOT = intern("dot")69TOKEN_EQ = intern("eq")70TOKEN_FLOORDIV = intern("floordiv")71TOKEN_GT = intern("gt")72TOKEN_GTEQ = intern("gteq")73TOKEN_LBRACE = intern("lbrace")74TOKEN_LBRACKET = intern("lbracket")75TOKEN_LPAREN = intern("lparen")76TOKEN_LT = intern("lt")77TOKEN_LTEQ = intern("lteq")78TOKEN_MOD = intern("mod")79TOKEN_MUL = intern("mul")80TOKEN_NE = intern("ne")81TOKEN_PIPE = intern("pipe")82TOKEN_POW = intern("pow")83TOKEN_RBRACE = intern("rbrace")84TOKEN_RBRACKET = intern("rbracket")85TOKEN_RPAREN = intern("rparen")86TOKEN_SEMICOLON = intern("semicolon")87TOKEN_SUB = intern("sub")88TOKEN_TILDE = intern("tilde")89TOKEN_WHITESPACE = intern("whitespace")90TOKEN_FLOAT = intern("float")91TOKEN_INTEGER = intern("integer")92TOKEN_NAME = intern("name")93TOKEN_STRING = intern("string")94TOKEN_OPERATOR = intern("operator")95TOKEN_BLOCK_BEGIN = intern("block_begin")96TOKEN_BLOCK_END = intern("block_end")97TOKEN_VARIABLE_BEGIN = intern("variable_begin")98TOKEN_VARIABLE_END = intern("variable_end")99TOKEN_RAW_BEGIN = intern("raw_begin")100TOKEN_RAW_END = intern("raw_end")101TOKEN_COMMENT_BEGIN = intern("comment_begin")102TOKEN_COMMENT_END = intern("comment_end")103TOKEN_COMMENT = intern("comment")104TOKEN_LINESTATEMENT_BEGIN = intern("linestatement_begin")105TOKEN_LINESTATEMENT_END = intern("linestatement_end")106TOKEN_LINECOMMENT_BEGIN = intern("linecomment_begin")107TOKEN_LINECOMMENT_END = intern("linecomment_end")108TOKEN_LINECOMMENT = intern("linecomment")109TOKEN_DATA = intern("data")110TOKEN_INITIAL = intern("initial")111TOKEN_EOF = intern("eof")112113# bind operators to token types114operators = {115 "+": TOKEN_ADD,116 "-": TOKEN_SUB,117 "/": TOKEN_DIV,118 "//": TOKEN_FLOORDIV,119 "*": TOKEN_MUL,120 "%": TOKEN_MOD,121 "**": TOKEN_POW,122 "~": TOKEN_TILDE,123 "[": TOKEN_LBRACKET,124 "]": TOKEN_RBRACKET,125 "(": TOKEN_LPAREN,126 ")": TOKEN_RPAREN,127 "{": TOKEN_LBRACE,128 "}": TOKEN_RBRACE,129 "==": TOKEN_EQ,130 "!=": TOKEN_NE,131 ">": TOKEN_GT,132 ">=": TOKEN_GTEQ,133 "<": TOKEN_LT,134 "<=": TOKEN_LTEQ,135 "=": TOKEN_ASSIGN,136 ".": TOKEN_DOT,137 ":": TOKEN_COLON,138 "|": TOKEN_PIPE,139 ",": TOKEN_COMMA,140 ";": TOKEN_SEMICOLON,141}142143reverse_operators = {v: k for k, v in operators.items()}144assert len(operators) == len(reverse_operators), "operators dropped"145operator_re = re.compile(146 f"({'|'.join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))})"147)148149ignored_tokens = frozenset(150 [151 TOKEN_COMMENT_BEGIN,152 TOKEN_COMMENT,153 TOKEN_COMMENT_END,154 TOKEN_WHITESPACE,155 TOKEN_LINECOMMENT_BEGIN,156 TOKEN_LINECOMMENT_END,157 TOKEN_LINECOMMENT,158 ]159)160ignore_if_empty = frozenset(161 [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]162)163164

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 165why, one step back
165def _describe_token_type(token_type: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 166–167why, one step back
166 if token_type in reverse_operators:
167 return reverse_operators[token_type]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 168why, one step back
168

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 169–184why, one step back
169 return {
170 TOKEN_COMMENT_BEGIN: "begin of comment",171 TOKEN_COMMENT_END: "end of comment",172 TOKEN_COMMENT: "comment",173 TOKEN_LINECOMMENT: "comment",174 TOKEN_BLOCK_BEGIN: "begin of statement block",175 TOKEN_BLOCK_END: "end of statement block",176 TOKEN_VARIABLE_BEGIN: "begin of print statement",177 TOKEN_VARIABLE_END: "end of print statement",178 TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",179 TOKEN_LINESTATEMENT_END: "end of line statement",180 TOKEN_DATA: "template data / text",181 TOKEN_EOF: "end of template",182 }.get(token_type, token_type)183184

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 185why, one step back
185def describe_token(token: "Token") -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 186–188why, one step back
186 """Returns a description of the token."""
187 if token.type == TOKEN_NAME:188 return token.value

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 189why, one step back
189

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 190–192why, one step back
190 return _describe_token_type(token.type)
191192

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 193why, one step back
193def describe_token_expr(expr: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 194–196why, one step back
194 """Like `describe_token` but for token expressions."""
195 if ":" in expr:196 type, value = expr.split(":", 1)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 197why, one step back
197

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 198–201why, one step back
198 if type == TOKEN_NAME:
199 return value200 else:201 type = expr

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 202why, one step back
202

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 203–205why, one step back
203 return _describe_token_type(type)
204205

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 206why, one step back
206def count_newlines(value: str) -> int:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 207–212why, one step back
207 """Count the number of newline characters in the string. This is
208 useful for extensions that filter a stream.209 """210 return len(newline_re.findall(value))211212

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 213why, one step back
213def compile_rules(environment: "Environment") -> list[tuple[str, str]]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 214–258why, one step back
214 """Compiles all the rules from the environment into a list of rules."""
215 e = re.escape216 rules = [217 (218 len(environment.comment_start_string),219 TOKEN_COMMENT_BEGIN,220 e(environment.comment_start_string),221 ),222 (223 len(environment.block_start_string),224 TOKEN_BLOCK_BEGIN,225 e(environment.block_start_string),226 ),227 (228 len(environment.variable_start_string),229 TOKEN_VARIABLE_BEGIN,230 e(environment.variable_start_string),231 ),232 ]233234 if environment.line_statement_prefix is not None:235 rules.append(236 (237 len(environment.line_statement_prefix),238 TOKEN_LINESTATEMENT_BEGIN,239 r"^[ \t\v]*" + e(environment.line_statement_prefix),240 )241 )242 if environment.line_comment_prefix is not None:243 rules.append(244 (245 len(environment.line_comment_prefix),246 TOKEN_LINECOMMENT_BEGIN,247 r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),248 )249 )250251 return [x[1:] for x in sorted(rules, reverse=True)]252253254class Failure:255 """Class that raises a `TemplateSyntaxError` if called.256 Used by the `Lexer` to specify known errors.257 """258

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 259why, one step back
259 def __init__(

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 260why, one step back
260 self, message: str, cls: type[TemplateSyntaxError] = TemplateSyntaxError

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 261why, one step back
261 ) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 262–264why, one step back
262 self.message = message
263 self.error_class = cls264

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 265why, one step back
265 def __call__(self, lineno: int, filename: str | None) -> "te.NoReturn":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 266–268why, one step back
266 raise self.error_class(self.message, lineno, filename)
267268

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 269–272why, one step back
269class Token(t.NamedTuple):
270 lineno: int271 type: str272 value: str

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 273why, one step back
273

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 274–275why, one step back
274 def __str__(self) -> str:
275 return describe_token(self)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 276why, one step back
276

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 277why, one step back
277 def test(self, expr: str) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 278–285why, one step back
278 """Test a token against a token expression. This can either be a
279 token type or ``'token_type:token_value'``. This can only test280 against string values and types.281 """282 # here we do a regular string equality check as test_any is usually283 # passed an iterable of not interned strings.284 if self.type == expr:285 return True

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 286–287why, one step back
286
287 if ":" in expr:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 288why, one step back
288 return expr.split(":", 1) == [self.type, self.value]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 289why, one step back
289

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 290–291why, one step back
290 return False
291

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 292why, one step back
292 def test_any(self, *iterable: str) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 293why, one step back
293 """Test against multiple token expressions."""

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 294why, one step back
294 return any(self.test(expr) for expr in iterable)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 295–301why, one step back
295
296297class TokenStreamIterator:298 """The iterator for tokenstreams. Iterate over the stream299 until the eof token is reached.300 """301

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 302why, one step back
302 def __init__(self, stream: "TokenStream") -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 303–304why, one step back
303 self.stream = stream
304

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 305why, one step back
305 def __iter__(self) -> "TokenStreamIterator":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 306–307why, one step back
306 return self
307

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 308why, one step back
308 def __next__(self) -> Token:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 309why, one step back
309 token = self.stream.current

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 310why, one step back
310

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 311–312why, one step back
311 if token.type is TOKEN_EOF:
312 self.stream.close()

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 313–314why, one step back
313 raise StopIteration
314

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 315–324why, one step back
315 next(self.stream)
316 return token317318319class TokenStream:320 """A token stream is an iterable that yields :class:`Token`\\s. The321 parser however does not iterate over it but calls :meth:`next` to go322 one token ahead. The current active token is stored as :attr:`current`.323 """324

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 325–327why, one step back
325 def __init__(
326 self,327 generator: t.Iterable[Token],

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 328–329why, one step back
328 name: str | None,
329 filename: str | None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 330why, one step back
330 ):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 331why, one step back
331 self._iter = iter(generator)

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 332why, one step back
332 self._pushed: deque[Token] = deque()

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 333–338why, one step back
333 self.name = name
334 self.filename = filename335 self.closed = False336 self.current = Token(1, TOKEN_INITIAL, "")337 next(self)338

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 339why, one step back
339 def __iter__(self) -> TokenStreamIterator:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 340–341why, one step back
340 return TokenStreamIterator(self)
341

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 342why, one step back
342 def __bool__(self) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 343–345why, one step back
343 return bool(self._pushed) or self.current.type is not TOKEN_EOF
344345 @property

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 346why, one step back
346 def eos(self) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 347–349why, one step back
347 """Are we at the end of the stream?"""
348 return not self349

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 350why, one step back
350 def push(self, token: Token) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 351–353why, one step back
351 """Push a token back to the stream."""
352 self._pushed.append(token)353

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 354why, one step back
354 def look(self) -> Token:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 355–361why, one step back
355 """Look at the next token."""
356 old_token = next(self)357 result = self.current358 self.push(result)359 self.current = old_token360 return result361

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 362why, one step back
362 def skip(self, n: int = 1) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 363–366why, one step back
363 """Got n tokens ahead."""
364 for _ in range(n):365 next(self)366

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

line 367why, one step back
367 def next_if(self, expr: str) -> Token | None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 368–373why, one step back
368 """Perform the token test and return the token if it matched.
369 Otherwise the return value is `None`.370 """371 if self.current.test(expr):372 return next(self)373

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 374–376why, one step back
374 return None
375376 def skip_if(self, expr: str) -> bool:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 377–379why, one step back
377 """Like :meth:`next_if` but only returns `True` or `False`."""
378 return self.next_if(expr) is not None379

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 380why, one step back
380 def __next__(self) -> Token:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 381–385why, one step back
381 """Go one token ahead and return the old one.
382383 Use the built-in :func:`next` instead of calling this directly.384 """385 rv = self.current

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 386why, one step back
386

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 387–393why, one step back
387 if self._pushed:
388 self.current = self._pushed.popleft()389 elif self.current.type is not TOKEN_EOF:390 try:391 self.current = next(self._iter)392 except StopIteration:393 self.close()

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 394why, one step back
394

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 395–396why, one step back
395 return rv
396

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 397why, one step back
397 def close(self) -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 398–399why, one step back
398 """Close the stream."""
399 self.current = Token(self.current.lineno, TOKEN_EOF, "")

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 400why, one step back
400 self._iter = iter(())

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 401–402why, one step back
401 self.closed = True
402

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 403why, one step back
403 def expect(self, expr: str) -> Token:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 404–408why, one step back
404 """Expect a given token type and return it. This accepts the same
405 argument as :meth:`jinja2.lexer.Token.test`.406 """407 if not self.current.test(expr):408 expr = describe_token_expr(expr)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 409why, one step back
409

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 410–416why, one step back
410 if self.current.type is TOKEN_EOF:
411 raise TemplateSyntaxError(412 f"unexpected end of template, expected {expr!r}.",413 self.current.lineno,414 self.name,415 self.filename,416 )

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 417why, one step back
417

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 418–424why, one step back
418 raise TemplateSyntaxError(
419 f"expected token {expr!r}, got {describe_token(self.current)!r}",420 self.current.lineno,421 self.name,422 self.filename,423 )424

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 425why, one step back
425 return next(self)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 426why, one step back
426

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 427–428why, one step back
427
428def get_lexer(environment: "Environment") -> "Lexer":

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 429–444why, one step back
429 """Return a lexer which is probably cached."""
430 key = (431 environment.block_start_string,432 environment.block_end_string,433 environment.variable_start_string,434 environment.variable_end_string,435 environment.comment_start_string,436 environment.comment_end_string,437 environment.line_statement_prefix,438 environment.line_comment_prefix,439 environment.trim_blocks,440 environment.lstrip_blocks,441 environment.newline_sequence,442 environment.keep_trailing_newline,443 )444 lexer = _lexer_cache.get(key)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 445why, one step back
445

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 446why, one step back
446 if lexer is None:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 447–448why, one step back
447 _lexer_cache[key] = lexer = Lexer(environment)
448

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 449–451why, one step back
449 return lexer
450451

switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81

line 452why, one step back
452class OptionalLStrip(tuple): # type: ignore[type-arg]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 453–460why, one step back
453 """A special tuple for marking a point in the state that can have
454 lstrip applied.455 """456457 __slots__ = ()458459 # Even though it looks like a no-op, creating instances fails460 # without this.

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 461why, one step back
461 def __new__(cls, *members, **kwargs): # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 462–464why, one step back
462 return super().__new__(cls, members)
463464

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 465–466why, one step back
465class _Rule(t.NamedTuple):
466 pattern: t.Pattern[str]

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 467–468why, one step back
467 tokens: str | tuple[str, ...] | tuple[Failure]
468 command: str | None

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 469–470why, one step back
469
470

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 471–478why, one step back
471class Lexer:
472 """Class that implements a lexer for a given environment. Automatically473 created by the environment class, usually you don't have to do that.474475 Note that the lexer is not automatically bound to an environment.476 Multiple environments can share the same lexer.477 """478

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 479why, one step back
479 def __init__(self, environment: "Environment") -> None:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 480–482why, one step back
480 # shortcuts
481 e = re.escape482

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 483why, one step back
483 def c(x: str) -> t.Pattern[str]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 484–486why, one step back
484 return re.compile(x, re.M | re.S)
485486 # lexing rules for tags

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 487why, one step back
487 tag_rules: list[_Rule] = [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 488–493why, one step back
488 _Rule(whitespace_re, TOKEN_WHITESPACE, None),
489 _Rule(float_re, TOKEN_FLOAT, None),490 _Rule(integer_re, TOKEN_INTEGER, None),491 _Rule(name_re, TOKEN_NAME, None),492 _Rule(string_re, TOKEN_STRING, None),493 _Rule(operator_re, TOKEN_OPERATOR, None),

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 494–511why, one step back
494 ]
495496 # assemble the root lexing rule. because "|" is ungreedy497 # we have to sort by length so that the lexer continues working498 # as expected when we have parsing rules like <% for block and499 # <%= for variables. (if someone wants asp like syntax)500 # variables are just part of the rules if variable processing501 # is required.502 root_tag_rules = compile_rules(environment)503504 block_start_re = e(environment.block_start_string)505 block_end_re = e(environment.block_end_string)506 comment_end_re = e(environment.comment_end_string)507 variable_end_re = e(environment.variable_end_string)508509 # block suffix if trimming is enabled510 block_suffix_re = "\\n?" if environment.trim_blocks else ""511

Merge pull request #1368 from mvolfik/refactor-regexDavid Lordbefore adoption4bbb1fb

line 512why, one step back
512 self.lstrip_blocks = environment.lstrip_blocks

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 513–517why, one step back
513
514 self.newline_sequence = environment.newline_sequence515 self.keep_trailing_newline = environment.keep_trailing_newline516517 root_raw_re = (

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

lines 518–519why, one step back
518 rf"(?P<raw_begin>{block_start_re}(\-|\+|)\s*raw\s*"
519 rf"(?:\-{block_end_re}\s*|{block_end_re}))"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 520–521why, one step back
520 )
521 root_parts_re = "|".join(

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

line 522why, one step back
522 [root_raw_re] + [rf"(?P<{n}>{r}(\-|\+|))" for n, r in root_tag_rules]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 523–525why, one step back
523 )
524525 # global lexing rules

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 526why, one step back
526 self.rules: dict[str, list[_Rule]] = {

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 527–528why, one step back
527 "root": [
528 # directives

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 529why, one step back
529 _Rule(

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

line 530why, one step back
530 c(rf"(.*?)(?:{root_parts_re})"),

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 531why, one step back
531 OptionalLStrip(TOKEN_DATA, "#bygroup"), # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 532–534why, one step back
532 "#bygroup",
533 ),534 # data

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 535why, one step back
535 _Rule(c(".+"), TOKEN_DATA, None),

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 536–538why, one step back
536 ],
537 # comments538 TOKEN_COMMENT_BEGIN: [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 539why, one step back
539 _Rule(

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 540why, one step back
540 c(

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

lines 541–542why, one step back
541 rf"(.*?)((?:\+{comment_end_re}|\-{comment_end_re}\s*"
542 rf"|{comment_end_re}{block_suffix_re}))"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 543–546why, one step back
543 ),
544 (TOKEN_COMMENT, TOKEN_COMMENT_END),545 "#pop",546 ),

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 547why, one step back
547 _Rule(c(r"(.)"), (Failure("Missing end of comment tag"),), None),

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 548–550why, one step back
548 ],
549 # blocks550 TOKEN_BLOCK_BEGIN: [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 551why, one step back
551 _Rule(

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 552why, one step back
552 c(

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

lines 553–554why, one step back
553 rf"(?:\+{block_end_re}|\-{block_end_re}\s*"
554 rf"|{block_end_re}{block_suffix_re})"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 555–562why, one step back
555 ),
556 TOKEN_BLOCK_END,557 "#pop",558 ),559 ]560 + tag_rules,561 # variables562 TOKEN_VARIABLE_BEGIN: [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 563why, one step back
563 _Rule(

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

line 564why, one step back
564 c(rf"\-{variable_end_re}\s*|{variable_end_re}"),

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 565–571why, one step back
565 TOKEN_VARIABLE_END,
566 "#pop",567 )568 ]569 + tag_rules,570 # raw block571 TOKEN_RAW_BEGIN: [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 572why, one step back
572 _Rule(

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 573why, one step back
573 c(

Merge branch '3.0.x'David Lordbefore adoption80e6c4b

lines 574–576why, one step back
574 rf"(.*?)((?:{block_start_re}(\-|\+|))\s*endraw\s*"
575 rf"(?:\+{block_end_re}|\-{block_end_re}\s*"576 rf"|{block_end_re}{block_suffix_re}))"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 577why, one step back
577 ),

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 578why, one step back
578 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END), # type: ignore

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 579–580why, one step back
579 "#pop",
580 ),

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 581why, one step back
581 _Rule(c(r"(.)"), (Failure("Missing end of raw directive"),), None),

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 582–584why, one step back
582 ],
583 # line statements584 TOKEN_LINESTATEMENT_BEGIN: [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 585why, one step back
585 _Rule(c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 586–589why, one step back
586 ]
587 + tag_rules,588 # line comments589 TOKEN_LINECOMMENT_BEGIN: [

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 590why, one step back
590 _Rule(

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 591–597why, one step back
591 c(r"(.*?)()(?=\n|$)"),
592 (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),593 "#pop",594 )595 ],596 }597

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 598why, one step back
598 def _normalize_newlines(self, value: str) -> str:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 599–603why, one step back
599 """Replace all newlines with the configured sequence in strings
600 and template data.601 """602 return newline_re.sub(self.newline_sequence, value)603

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 604–606why, one step back
604 def tokenize(
605 self,606 source: str,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 607–609why, one step back
607 name: str | None = None,
608 filename: str | None = None,609 state: str | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 610why, one step back
610 ) -> TokenStream:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 611–614why, one step back
611 """Calls tokeniter + tokenize and wraps it in a token stream."""
612 stream = self.tokeniter(source, name, filename, state)613 return TokenStream(self.wrap(stream, name, filename), name, filename)614

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 615–616why, one step back
615 def wrap(
616 self,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 617why, one step back
617 stream: t.Iterable[tuple[int, str, str]],

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 618–619why, one step back
618 name: str | None = None,
619 filename: str | None = None,

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 620why, one step back
620 ) -> t.Iterator[Token]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 621–623why, one step back
621 """This is called with the stream as returned by `tokenize` and wraps
622 every token in a :class:`Token` and converts the value.623 """

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 624why, one step back
624 for lineno, token, value_str in stream:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 625–626why, one step back
625 if token in ignored_tokens:
626 continue

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 627–630why, one step back
627
628 value: t.Any = value_str629630 if token == TOKEN_LINESTATEMENT_BEGIN:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 631–637why, one step back
631 token = TOKEN_BLOCK_BEGIN
632 elif token == TOKEN_LINESTATEMENT_END:633 token = TOKEN_BLOCK_END634 # we are not interested in those tokens in the parser635 elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):636 continue637 elif token == TOKEN_DATA:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 638why, one step back
638 value = self._normalize_newlines(value_str)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 639why, one step back
639 elif token == "keyword":

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 640why, one step back
640 token = value_str

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 641why, one step back
641 elif token == TOKEN_NAME:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 642–643why, one step back
642 value = value_str
643

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 644–651why, one step back
644 if not value.isidentifier():
645 raise TemplateSyntaxError(646 "Invalid character in identifier", lineno, name, filename647 )648 elif token == TOKEN_STRING:649 # try to unescape string650 try:651 value = (

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 652why, one step back
652 self._normalize_newlines(value_str[1:-1])

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 653–657why, one step back
653 .encode("ascii", "backslashreplace")
654 .decode("unicode-escape")655 )656 except Exception as e:657 msg = str(e).split(":")[-1].strip()

Merge branch '3.0.x'David Lordbefore adoptione20a52e

line 658why, one step back
658 raise TemplateSyntaxError(msg, lineno, name, filename) from e

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 659why, one step back
659 elif token == TOKEN_INTEGER:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 660why, one step back
660 value = int(value_str.replace("_", ""), 0)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 661–662why, one step back
661 elif token == TOKEN_FLOAT:
662 # remove all "_" first to support more Python versions

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 663why, one step back
663 value = literal_eval(value_str.replace("_", ""))

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 664why, one step back
664 elif token == TOKEN_OPERATOR:

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 665–666why, one step back
665 token = operators[value_str]
666

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 667–668why, one step back
667 yield Token(lineno, token, value)
668

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

lines 669–671why, one step back
669 def tokeniter(
670 self,671 source: str,

drop end of life python versions (#2096)David Lordbefore adoption49c48a0

lines 672–674why, one step back
672 name: str | None,
673 filename: str | None = None,674 state: str | None = None,

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 675why, one step back
675 ) -> t.Iterator[tuple[int, str, str]]:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 676why, one step back
676 """This method tokenizes the text and returns the tokens in a

Merge pull request #1366 from mvolfik/fix-unicode-newlinesDavid Lordbefore adoption4abb2a0

lines 677–681why, one step back
677 generator. Use this method if you just want to tokenize a template.
678679 .. versionchanged:: 3.0680 Only ``\\n``, ``\\r\\n`` and ``\\r`` are treated as line681 breaks.

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 682why, one step back
682 """

Merge pull request #1366 from mvolfik/fix-unicode-newlinesDavid Lordbefore adoption4abb2a0

lines 683–687why, one step back
683 lines = newline_re.split(source)[::2]
684685 if not self.keep_trailing_newline and lines[-1] == "":686 del lines[-1]687

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 688–691why, one step back
688 source = "\n".join(lines)
689 pos = 0690 lineno = 1691 stack = ["root"]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 692why, one step back
692

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 693–695why, one step back
693 if state is not None and state != "root":
694 assert state in ("variable", "block"), "invalid state"695 stack.append(state + "_begin")

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 696why, one step back
696

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 697–698why, one step back
697 statetokens = self.rules[stack[-1]]
698 source_length = len(source)

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 699why, one step back
699 balancing_stack: list[str] = []

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 700–702why, one step back
700 newlines_stripped = 0
701 line_starting = True702

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 703why, one step back
703 while True:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 704–706why, one step back
704 # tokenizer loop
705 for regex, tokens, new_state in statetokens:706 m = regex.match(source, pos)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 707why, one step back
707

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 708–724why, one step back
708 # if no match we try again with the next rule
709 if m is None:710 continue711712 # we only match blocks and variables if braces / parentheses713 # are balanced. continue parsing with the lower rule which714 # is the operator rule. do this only if the end tags look715 # like operators716 if balancing_stack and tokens in (717 TOKEN_VARIABLE_END,718 TOKEN_BLOCK_END,719 TOKEN_LINESTATEMENT_END,720 ):721 continue722723 # tuples support more options724 if isinstance(tokens, tuple):

Merge branch '3.0.x'David Lordbefore adoption896a621

line 725why, one step back
725 groups: t.Sequence[str] = m.groups()

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 726–739why, one step back
726
727 if isinstance(tokens, OptionalLStrip):728 # Rule supports lstrip. Match will look like729 # text, block type, whitespace control, type, control, ...730 text = groups[0]731 # Skipping the text and first type, every other group is the732 # whitespace control for each type. One of the groups will be733 # -, +, or empty string instead of None.734 strip_sign = next(g for g in groups[2::2] if g is not None)735736 if strip_sign == "-":737 # Strip all whitespace between the text and the tag.738 stripped = text.rstrip()739 newlines_stripped = text[len(stripped) :].count("\n")

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 740why, one step back
740 groups = [stripped, *groups[1:]]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 741–744why, one step back
741 elif (
742 # Not marked for preserving whitespace.743 strip_sign != "+"744 # lstrip is enabled.

Merge pull request #1368 from mvolfik/refactor-regexDavid Lordbefore adoption4bbb1fb

line 745why, one step back
745 and self.lstrip_blocks

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 746–750why, one step back
746 # Not a variable expression.
747 and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)748 ):749 # The start of text between the last newline and the tag.750 l_pos = text.rfind("\n") + 1

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 751why, one step back
751

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 752–754why, one step back
752 if l_pos > 0 or line_starting:
753 # If there's only whitespace between the newline and the754 # tag, strip it.

Merge pull request #1368 from mvolfik/refactor-regexDavid Lordbefore adoption4bbb1fb

line 755why, one step back
755 if whitespace_re.fullmatch(text, l_pos):

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 756why, one step back
756 groups = [text[:l_pos], *groups[1:]]

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 757–759why, one step back
757
758 for idx, token in enumerate(tokens):759 # failure group

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 760why, one step back
760 if isinstance(token, Failure):

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 761–778why, one step back
761 raise token(lineno, filename)
762 # bygroup is a bit more complex, in that case we763 # yield for the current token the first named764 # group that matched765 elif token == "#bygroup":766 for key, value in m.groupdict().items():767 if value is not None:768 yield lineno, key, value769 lineno += value.count("\n")770 break771 else:772 raise RuntimeError(773 f"{regex!r} wanted to resolve the token dynamically"774 " but no group matched"775 )776 # normal group777 else:778 data = groups[idx]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 779why, one step back
779

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 780why, one step back
780 if data or token not in ignore_if_empty:

Merge branch 'stable'David Lordbefore adoption6aeab5d

line 781why, one step back
781 yield lineno, token, data # type: ignore[misc]

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 782why, one step back
782

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 783–788why, one step back
783 lineno += data.count("\n") + newlines_stripped
784 newlines_stripped = 0785786 # strings as token just are yielded as it.787 else:788 data = m.group()

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 789why, one step back
789

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 790–802why, one step back
790 # update brace/parentheses balance
791 if tokens == TOKEN_OPERATOR:792 if data == "{":793 balancing_stack.append("}")794 elif data == "(":795 balancing_stack.append(")")796 elif data == "[":797 balancing_stack.append("]")798 elif data in ("}", ")", "]"):799 if not balancing_stack:800 raise TemplateSyntaxError(801 f"unexpected '{data}'", lineno, name, filename802 )

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 803why, one step back
803

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 804why, one step back
804 expected_op = balancing_stack.pop()

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 805why, one step back
805

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 806–812why, one step back
806 if expected_op != data:
807 raise TemplateSyntaxError(808 f"unexpected '{data}', expected '{expected_op}'",809 lineno,810 name,811 filename,812 )

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 813why, one step back
813

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 814–816why, one step back
814 # yield items
815 if data or tokens not in ignore_if_empty:816 yield lineno, tokens, data

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 817why, one step back
817

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 818–844why, one step back
818 lineno += data.count("\n")
819820 line_starting = m.group()[-1:] == "\n"821 # fetch new position into new variable so that we can check822 # if there is a internal parsing error which would result823 # in an infinite loop824 pos2 = m.end()825826 # handle state changes827 if new_state is not None:828 # remove the uppermost state829 if new_state == "#pop":830 stack.pop()831 # resolve the new state by group checking832 elif new_state == "#bygroup":833 for key, value in m.groupdict().items():834 if value is not None:835 stack.append(key)836 break837 else:838 raise RuntimeError(839 f"{regex!r} wanted to resolve the new state dynamically"840 f" but no group matched"841 )842 # direct state name given843 else:844 stack.append(new_state)

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 845why, one step back
845

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 846–853why, one step back
846 statetokens = self.rules[stack[-1]]
847 # we are still at the same position and no stack change.848 # this means a loop without break condition, avoid that and849 # raise error850 elif pos2 == pos:851 raise RuntimeError(852 f"{regex!r} yielded empty string without stack change"853 )

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 854why, one step back
854

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 855–863why, one step back
855 # publish new function and start again
856 pos = pos2857 break858 # if loop terminated without break we haven't found a single match859 # either we are at the end of the file or we have a problem860 else:861 # end of text862 if pos >= source_length:863 return

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 864why, one step back
864

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 865–868why, one step back
865 # something went wrong
866 raise TemplateSyntaxError(867 f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename868 )