"""Implements a Jinja / Python combination lexer. The ``Lexer`` class is used to do some preprocessing. It filters out invalid operators like
the bitshift operators we don't allow in templates. It separates
template code and python code in expressions. """ import re import typing as t from ast import literal_eval from collections import deque from sys import intern
from ._identifier import pattern as name_re from .exceptions import TemplateSyntaxError from .utils import LRUCache
if t.TYPE_CHECKING: import typing_extensions as te from .environment import Environment
# cache for the lexers. Exists in order to be able to have multiple # environments with the same lexer
_lexer_cache: t.MutableMapping[t.Tuple, "Lexer"] = LRUCache(50) # type: ignore
reverse_operators = {v: k for k, v in operators.items()} assert len(operators) == len(reverse_operators), "operators dropped"
operator_re = re.compile(
f"({'|'.join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))})"
)
def _describe_token_type(token_type: str) -> str: if token_type in reverse_operators: return reverse_operators[token_type]
return {
TOKEN_COMMENT_BEGIN: "begin of comment",
TOKEN_COMMENT_END: "end of comment",
TOKEN_COMMENT: "comment",
TOKEN_LINECOMMENT: "comment",
TOKEN_BLOCK_BEGIN: "begin of statement block",
TOKEN_BLOCK_END: "end of statement block",
TOKEN_VARIABLE_BEGIN: "begin of print statement",
TOKEN_VARIABLE_END: "end of print statement",
TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",
TOKEN_LINESTATEMENT_END: "end of line statement",
TOKEN_DATA: "template data / text",
TOKEN_EOF: "end of template",
}.get(token_type, token_type)
def describe_token(token: "Token") -> str: """Returns a description of the token.""" if token.type == TOKEN_NAME: return token.value
return _describe_token_type(token.type)
def describe_token_expr(expr: str) -> str: """Like `describe_token` but for token expressions.""" if":"in expr:
type, value = expr.split(":", 1)
if type == TOKEN_NAME: return value else:
type = expr
return _describe_token_type(type)
def count_newlines(value: str) -> int: """Count the number of newline characters in the string. This is
useful for extensions that filter a stream. """ return len(newline_re.findall(value))
def compile_rules(environment: "Environment") -> t.List[t.Tuple[str, str]]: """Compiles all the rules from the environment into a list of rules."""
e = re.escape
rules = [
(
len(environment.comment_start_string),
TOKEN_COMMENT_BEGIN,
e(environment.comment_start_string),
),
(
len(environment.block_start_string),
TOKEN_BLOCK_BEGIN,
e(environment.block_start_string),
),
(
len(environment.variable_start_string),
TOKEN_VARIABLE_BEGIN,
e(environment.variable_start_string),
),
]
def test(self, expr: str) -> bool: """Test a token against a token expression. This can either be a
token type or ``'token_type:token_value'``. This can only test
against string values and types. """ # here we do a regular string equality check as test_any is usually # passed an iterable of not interned strings. if self.type == expr: returnTrue
if token.type is TOKEN_EOF:
self.stream.close() raise StopIteration
next(self.stream) return token
class TokenStream: """A token stream is an iterable that yields :class:`Token`\\s. The
parser however does not iterate over it but calls :meth:`next` to go
one token ahead. The current active token is stored as :attr:`current`. """
def __bool__(self) -> bool: return bool(self._pushed) or self.current.type isnot TOKEN_EOF
@property def eos(self) -> bool: """Are we at the end of the stream?""" returnnot self
def push(self, token: Token) -> None: """Push a token back to the stream."""
self._pushed.append(token)
def look(self) -> Token: """Look at the next token."""
old_token = next(self)
result = self.current
self.push(result)
self.current = old_token return result
def skip(self, n: int = 1) -> None: """Got n tokens ahead.""" for _ in range(n):
next(self)
def next_if(self, expr: str) -> t.Optional[Token]: """Perform the token test and return the token if it matched.
Otherwise the return value is `None`. """ if self.current.test(expr): return next(self)
returnNone
def skip_if(self, expr: str) -> bool: """Like :meth:`next_if` but only returns `True` or `False`.""" return self.next_if(expr) isnotNone
def __next__(self) -> Token: """Go one token ahead and return the old one.
Use the built-in :func:`next` instead of calling this directly. """
rv = self.current
def expect(self, expr: str) -> Token: """Expect a given token type and return it. This accepts the same
argument as :meth:`jinja2.lexer.Token.test`. """ ifnot self.current.test(expr):
expr = describe_token_expr(expr)
if self.current.type is TOKEN_EOF: raise TemplateSyntaxError(
f"unexpected end of template, expected {expr!r}.",
self.current.lineno,
self.name,
self.filename,
)
if lexer isNone:
_lexer_cache[key] = lexer = Lexer(environment)
return lexer
class OptionalLStrip(tuple): """A special tuple for marking a point in the state that can have
lstrip applied. """
__slots__ = ()
# Even though it looks like a no-op, creating instances fails # without this. def __new__(cls, *members, **kwargs): # type: ignore return super().__new__(cls, members)
class Lexer: """Class that implements a lexer for a given environment. Automatically
created by the environment class, usually you don't have to do that.
Note that the lexer isnot automatically bound to an environment.
Multiple environments can share the same lexer. """
# assemble the root lexing rule. because "|" is ungreedy # we have to sort by length so that the lexer continues working # as expected when we have parsing rules like <% for block and # <%= for variables. (if someone wants asp like syntax) # variables are just part of the rules if variable processing # is required.
root_tag_rules = compile_rules(environment)
def _normalize_newlines(self, value: str) -> str: """Replace all newlines with the configured sequence in strings and template data. """ return newline_re.sub(self.newline_sequence, value)
def wrap(
self,
stream: t.Iterable[t.Tuple[int, str, str]],
name: t.Optional[str] = None,
filename: t.Optional[str] = None,
) -> t.Iterator[Token]: """This is called with the stream as returned by `tokenize` and wraps
every token in a :class:`Token` and converts the value. """ for lineno, token, value_str in stream: if token in ignored_tokens: continue
value: t.Any = value_str
if token == TOKEN_LINESTATEMENT_BEGIN:
token = TOKEN_BLOCK_BEGIN elif token == TOKEN_LINESTATEMENT_END:
token = TOKEN_BLOCK_END # we are not interested in those tokens in the parser elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END): continue elif token == TOKEN_DATA:
value = self._normalize_newlines(value_str) elif token == "keyword":
token = value_str elif token == TOKEN_NAME:
value = value_str
ifnot value.isidentifier(): raise TemplateSyntaxError( "Invalid character in identifier", lineno, name, filename
) elif token == TOKEN_STRING: # try to unescape string try:
value = (
self._normalize_newlines(value_str[1:-1])
.encode("ascii", "backslashreplace")
.decode("unicode-escape")
) except Exception as e:
msg = str(e).split(":")[-1].strip() raise TemplateSyntaxError(msg, lineno, name, filename) from e elif token == TOKEN_INTEGER:
value = int(value_str.replace("_", ""), 0) elif token == TOKEN_FLOAT: # remove all "_" first to support more Python versions
value = literal_eval(value_str.replace("_", "")) elif token == TOKEN_OPERATOR:
token = operators[value_str]
yield Token(lineno, token, value)
def tokeniter(
self,
source: str,
name: t.Optional[str],
filename: t.Optional[str] = None,
state: t.Optional[str] = None,
) -> t.Iterator[t.Tuple[int, str, str]]: """This method tokenizes the text and returns the tokens in a
generator. Use this method if you just want to tokenize a template.
.. versionchanged:: 3.0
Only ``\\n``, ``\\r\\n`` and ``\\r`` are treated as line
breaks. """
lines = newline_re.split(source)[::2]
ifnot self.keep_trailing_newline and lines[-1] == "": del lines[-1]
whileTrue: # tokenizer loop for regex, tokens, new_state in statetokens:
m = regex.match(source, pos)
# if no match we try again with the next rule if m isNone: continue
# we only match blocks and variables if braces / parentheses # are balanced. continue parsing with the lower rule which # is the operator rule. do this only if the end tags look # like operators if balancing_stack and tokens in (
TOKEN_VARIABLE_END,
TOKEN_BLOCK_END,
TOKEN_LINESTATEMENT_END,
): continue
# tuples support more options if isinstance(tokens, tuple):
groups: t.Sequence[str] = m.groups()
if isinstance(tokens, OptionalLStrip): # Rule supports lstrip. Match will look like # text, block type, whitespace control, type, control, ...
text = groups[0] # Skipping the text and first type, every other group is the # whitespace control for each type. One of the groups will be # -, +, or empty string instead of None.
strip_sign = next(g for g in groups[2::2] if g isnotNone)
if strip_sign == "-": # Strip all whitespace between the text and the tag.
stripped = text.rstrip()
newlines_stripped = text[len(stripped) :].count("\n")
groups = [stripped, *groups[1:]] elif ( # Not marked for preserving whitespace.
strip_sign != "+" # lstrip is enabled. and self.lstrip_blocks # Not a variable expression. andnot m.groupdict().get(TOKEN_VARIABLE_BEGIN)
): # The start of text between the last newline and the tag.
l_pos = text.rfind("\n") + 1
if l_pos > 0 or line_starting: # If there's only whitespace between the newline and the # tag, strip it. if whitespace_re.fullmatch(text, l_pos):
groups = [text[:l_pos], *groups[1:]]
for idx, token in enumerate(tokens): # failure group if token.__class__ is Failure: raise token(lineno, filename) # bygroup is a bit more complex, in that case we # yield for the current token the first named # group that matched elif token == "#bygroup": for key, value in m.groupdict().items(): if value isnotNone: yield lineno, key, value
lineno += value.count("\n") break else: raise RuntimeError(
f"{regex!r} wanted to resolve the token dynamically" " but no group matched"
) # normal group else:
data = groups[idx]
if data or token notin ignore_if_empty: yield lineno, token, data
# yield items if data or tokens notin ignore_if_empty: yield lineno, tokens, data
lineno += data.count("\n")
line_starting = m.group()[-1:] == "\n" # fetch new position into new variable so that we can check # if there is a internal parsing error which would result # in an infinite loop
pos2 = m.end()
# handle state changes if new_state isnotNone: # remove the uppermost state if new_state == "#pop":
stack.pop() # resolve the new state by group checking elif new_state == "#bygroup": for key, value in m.groupdict().items(): if value isnotNone:
stack.append(key) break else: raise RuntimeError(
f"{regex!r} wanted to resolve the new state dynamically"
f" but no group matched"
) # direct state name given else:
stack.append(new_state)
statetokens = self.rules[stack[-1]] # we are still at the same position and no stack change. # this means a loop without break condition, avoid that and # raise error elif pos2 == pos: raise RuntimeError(
f"{regex!r} yielded empty string without stack change"
)
# publish new function and start again
pos = pos2 break # if loop terminated without break we haven't found a single match # either we are at the end of the file or we have a problem else: # end of text if pos >= source_length: return
# something went wrong raise TemplateSyntaxError(
f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename
)
Messung V0.5
¤ Dauer der Verarbeitung: 0.19 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.