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 fileTake 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 back1"""Implements a Jinja / Python combination lexer. The ``Lexer`` class2is 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 back6update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 7why, one step back7import reMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 8why, one step back8import typing as tupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 9–16why, one step back9from ast import literal_eval10from collections import deque11from sys import intern1213from ._identifier import pattern as name_re14from .exceptions import TemplateSyntaxError15from .utils import LRUCache16Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 17why, one step back17if t.TYPE_CHECKING:Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 18why, one step back18 import typing_extensions as teMerge branch '3.1.x'David Lordbefore adoptionde61312
line 19why, one step back19Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 20–21why, one step back20 from .environment import Environment21update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 22–23why, one step back22# cache for the lexers. Exists in order to be able to have multiple23# environments with the same lexerUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 24why, one step back24_lexer_cache: t.MutableMapping[tuple, "Lexer"] = LRUCache(50) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 25–31why, one step back2526# 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 back32integer_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 back48float_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)163164Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 165why, one step back165def _describe_token_type(token_type: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 166–167why, one step back166 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 back168update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 169–184why, one step back169 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)183184Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 185why, one step back185def describe_token(token: "Token") -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 186–188why, one step back186 """Returns a description of the token."""187 if token.type == TOKEN_NAME:188 return token.valueMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 189why, one step back189update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 190–192why, one step back190 return _describe_token_type(token.type)191192Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 193why, one step back193def describe_token_expr(expr: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 194–196why, one step back194 """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 back197update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 198–201why, one step back198 if type == TOKEN_NAME:199 return value200 else:201 type = exprMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 202why, one step back202update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 203–205why, one step back203 return _describe_token_type(type)204205Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 206why, one step back206def count_newlines(value: str) -> int:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 207–212why, one step back207 """Count the number of newline characters in the string. This is208 useful for extensions that filter a stream.209 """210 return len(newline_re.findall(value))211212Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 213why, one step back213def compile_rules(environment: "Environment") -> list[tuple[str, str]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 214–258why, one step back214 """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 """258Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 259why, one step back259 def __init__(Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 260why, one step back260 self, message: str, cls: type[TemplateSyntaxError] = TemplateSyntaxErrorMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 261why, one step back261 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 262–264why, one step back262 self.message = message263 self.error_class = cls264drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 265why, one step back265 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 back266 raise self.error_class(self.message, lineno, filename)267268Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 269–272why, one step back269class Token(t.NamedTuple):270 lineno: int271 type: str272 value: strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 273why, one step back273Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 274–275why, one step back274 def __str__(self) -> str:275 return describe_token(self)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 276why, one step back276Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 277why, one step back277 def test(self, expr: str) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 278–285why, one step back278 """Test a token against a token expression. This can either be a279 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 TrueMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 286–287why, one step back286287 if ":" in expr:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 288why, one step back288 return expr.split(":", 1) == [self.type, self.value]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 289why, one step back289update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 290–291why, one step back290 return False291Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 292why, one step back292 def test_any(self, *iterable: str) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 293why, one step back293 """Test against multiple token expressions."""Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 294why, one step back294 return any(self.test(expr) for expr in iterable)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 295–301why, one step back295296297class TokenStreamIterator:298 """The iterator for tokenstreams. Iterate over the stream299 until the eof token is reached.300 """301Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 302why, one step back302 def __init__(self, stream: "TokenStream") -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 303–304why, one step back303 self.stream = stream304Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 305why, one step back305 def __iter__(self) -> "TokenStreamIterator":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 306–307why, one step back306 return self307Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 308why, one step back308 def __next__(self) -> Token:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 309why, one step back309 token = self.stream.currentMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 310why, one step back310update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 311–312why, one step back311 if token.type is TOKEN_EOF:312 self.stream.close()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 313–314why, one step back313 raise StopIteration314update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 315–324why, one step back315 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 """324Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 325–327why, one step back325 def __init__(326 self,327 generator: t.Iterable[Token],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 328–329why, one step back328 name: str | None,329 filename: str | None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 330why, one step back330 ):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 331why, one step back331 self._iter = iter(generator)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 332why, one step back332 self._pushed: deque[Token] = deque()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 333–338why, one step back333 self.name = name334 self.filename = filename335 self.closed = False336 self.current = Token(1, TOKEN_INITIAL, "")337 next(self)338Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 339why, one step back339 def __iter__(self) -> TokenStreamIterator:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 340–341why, one step back340 return TokenStreamIterator(self)341Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 342why, one step back342 def __bool__(self) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 343–345why, one step back343 return bool(self._pushed) or self.current.type is not TOKEN_EOF344345 @propertyMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 346why, one step back346 def eos(self) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 347–349why, one step back347 """Are we at the end of the stream?"""348 return not self349Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 350why, one step back350 def push(self, token: Token) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 351–353why, one step back351 """Push a token back to the stream."""352 self._pushed.append(token)353Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 354why, one step back354 def look(self) -> Token:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 355–361why, one step back355 """Look at the next token."""356 old_token = next(self)357 result = self.current358 self.push(result)359 self.current = old_token360 return result361Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 362why, one step back362 def skip(self, n: int = 1) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 363–366why, one step back363 """Got n tokens ahead."""364 for _ in range(n):365 next(self)366drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 367why, one step back367 def next_if(self, expr: str) -> Token | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 368–373why, one step back368 """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)373Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 374–376why, one step back374 return None375376 def skip_if(self, expr: str) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 377–379why, one step back377 """Like :meth:`next_if` but only returns `True` or `False`."""378 return self.next_if(expr) is not None379Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 380why, one step back380 def __next__(self) -> Token:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 381–385why, one step back381 """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.currentMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 386why, one step back386update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 387–393why, one step back387 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 back394update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 395–396why, one step back395 return rv396Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 397why, one step back397 def close(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 398–399why, one step back398 """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 back400 self._iter = iter(())update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 401–402why, one step back401 self.closed = True402Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 403why, one step back403 def expect(self, expr: str) -> Token:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 404–408why, one step back404 """Expect a given token type and return it. This accepts the same405 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 back409update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 410–416why, one step back410 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 back417update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 418–424why, one step back418 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 )424Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 425why, one step back425 return next(self)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 426why, one step back426Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 427–428why, one step back427428def get_lexer(environment: "Environment") -> "Lexer":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 429–444why, one step back429 """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 back445update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 446why, one step back446 if lexer is None:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 447–448why, one step back447 _lexer_cache[key] = lexer = Lexer(environment)448update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 449–451why, one step back449 return lexer450451switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
line 452why, one step back452class OptionalLStrip(tuple): # type: ignore[type-arg]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 453–460why, one step back453 """A special tuple for marking a point in the state that can have454 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 back461 def __new__(cls, *members, **kwargs): # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 462–464why, one step back462 return super().__new__(cls, members)463464Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 465–466why, one step back465class _Rule(t.NamedTuple):466 pattern: t.Pattern[str]drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 467–468why, one step back467 tokens: str | tuple[str, ...] | tuple[Failure]468 command: str | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 469–470why, one step back469470update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 471–478why, one step back471class 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 """478Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 479why, one step back479 def __init__(self, environment: "Environment") -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 480–482why, one step back480 # shortcuts481 e = re.escape482Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 483why, one step back483 def c(x: str) -> t.Pattern[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 484–486why, one step back484 return re.compile(x, re.M | re.S)485486 # lexing rules for tagsUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 487why, one step back487 tag_rules: list[_Rule] = [Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 488–493why, one step back488 _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 back494 ]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 ""511Merge pull request #1368 from mvolfik/refactor-regexDavid Lordbefore adoption4bbb1fb
line 512why, one step back512 self.lstrip_blocks = environment.lstrip_blocksupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 513–517why, one step back513514 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 back518 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 back520 )521 root_parts_re = "|".join(Merge branch '3.0.x'David Lordbefore adoption80e6c4b
line 522why, one step back522 [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 back523 )524525 # global lexing rulesUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 526why, one step back526 self.rules: dict[str, list[_Rule]] = {update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 527–528why, one step back527 "root": [528 # directivesMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 529why, one step back529 _Rule(Merge branch '3.0.x'David Lordbefore adoption80e6c4b
line 530why, one step back530 c(rf"(.*?)(?:{root_parts_re})"),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 531why, one step back531 OptionalLStrip(TOKEN_DATA, "#bygroup"), # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 532–534why, one step back532 "#bygroup",533 ),534 # dataMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 535why, one step back535 _Rule(c(".+"), TOKEN_DATA, None),update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 536–538why, one step back536 ],537 # comments538 TOKEN_COMMENT_BEGIN: [Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 539why, one step back539 _Rule(update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 540why, one step back540 c(Merge branch '3.0.x'David Lordbefore adoption80e6c4b
lines 541–542why, one step back541 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 back543 ),544 (TOKEN_COMMENT, TOKEN_COMMENT_END),545 "#pop",546 ),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 547why, one step back547 _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 back548 ],549 # blocks550 TOKEN_BLOCK_BEGIN: [Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 551why, one step back551 _Rule(update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 552why, one step back552 c(Merge branch '3.0.x'David Lordbefore adoption80e6c4b
lines 553–554why, one step back553 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 back555 ),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 back563 _Rule(Merge branch '3.0.x'David Lordbefore adoption80e6c4b
line 564why, one step back564 c(rf"\-{variable_end_re}\s*|{variable_end_re}"),update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 565–571why, one step back565 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 back572 _Rule(update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 573why, one step back573 c(Merge branch '3.0.x'David Lordbefore adoption80e6c4b
lines 574–576why, one step back574 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 back577 ),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 578why, one step back578 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END), # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 579–580why, one step back579 "#pop",580 ),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 581why, one step back581 _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 back582 ],583 # line statements584 TOKEN_LINESTATEMENT_BEGIN: [Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 585why, one step back585 _Rule(c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 586–589why, one step back586 ]587 + tag_rules,588 # line comments589 TOKEN_LINECOMMENT_BEGIN: [Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 590why, one step back590 _Rule(update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 591–597why, one step back591 c(r"(.*?)()(?=\n|$)"),592 (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),593 "#pop",594 )595 ],596 }597Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 598why, one step back598 def _normalize_newlines(self, value: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 599–603why, one step back599 """Replace all newlines with the configured sequence in strings600 and template data.601 """602 return newline_re.sub(self.newline_sequence, value)603Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 604–606why, one step back604 def tokenize(605 self,606 source: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 607–609why, one step back607 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 back610 ) -> TokenStream:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 611–614why, one step back611 """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)614Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 615–616why, one step back615 def wrap(616 self,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 617why, one step back617 stream: t.Iterable[tuple[int, str, str]],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 618–619why, one step back618 name: str | None = None,619 filename: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 620why, one step back620 ) -> t.Iterator[Token]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 621–623why, one step back621 """This is called with the stream as returned by `tokenize` and wraps622 every token in a :class:`Token` and converts the value.623 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 624why, one step back624 for lineno, token, value_str in stream:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 625–626why, one step back625 if token in ignored_tokens:626 continueMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 627–630why, one step back627628 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 back631 token = TOKEN_BLOCK_BEGIN632 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 back638 value = self._normalize_newlines(value_str)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 639why, one step back639 elif token == "keyword":Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 640why, one step back640 token = value_strupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 641why, one step back641 elif token == TOKEN_NAME:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 642–643why, one step back642 value = value_str643update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 644–651why, one step back644 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 back652 self._normalize_newlines(value_str[1:-1])update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 653–657why, one step back653 .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 back658 raise TemplateSyntaxError(msg, lineno, name, filename) from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 659why, one step back659 elif token == TOKEN_INTEGER:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 660why, one step back660 value = int(value_str.replace("_", ""), 0)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 661–662why, one step back661 elif token == TOKEN_FLOAT:662 # remove all "_" first to support more Python versionsMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 663why, one step back663 value = literal_eval(value_str.replace("_", ""))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 664why, one step back664 elif token == TOKEN_OPERATOR:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 665–666why, one step back665 token = operators[value_str]666update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 667–668why, one step back667 yield Token(lineno, token, value)668Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 669–671why, one step back669 def tokeniter(670 self,671 source: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 672–674why, one step back672 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 back675 ) -> t.Iterator[tuple[int, str, str]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 676why, one step back676 """This method tokenizes the text and returns the tokens in aMerge pull request #1366 from mvolfik/fix-unicode-newlinesDavid Lordbefore adoption4abb2a0
lines 677–681why, one step back677 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 back682 """Merge pull request #1366 from mvolfik/fix-unicode-newlinesDavid Lordbefore adoption4abb2a0
lines 683–687why, one step back683 lines = newline_re.split(source)[::2]684685 if not self.keep_trailing_newline and lines[-1] == "":686 del lines[-1]687update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 688–691why, one step back688 source = "\n".join(lines)689 pos = 0690 lineno = 1691 stack = ["root"]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 692why, one step back692update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 693–695why, one step back693 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 back696update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 697–698why, one step back697 statetokens = self.rules[stack[-1]]698 source_length = len(source)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 699why, one step back699 balancing_stack: list[str] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 700–702why, one step back700 newlines_stripped = 0701 line_starting = True702Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 703why, one step back703 while True:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 704–706why, one step back704 # tokenizer loop705 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 back707update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 708–724why, one step back708 # if no match we try again with the next rule709 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 back725 groups: t.Sequence[str] = m.groups()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 726–739why, one step back726727 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 back740 groups = [stripped, *groups[1:]]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 741–744why, one step back741 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 back745 and self.lstrip_blocksupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 746–750why, one step back746 # 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") + 1Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 751why, one step back751update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 752–754why, one step back752 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 back755 if whitespace_re.fullmatch(text, l_pos):Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 756why, one step back756 groups = [text[:l_pos], *groups[1:]]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 757–759why, one step back757758 for idx, token in enumerate(tokens):759 # failure groupMerge branch 'stable'David Lordbefore adoption6aeab5d
line 760why, one step back760 if isinstance(token, Failure):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 761–778why, one step back761 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 back779update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 780why, one step back780 if data or token not in ignore_if_empty:Merge branch 'stable'David Lordbefore adoption6aeab5d
line 781why, one step back781 yield lineno, token, data # type: ignore[misc]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 782why, one step back782update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 783–788why, one step back783 lineno += data.count("\n") + newlines_stripped784 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 back789update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 790–802why, one step back790 # update brace/parentheses balance791 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 back803update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 804why, one step back804 expected_op = balancing_stack.pop()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 805why, one step back805update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 806–812why, one step back806 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 back813update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 814–816why, one step back814 # yield items815 if data or tokens not in ignore_if_empty:816 yield lineno, tokens, dataMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 817why, one step back817update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 818–844why, one step back818 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 back845update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 846–853why, one step back846 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 back854update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 855–863why, one step back855 # publish new function and start again856 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 returnMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 864why, one step back864update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 865–868why, one step back865 # something went wrong866 raise TemplateSyntaxError(867 f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename868 )