Skip to content
Myr

Merge pull request #1412 from pallets/typing

Before adoption: this commit came in with the history the project adopted, so no landing records it.

add type annotations

authored by David Lord · committed by GitHub · parents f418f71, be15556 · Browse files · 27 files+2467 added−1515 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

27 files+2467 added−1515 removed

  • tests:+1 added−1 removed
  • other:+2466 added−1514 removed

27 files+2467 added−1515 removed

modified:docs/examples/inline_gettext_extension.py+1 added-1 removed
28 unmodified lines
2930 pos = 031 lineno = token.lineno3233 while 1:33 while True:34 if not paren_stack:35 match = _outside_re.search(token.value, pos)36 else:37 match = _inside_re.search(token.value, pos)
35 unmodified lines
modified:src/jinja2/async_utils.py+18 added-26 removed
3 unmodified lines
45from .utils import _PassArg6from .utils import pass_eval_context78if t.TYPE_CHECKING:9 V = t.TypeVar("V")8V = t.TypeVar("V")91012def async_variant(normal_func):13 def decorator(async_func):11def async_variant(normal_func): # type: ignore12 def decorator(async_func): # type: ignore13 pass_arg = _PassArg.from_obj(normal_func)14 need_eval_context = pass_arg is None1516 if pass_arg is _PassArg.environment:1719 def is_async(args):20 return args[0].is_async18 def is_async(args: t.Any) -> bool:19 return t.cast(bool, args[0].is_async)2021 else:2224 def is_async(args):25 return args[0].environment.is_async23 def is_async(args: t.Any) -> bool:24 return t.cast(bool, args[0].environment.is_async)2526 @wraps(normal_func)28 def wrapper(*args, **kwargs):27 def wrapper(*args, **kwargs): # type: ignore28 b = is_async(args)2930 if need_eval_context:31 args = args[1:]
11 unmodified lines
4344 return decorator454648async def auto_await(value):47async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":48 if inspect.isawaitable(value):50 return await value49 return await t.cast("t.Awaitable[V]", value)5052 return value51 return t.cast("V", value)525355async def auto_aiter(iterable):54async def auto_aiter(55 iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",56) -> "t.AsyncIterator[V]":57 if hasattr(iterable, "__aiter__"):57 async for item in iterable:58 async for item in t.cast("t.AsyncIterable[V]", iterable):59 yield item60 else:60 for item in iterable:61 for item in t.cast("t.Iterable[V]", iterable):62 yield item636465async def auto_to_list(66 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",66) -> "t.List[V]":67 seq = []6869 if hasattr(value, "__aiter__"):70 async for item in t.cast(t.AsyncIterable, value):71 seq.append(item)72 else:73 for item in t.cast(t.Iterable, value):74 seq.append(item)7576 return seq67) -> t.List["V"]:68 return [x async for x in auto_aiter(value)]
modified:src/jinja2/bccache.py+68 added-49 removed
11 unmodified lines
12import pickle13import stat14import sys15import tempfile16import typing as t17from hashlib import sha118from io import BytesIO19from types import CodeType2019from .utils import open_if_exists21if t.TYPE_CHECKING:22 import typing_extensions as te23 from .environment import Environment2425 class _MemcachedClient(te.Protocol):26 def get(self, key: str) -> bytes:27 ...2829 def set(self, key: str, value: bytes, timeout: t.Optional[int] = None) -> None:30 ...313233bc_version = 534# Magic bytes to identify Jinja bytecode cache files. Contains the35# Python major and minor version to avoid loading incompatible bytecode36# if a project upgrades its Python version.
12 unmodified lines
49 to automatically reject outdated cache material. Individual bytecode50 cache subclasses don't have to care about cache invalidation.51 """5241 def __init__(self, environment, key, checksum):53 def __init__(self, environment: "Environment", key: str, checksum: str) -> None:54 self.environment = environment55 self.key = key56 self.checksum = checksum57 self.reset()5847 def reset(self):59 def reset(self) -> None:60 """Resets the bucket (unloads the bytecode)."""49 self.code = None61 self.code: t.Optional[CodeType] = None6251 def load_bytecode(self, f):63 def load_bytecode(self, f: t.BinaryIO) -> None:64 """Loads bytecode from a file or file like object."""65 # make sure the magic header is correct66 magic = f.read(len(bc_magic))67 if magic != bc_magic:
10 unmodified lines
78 except (EOFError, ValueError, TypeError):79 self.reset()80 return8170 def write_bytecode(self, f):82 def write_bytecode(self, f: t.BinaryIO) -> None:83 """Dump the bytecode into the file or file like object passed."""84 if self.code is None:85 raise TypeError("can't write empty bucket")86 f.write(bc_magic)87 pickle.dump(self.checksum, f, 2)88 marshal.dump(self.code, f)8978 def bytecode_from_string(self, string):79 """Load bytecode from a string."""90 def bytecode_from_string(self, string: bytes) -> None:91 """Load bytecode from bytes."""92 self.load_bytecode(BytesIO(string))9382 def bytecode_to_string(self):83 """Return the bytecode as string."""94 def bytecode_to_string(self) -> bytes:95 """Return the bytecode as bytes."""96 out = BytesIO()97 self.write_bytecode(out)98 return out.getvalue()99
26 unmodified lines
126 A more advanced version of a filesystem based bytecode cache is part of127 Jinja.128 """129118 def load_bytecode(self, bucket):130 def load_bytecode(self, bucket: Bucket) -> None:131 """Subclasses have to override this method to load bytecode into a132 bucket. If they are not able to find code in the cache for the133 bucket, it must not do anything.134 """135 raise NotImplementedError()136125 def dump_bytecode(self, bucket):137 def dump_bytecode(self, bucket: Bucket) -> None:138 """Subclasses have to override this method to write the bytecode139 from a bucket back to the cache. If it unable to do so it must not140 fail silently but raise an exception.141 """142 raise NotImplementedError()143132 def clear(self):144 def clear(self) -> None:145 """Clears the cache. This method is not used by Jinja but should be146 implemented to allow applications to clear the bytecode cache used147 by a particular environment.148 """149138 def get_cache_key(self, name, filename=None):150 def get_cache_key(151 self, name: str, filename: t.Optional[t.Union[str]] = None152 ) -> str:153 """Returns the unique hash key for this template name."""154 hash = sha1(name.encode("utf-8"))155156 if filename is not None:142 filename = "|" + filename143 if isinstance(filename, str):144 filename = filename.encode("utf-8")145 hash.update(filename)157 hash.update(f"|{filename}".encode("utf-8"))158159 return hash.hexdigest()160148 def get_source_checksum(self, source):161 def get_source_checksum(self, source: str) -> str:162 """Returns a checksum for the source."""163 return sha1(source.encode("utf-8")).hexdigest()164152 def get_bucket(self, environment, name, filename, source):165 def get_bucket(166 self,167 environment: "Environment",168 name: str,169 filename: t.Optional[str],170 source: str,171 ) -> Bucket:172 """Return a cache bucket for the given template. All arguments are173 mandatory but filename may be `None`.174 """175 key = self.get_cache_key(name, filename)
1 unmodified line
177 bucket = Bucket(environment, key, checksum)178 self.load_bytecode(bucket)179 return bucket180162 def set_bucket(self, bucket):181 def set_bucket(self, bucket: Bucket) -> None:182 """Put the bucket into the cache."""183 self.dump_bytecode(bucket)184185
14 unmodified lines
200201 This bytecode cache supports clearing of the cache using the clear method.202 """203185 def __init__(self, directory=None, pattern="__jinja2_%s.cache"):204 def __init__(205 self, directory: t.Optional[str] = None, pattern: str = "__jinja2_%s.cache"206 ) -> None:207 if directory is None:208 directory = self._get_default_cache_dir()209 self.directory = directory210 self.pattern = pattern211191 def _get_default_cache_dir(self):192 def _unsafe_dir():212 def _get_default_cache_dir(self) -> str:213 def _unsafe_dir() -> t.NoReturn:214 raise RuntimeError(215 "Cannot determine safe temp directory. You "216 "need to explicitly provide one."217 )
37 unmodified lines
255 _unsafe_dir()256257 return actual_dir258238 def _get_cache_filename(self, bucket):259 def _get_cache_filename(self, bucket: Bucket) -> str:260 return os.path.join(self.directory, self.pattern % (bucket.key,))261241 def load_bytecode(self, bucket):242 f = open_if_exists(self._get_cache_filename(bucket), "rb")243 if f is not None:244 try:262 def load_bytecode(self, bucket: Bucket) -> None:263 filename = self._get_cache_filename(bucket)264265 if os.path.exists(filename):266 with open(filename, "rb") as f:267 bucket.load_bytecode(f)246 finally:247 f.close()268249 def dump_bytecode(self, bucket):250 f = open(self._get_cache_filename(bucket), "wb")251 try:269 def dump_bytecode(self, bucket: Bucket) -> None:270 with open(self._get_cache_filename(bucket), "wb") as f:271 bucket.write_bytecode(f)253 finally:254 f.close()272256 def clear(self):273 def clear(self) -> None:274 # imported lazily here because google app-engine doesn't support275 # write access on the file system and the function does not exist276 # normally.277 from os import remove
52 unmodified lines
330 """331332 def __init__(333 self,317 client,318 prefix="jinja2/bytecode/",319 timeout=None,320 ignore_memcache_errors=True,334 client: "_MemcachedClient",335 prefix: str = "jinja2/bytecode/",336 timeout: t.Optional[int] = None,337 ignore_memcache_errors: bool = True,338 ):339 self.client = client340 self.prefix = prefix341 self.timeout = timeout342 self.ignore_memcache_errors = ignore_memcache_errors343327 def load_bytecode(self, bucket):344 def load_bytecode(self, bucket: Bucket) -> None:345 try:346 code = self.client.get(self.prefix + bucket.key)347 except Exception:348 if not self.ignore_memcache_errors:349 raise333 code = None334 if code is not None:350 else:351 bucket.bytecode_from_string(code)352337 def dump_bytecode(self, bucket):338 args = (self.prefix + bucket.key, bucket.bytecode_to_string())339 if self.timeout is not None:340 args += (self.timeout,)353 def dump_bytecode(self, bucket: Bucket) -> None:354 key = self.prefix + bucket.key355 value = bucket.bytecode_to_string()356357 try:358 if self.timeout is not None:359 self.client.set(key, value, self.timeout)360 else:342 self.client.set(*args)361 self.client.set(key, value)362 except Exception:363 if not self.ignore_memcache_errors:364 raise
modified:src/jinja2/compiler.py+332 added-233 removed
1"""Compiles nodes from the parser into Python code."""2import typing as t3from collections import namedtuple3from contextlib import contextmanager4from functools import update_wrapper5from io import StringIO6from itertools import chain
14 unmodified lines
21from .utils import _PassArg22from .utils import concat23from .visitor import NodeVisitor2425if t.TYPE_CHECKING:26 from .environment import Environment2728F = t.TypeVar("F", bound=t.Callable[..., t.Any])2930operators = {31 "eq": "==",32 "ne": "!=",33 "gt": ">",
4 unmodified lines
38 "notin": "not in",39}404138def optimizeconst(f):39 def new_func(self, node, frame, **kwargs):42def optimizeconst(f: F) -> F:43 def new_func(44 self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any45 ) -> t.Any:46 # Only optimize if the frame is not volatile41 if self.optimized and not frame.eval_ctx.volatile:47 if self.optimizer is not None and not frame.eval_ctx.volatile:48 new_node = self.optimizer.visit(node, frame.eval_ctx)4950 if new_node != node:51 return self.visit(new_node, frame)5253 return f(self, node, frame, **kwargs)5447 return update_wrapper(new_func, f)55 return update_wrapper(t.cast(F, new_func), f)565758def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:59 @optimizeconst60 def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:61 if (62 self.environment.sandboxed63 and op in self.environment.intercepted_binops # type: ignore64 ):65 self.write(f"environment.call_binop(context, {op!r}, ")66 self.visit(node.left, frame)67 self.write(", ")68 self.visit(node.right, frame)69 else:70 self.write("(")71 self.visit(node.left, frame)72 self.write(f" {op} ")73 self.visit(node.right, frame)7475 self.write(")")7677 return visitor787980def _make_unop(81 op: str,82) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:83 @optimizeconst84 def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:85 if (86 self.environment.sandboxed87 and op in self.environment.intercepted_unops # type: ignore88 ):89 self.write(f"environment.call_unop(context, {op!r}, ")90 self.visit(node.node, frame)91 else:92 self.write("(" + op)93 self.visit(node.node, frame)9495 self.write(")")9697 return visitor9899100def generate(51 node, environment, name, filename, stream=None, defer_init=False, optimized=True52):101 node: nodes.Template,102 environment: "Environment",103 name: t.Optional[str],104 filename: t.Optional[str],105 stream: t.Optional[t.TextIO] = None,106 defer_init: bool = False,107 optimized: bool = True,108) -> t.Optional[str]:109 """Generate the python source for a node tree."""110 if not isinstance(node, nodes.Template):111 raise TypeError("Can't compile non template nodes")112113 generator = environment.code_generator_class(114 environment, name, filename, stream, defer_init, optimized115 )116 generator.visit(node)117118 if stream is None:61 return generator.stream.getvalue()119 return generator.stream.getvalue() # type: ignore120121 return None12212364def has_safe_repr(value):124def has_safe_repr(value: t.Any) -> bool:125 """Does the node have a safe representation?"""126 if value is None or value is NotImplemented or value is Ellipsis:127 return True128
8 unmodified lines
137138 return False13914081def find_undeclared(nodes, names):141def find_undeclared(142 nodes: t.Iterable[nodes.Node], names: t.Iterable[str]143) -> t.Set[str]:144 """Check if the names passed are accessed undeclared. The return value145 is a set of all the undeclared names from the sequence of names found.146 """147 visitor = UndeclaredNameVisitor(names)
5 unmodified lines
153 return visitor.undeclared154155156class MacroRef:95 def __init__(self, node):157 def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None:158 self.node = node159 self.accesses_caller = False160 self.accesses_kwargs = False161 self.accesses_varargs = False
1 unmodified line
163164class Frame:165 """Holds compile time information for us."""166105 def __init__(self, eval_ctx, parent=None, level=None):167 def __init__(168 self,169 eval_ctx: EvalContext,170 parent: t.Optional["Frame"] = None,171 level: t.Optional[int] = None,172 ) -> None:173 self.eval_ctx = eval_ctx107 self.symbols = Symbols(parent.symbols if parent else None, level=level)174175 # the parent of this frame176 self.parent = parent177178 if parent is None:179 self.symbols = Symbols(level=level)180181 # in some dynamic inheritance situations the compiler needs to add182 # write tests around output statements.183 self.require_output_check = False184185 # inside some tags we are using a buffer rather than yield statements.186 # this for example affects {% filter %} or {% macro %}. If a frame187 # is buffered this variable points to the name of the list used as188 # buffer.189 self.buffer: t.Optional[str] = None190191 # the name of the block we're in, otherwise None.192 self.block: t.Optional[str] = None193194 else:195 self.symbols = Symbols(parent.symbols, level=level)196 self.require_output_check = parent.require_output_check197 self.buffer = parent.buffer198 self.block = parent.block199200 # a toplevel frame is the root + soft frames such as if conditions.201 self.toplevel = False202203 # the root frame is basically just the outermost frame, so no if204 # conditions. This information is used to optimize inheritance205 # situations.206 self.rootlevel = False207117 # in some dynamic inheritance situations the compiler needs to add118 # write tests around output statements.119 self.require_output_check = parent and parent.require_output_check120121 # inside some tags we are using a buffer rather than yield statements.122 # this for example affects {% filter %} or {% macro %}. If a frame123 # is buffered this variable points to the name of the list used as124 # buffer.125 self.buffer = None126127 # the name of the block we're in, otherwise None.128 self.block = parent.block if parent else None129130 # the parent of this frame131 self.parent = parent132133 if parent is not None:134 self.buffer = parent.buffer135208 # variables set inside of loops and blocks should not affect outer frames,209 # but they still needs to be kept track of as part of the active context.210 self.loop_frame = False211 self.block_frame = False
2 unmodified lines
214 # expression as it determines which errors should be raised during runtime215 # or compile time.216 self.soft_frame = False217146 def copy(self):218 def copy(self) -> "Frame":219 """Create a copy of the current one."""148 rv = object.__new__(self.__class__)220 rv = t.cast(Frame, object.__new__(self.__class__))221 rv.__dict__.update(self.__dict__)222 rv.symbols = self.symbols.copy()223 return rv224153 def inner(self, isolated=False):225 def inner(self, isolated: bool = False) -> "Frame":226 """Return an inner frame."""227 if isolated:228 return Frame(self.eval_ctx, level=self.symbols.level + 1)229 return Frame(self.eval_ctx, self)230159 def soft(self):231 def soft(self) -> "Frame":232 """Return a soft frame. A soft frame may not be modified as233 standalone thing as it shares the resources with the frame it234 was created of, but it's not a rootlevel frame any longer.235
14 unmodified lines
250251class DependencyFinderVisitor(NodeVisitor):252 """A visitor that collects filter and test calls."""253182 def __init__(self):183 self.filters = set()184 self.tests = set()254 def __init__(self) -> None:255 self.filters: t.Set[str] = set()256 self.tests: t.Set[str] = set()257186 def visit_Filter(self, node):258 def visit_Filter(self, node: nodes.Filter) -> None:259 self.generic_visit(node)260 self.filters.add(node.name)261190 def visit_Test(self, node):262 def visit_Test(self, node: nodes.Test) -> None:263 self.generic_visit(node)264 self.tests.add(node.name)265194 def visit_Block(self, node):266 def visit_Block(self, node: nodes.Block) -> None:267 """Stop visiting at blocks."""268269270class UndeclaredNameVisitor(NodeVisitor):
1 unmodified line
272 declared. This is different from the frame visitor as it will273 not stop at closure frames.274 """275204 def __init__(self, names):276 def __init__(self, names: t.Iterable[str]) -> None:277 self.names = set(names)206 self.undeclared = set()278 self.undeclared: t.Set[str] = set()279208 def visit_Name(self, node):280 def visit_Name(self, node: nodes.Name) -> None:281 if node.ctx == "load" and node.name in self.names:282 self.undeclared.add(node.name)283 if self.undeclared == self.names:284 raise VisitorExit()285 else:286 self.names.discard(node.name)287216 def visit_Block(self, node):288 def visit_Block(self, node: nodes.Block) -> None:289 """Stop visiting a blocks."""290291292class CompilerExit(Exception):
4 unmodified lines
297298299class CodeGenerator(NodeVisitor):300 def __init__(229 self, environment, name, filename, stream=None, defer_init=False, optimized=True230 ):301 self,302 environment: "Environment",303 name: t.Optional[str],304 filename: t.Optional[str],305 stream: t.Optional[t.TextIO] = None,306 defer_init: bool = False,307 optimized: bool = True,308 ) -> None:309 if stream is None:310 stream = StringIO()311 self.environment = environment312 self.name = name313 self.filename = filename314 self.stream = stream315 self.created_block_context = False316 self.defer_init = defer_init239 self.optimized = optimized317 self.optimizer: t.Optional[Optimizer] = None318319 if optimized:320 self.optimizer = Optimizer(environment)321322 # aliases for imports244 self.import_aliases = {}323 self.import_aliases: t.Dict[str, str] = {}324325 # a registry for all blocks. Because blocks are moved out326 # into the global python scope they are registered here248 self.blocks = {}327 self.blocks: t.Dict[str, nodes.Block] = {}328329 # the number of extends statements so far330 self.extends_so_far = 0331
5 unmodified lines
337 # the current line number338 self.code_lineno = 1339340 # registry of all filters and tests (global, not block local)262 self.tests = {}263 self.filters = {}341 self.tests: t.Dict[str, str] = {}342 self.filters: t.Dict[str, str] = {}343344 # the debug information266 self.debug_info = []267 self._write_debug_info = None345 self.debug_info: t.List[t.Tuple[int, int]] = []346 self._write_debug_info: t.Optional[int] = None347348 # the number of new lines before the next write()349 self._new_lines = 0350
10 unmodified lines
361 # the current indentation362 self._indentation = 0363364 # Tracks toplevel assignments286 self._assign_stack = []365 self._assign_stack: t.List[t.Set[str]] = []366367 # Tracks parameter definition blocks289 self._param_def_block = []368 self._param_def_block: t.List[t.Set[str]] = []369370 # Tracks the current context.371 self._context_reference_stack = ["context"]372373 @property374 def optimized(self) -> bool:375 return self.optimizer is not None376377 # -- Various compilation helpers378296 def fail(self, msg, lineno):379 def fail(self, msg: str, lineno: int) -> t.NoReturn:380 """Fail with a :exc:`TemplateAssertionError`."""381 raise TemplateAssertionError(msg, lineno, self.name, self.filename)382300 def temporary_identifier(self):383 def temporary_identifier(self) -> str:384 """Get a new unique identifier."""385 self._last_identifier += 1386 return f"t_{self._last_identifier}"387305 def buffer(self, frame):388 def buffer(self, frame: Frame) -> None:389 """Enable buffering for the frame from that point onwards."""390 frame.buffer = self.temporary_identifier()391 self.writeline(f"{frame.buffer} = []")392310 def return_buffer_contents(self, frame, force_unescaped=False):393 def return_buffer_contents(394 self, frame: Frame, force_unescaped: bool = False395 ) -> None:396 """Return the buffer contents of the frame."""397 if not force_unescaped:398 if frame.eval_ctx.volatile:399 self.writeline("if context.eval_ctx.autoescape:")
9 unmodified lines
409 self.writeline(f"return Markup(concat({frame.buffer}))")410 return411 self.writeline(f"return concat({frame.buffer})")412328 def indent(self):413 def indent(self) -> None:414 """Indent by one."""415 self._indentation += 1416332 def outdent(self, step=1):417 def outdent(self, step: int = 1) -> None:418 """Outdent by step."""419 self._indentation -= step420336 def start_write(self, frame, node=None):421 def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None:422 """Yield or write into the frame buffer."""423 if frame.buffer is None:424 self.writeline("yield ", node)425 else:426 self.writeline(f"{frame.buffer}.append(", node)427343 def end_write(self, frame):428 def end_write(self, frame: Frame) -> None:429 """End the writing process started by `start_write`."""430 if frame.buffer is not None:431 self.write(")")432348 def simple_write(self, s, frame, node=None):433 def simple_write(434 self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None435 ) -> None:436 """Simple shortcut for start_write + write + end_write."""437 self.start_write(frame, node)438 self.write(s)439 self.end_write(frame)440354 def blockvisit(self, nodes, frame):441 def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None:442 """Visit a list of nodes as block in a frame. If the current frame443 is no buffer a dummy ``if 0: yield None`` is written automatically.444 """445 try:
2 unmodified lines
448 self.visit(node, frame)449 except CompilerExit:450 pass451365 def write(self, x):452 def write(self, x: str) -> None:453 """Write a string into the output stream."""454 if self._new_lines:455 if not self._first_write:456 self.stream.write("\n" * self._new_lines)
5 unmodified lines
462 self.stream.write(" " * self._indentation)463 self._new_lines = 0464 self.stream.write(x)465379 def writeline(self, x, node=None, extra=0):466 def writeline(467 self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0468 ) -> None:469 """Combination of newline and write."""470 self.newline(node, extra)471 self.write(x)472384 def newline(self, node=None, extra=0):473 def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None:474 """Add one or more newlines before the next write."""475 self._new_lines = max(self._new_lines, 1 + extra)476 if node is not None and node.lineno != self._last_line:477 self._write_debug_info = node.lineno478 self._last_line = node.lineno479391 def signature(self, node, frame, extra_kwargs=None):480 def signature(481 self,482 node: t.Union[nodes.Call, nodes.Filter, nodes.Test],483 frame: Frame,484 extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None,485 ) -> None:486 """Writes a function call to the stream for the current node.487 A leading comma is added automatically. The extra keyword488 arguments may not include python keywords otherwise a syntax489 error could occur. The extra keyword arguments should be given490 as python dict.491 """492 # if any of the given keyword arguments is a python keyword493 # we have to make sure that no invalid call is created.400 kwarg_workaround = False401 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):402 if is_python_keyword(kwarg):403 kwarg_workaround = True404 break494 kwarg_workaround = any(495 is_python_keyword(t.cast(str, k))496 for k in chain((x.key for x in node.kwargs), extra_kwargs or ())497 )498499 for arg in node.args:500 self.write(", ")501 self.visit(arg, frame)
31 unmodified lines
533 elif node.dyn_kwargs is not None:534 self.write(", **")535 self.visit(node.dyn_kwargs, frame)536444 def pull_dependencies(self, nodes):537 def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None:538 """Find all filter and test names used in the template and539 assign them to variables in the compiled namespace. Checking540 that the names are registered with the environment is done when541 compiling the Filter and Test nodes. If the node is in an If or
7 unmodified lines
549550 for node in nodes:551 visitor.visit(node)552460 for dependency in "filters", "tests":461 mapping = getattr(self, dependency)553 for id_map, names, dependency in (self.filters, visitor.filters, "filters"), (554 self.tests,555 visitor.tests,556 "tests",557 ):558 for name in names:559 if name not in id_map:560 id_map[name] = self.temporary_identifier()561463 for name in getattr(visitor, dependency):464 if name not in mapping:465 mapping[name] = self.temporary_identifier()466562 # add check during runtime that dependencies used inside of executed563 # blocks are defined, as this step may be skipped during compile time564 self.writeline("try:")565 self.indent()471 self.writeline(f"{mapping[name]} = environment.{dependency}[{name!r}]")566 self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]")567 self.outdent()568 self.writeline("except KeyError:")569 self.indent()570 self.writeline("@internalcode")476 self.writeline(f"def {mapping[name]}(*unused):")571 self.writeline(f"def {id_map[name]}(*unused):")572 self.indent()573 self.writeline(574 f'raise TemplateRuntimeError("No {dependency[:-1]}'575 f' named {name!r} found.")'576 )577 self.outdent()578 self.outdent()579485 def enter_frame(self, frame):580 def enter_frame(self, frame: Frame) -> None:581 undefs = []582 for target, (action, param) in frame.symbols.loads.items():583 if action == VAR_LOAD_PARAMETER:584 pass
7 unmodified lines
592 raise NotImplementedError("unknown load instruction")593 if undefs:594 self.writeline(f"{' = '.join(undefs)} = missing")595501 def leave_frame(self, frame, with_python_scope=False):596 def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None:597 if not with_python_scope:598 undefs = []599 for target in frame.symbols.loads:600 undefs.append(target)601 if undefs:602 self.writeline(f"{' = '.join(undefs)} = missing")603509 def choose_async(self, async_value="async ", sync_value=""):604 def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str:605 return async_value if self.environment.is_async else sync_value606512 def func(self, name):607 def func(self, name: str) -> str:608 return f"{self.choose_async()}def {name}"609515 def macro_body(self, node, frame):610 def macro_body(611 self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame612 ) -> t.Tuple[Frame, MacroRef]:613 """Dump the function def of a macro or call block."""614 frame = frame.inner()615 frame.symbols.analyze_node(node)616 macro_ref = MacroRef(node)617618 explicit_caller = None619 skip_special_params = set()620 args = []621622 for idx, arg in enumerate(node.args):623 if arg.name == "caller":624 explicit_caller = idx625 if arg.name in ("kwargs", "varargs"):
63 unmodified lines
689 self.outdent()690691 return frame, macro_ref692595 def macro_def(self, macro_ref, frame):693 def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None:694 """Dump the macro definition for the def created by macro_body."""695 arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)696 name = getattr(macro_ref.node, "name", None)697 if len(macro_ref.node.args) == 1:
3 unmodified lines
701 f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"702 f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"703 )704607 def position(self, node):705 def position(self, node: nodes.Node) -> str:706 """Return a human readable position for the node."""707 rv = f"line {node.lineno}"708 if self.name is not None:709 rv = f"{rv} in {self.name!r}"710 return rv711614 def dump_local_context(self, frame):712 def dump_local_context(self, frame: Frame) -> str:713 items_kv = ", ".join(714 f"{name!r}: {target}"715 for name, target in frame.symbols.dump_stores().items()716 )717 return f"{{{items_kv}}}"718621 def write_commons(self):719 def write_commons(self) -> None:720 """Writes a common preamble that is used by root and block functions.721 Primarily this sets up common local helpers and enforces a generator722 through a dead branch.723 """
3 unmodified lines
727 # conditional expressions728 self.writeline("cond_expr_undefined = Undefined")729 self.writeline("if 0: yield None")730633 def push_parameter_definitions(self, frame):731 def push_parameter_definitions(self, frame: Frame) -> None:732 """Pushes all parameter targets from the given frame into a local733 stack that permits tracking of yet to be assigned parameters. In734 particular this enables the optimization from `visit_Name` to skip735 undefined expressions for parameters in macros as macros can reference736 otherwise unbound parameters.737 """738 self._param_def_block.append(frame.symbols.dump_param_targets())739642 def pop_parameter_definitions(self):740 def pop_parameter_definitions(self) -> None:741 """Pops the current parameter definitions set."""742 self._param_def_block.pop()743646 def mark_parameter_stored(self, target):744 def mark_parameter_stored(self, target: str) -> None:745 """Marks a parameter in the current parameter definitions as stored.746 This will skip the enforced undefined checks.747 """748 if self._param_def_block:749 self._param_def_block[-1].discard(target)750653 def push_context_reference(self, target):751 def push_context_reference(self, target: str) -> None:752 self._context_reference_stack.append(target)753656 def pop_context_reference(self):754 def pop_context_reference(self) -> None:755 self._context_reference_stack.pop()756659 def get_context_ref(self):757 def get_context_ref(self) -> str:758 return self._context_reference_stack[-1]759662 def get_resolve_func(self):760 def get_resolve_func(self) -> str:761 target = self._context_reference_stack[-1]762 if target == "context":763 return "resolve"764 return f"{target}.resolve"765668 def derive_context(self, frame):766 def derive_context(self, frame: Frame) -> str:767 return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"768671 def parameter_is_undeclared(self, target):769 def parameter_is_undeclared(self, target: str) -> bool:770 """Checks if a given target is an undeclared parameter."""771 if not self._param_def_block:772 return False773 return target in self._param_def_block[-1]774677 def push_assign_tracking(self):775 def push_assign_tracking(self) -> None:776 """Pushes a new layer for assignment tracking."""777 self._assign_stack.append(set())778681 def pop_assign_tracking(self, frame):779 def pop_assign_tracking(self, frame: Frame) -> None:780 """Pops the topmost level for assignment tracking and updates the781 context variables if necessary.782 """783 vars = self._assign_stack.pop()
36 unmodified lines
820 self.writeline(f"context.exported_vars.update(({names_str}))")821822 # -- Statement Visitors823726 def visit_Template(self, node, frame=None):824 def visit_Template(825 self, node: nodes.Template, frame: t.Optional[Frame] = None826 ) -> None:827 assert frame is None, "no root frame allowed"828 eval_ctx = EvalContext(self.environment, self.name)829830 from .runtime import exported, async_exported
108 unmodified lines
939 self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)940 debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)941 self.writeline(f"debug_info = {debug_kv_str!r}")942843 def visit_Block(self, node, frame):943 def visit_Block(self, node: nodes.Block, frame: Frame) -> None:944 """Call a block and register it for the template."""945 level = 0946 if frame.toplevel:947 # if we know that we are a child template, there is no need to
34 unmodified lines
982 self.outdent()983984 self.outdent(level)985886 def visit_Extends(self, node, frame):986 def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:987 """Calls the extender."""988 if not frame.toplevel:989 self.fail("cannot use extend from a non top-level scope", node.lineno)990
34 unmodified lines
10251026 # and now we have one more1027 self.extends_so_far += 11028929 def visit_Include(self, node, frame):1029 def visit_Include(self, node: nodes.Include, frame: Frame) -> None:1030 """Handles includes."""1031 if node.ignore_missing:1032 self.writeline("try:")1033 self.indent()
42 unmodified lines
10761077 if node.ignore_missing:1078 self.outdent()1079980 def _import_common(self, node, frame):1080 def _import_common(1081 self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame1082 ) -> None:1083 self.write(f"{self.choose_async('await ')}environment.get_template(")1084 self.visit(node.template, frame)1085 self.write(f", {self.name!r}).")1086
6 unmodified lines
1093 self.write("_get_default_module_async()")1094 else:1095 self.write("_get_default_module(context)")1096995 def visit_Import(self, node, frame):1097 def visit_Import(self, node: nodes.Import, frame: Frame) -> None:1098 """Visit regular imports."""1099 self.writeline(f"{frame.symbols.ref(node.target)} = ", node)1100 if frame.toplevel:1101 self.write(f"context.vars[{node.target!r}] = ")
2 unmodified lines
11041105 if frame.toplevel and not node.target.startswith("_"):1106 self.writeline(f"context.exported_vars.discard({node.target!r})")11071006 def visit_FromImport(self, node, frame):1108 def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None:1109 """Visit named imports."""1110 self.newline(node)1111 self.write("included_template = ")1112 self._import_common(node, frame)
41 unmodified lines
1154 self.writeline(1155 f"context.exported_vars.difference_update(({names_str}))"1156 )11571056 def visit_For(self, node, frame):1158 def visit_For(self, node: nodes.For, frame: Frame) -> None:1159 loop_frame = frame.inner()1160 loop_frame.loop_frame = True1161 test_frame = frame.inner()1162 else_frame = frame.inner()
125 unmodified lines
1288 self.write(")")1289 self.write(", loop)")1290 self.end_write(frame)12911190 def visit_If(self, node, frame):1292 def visit_If(self, node: nodes.If, frame: Frame) -> None:1293 if_frame = frame.soft()1294 self.writeline("if ", node)1295 self.visit(node.test, if_frame)1296 self.write(":")
12 unmodified lines
1309 self.indent()1310 self.blockvisit(node.else_, if_frame)1311 self.outdent()13121211 def visit_Macro(self, node, frame):1313 def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None:1314 macro_frame, macro_ref = self.macro_body(node, frame)1315 self.newline()1316 if frame.toplevel:1317 if not node.name.startswith("_"):
1 unmodified line
1319 self.writeline(f"context.vars[{node.name!r}] = ")1320 self.write(f"{frame.symbols.ref(node.name)} = ")1321 self.macro_def(macro_ref, macro_frame)13221221 def visit_CallBlock(self, node, frame):1323 def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None:1324 call_frame, macro_ref = self.macro_body(node, frame)1325 self.writeline("caller = ")1326 self.macro_def(macro_ref, call_frame)1327 self.start_write(frame, node)1328 self.visit_Call(node.call, frame, forward_caller=True)1329 self.end_write(frame)13301229 def visit_FilterBlock(self, node, frame):1331 def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None:1332 filter_frame = frame.inner()1333 filter_frame.symbols.analyze_node(node)1334 self.enter_frame(filter_frame)1335 self.buffer(filter_frame)
2 unmodified lines
1338 self.visit_Filter(node.filter, filter_frame)1339 self.end_write(frame)1340 self.leave_frame(filter_frame)13411240 def visit_With(self, node, frame):1342 def visit_With(self, node: nodes.With, frame: Frame) -> None:1343 with_frame = frame.inner()1344 with_frame.symbols.analyze_node(node)1345 self.enter_frame(with_frame)1346 for target, expr in zip(node.targets, node.values):
3 unmodified lines
1350 self.visit(expr, frame)1351 self.blockvisit(node.body, with_frame)1352 self.leave_frame(with_frame)13531252 def visit_ExprStmt(self, node, frame):1354 def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None:1355 self.newline(node)1356 self.visit(node.node, frame)13571256 _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1257 #: The default finalize function if the environment isn't configured1258 #: with one. Or if the environment has one, this is called on that1259 #: function's output for constants.1260 _default_finalize = str1358 class _FinalizeInfo(t.NamedTuple):1359 const: t.Optional[t.Callable[..., str]]1360 src: t.Optional[str]13611362 @staticmethod1363 def _default_finalize(value: t.Any) -> t.Any:1364 """The default finalize function if the environment isn't1365 configured with one. Or, if the environment has one, this is1366 called on that function's output for constants.1367 """1368 return str(value)13691370 _finalize: t.Optional[_FinalizeInfo] = None13711263 def _make_finalize(self):1372 def _make_finalize(self) -> _FinalizeInfo:1373 """Build the finalize function to be used on constants and at1374 runtime. Cached so it's only created once for all output nodes.13751376 Returns a ``namedtuple`` with the following attributes:
7 unmodified lines
1384 """1385 if self._finalize is not None:1386 return self._finalize13871388 finalize: t.Optional[t.Callable[..., t.Any]]1389 finalize = default = self._default_finalize1390 src = None13911392 if self.environment.finalize:
2 unmodified lines
1395 pass_arg = {1396 _PassArg.context: "context",1397 _PassArg.eval_context: "context.eval_ctx",1398 _PassArg.environment: "environment",1289 }.get(_PassArg.from_obj(env_finalize))1399 }.get(1400 _PassArg.from_obj(env_finalize) # type: ignore1401 )1402 finalize = None14031404 if pass_arg is None:14051294 def finalize(value):1406 def finalize(value: t.Any) -> t.Any:1407 return default(env_finalize(value))14081409 else:1410 src = f"{src}{pass_arg}, "14111412 if pass_arg == "environment":14131302 def finalize(value):1414 def finalize(value: t.Any) -> t.Any:1415 return default(env_finalize(self.environment, value))14161417 self._finalize = self._FinalizeInfo(finalize, src)1418 return self._finalize14191308 def _output_const_repr(self, group):1420 def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:1421 """Given a group of constant values converted from ``Output``1422 child nodes, produce a string to write to the template module1423 source.1424 """1425 return repr(concat(group))14261315 def _output_child_to_const(self, node, frame, finalize):1427 def _output_child_to_const(1428 self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo1429 ) -> str:1430 """Try to optimize a child of an ``Output`` node by trying to1431 convert it to constant, finalized data at compile time.14321433 If :exc:`Impossible` is raised, the node is not constant and
8 unmodified lines
1442 # Template data doesn't go through finalize.1443 if isinstance(node, nodes.TemplateData):1444 return str(const)14451332 return finalize.const(const)1446 return finalize.const(const) # type: ignore14471334 def _output_child_pre(self, node, frame, finalize):1448 def _output_child_pre(1449 self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo1450 ) -> None:1451 """Output extra source code before visiting a child of an1452 ``Output`` node.1453 """1454 if frame.eval_ctx.volatile:
5 unmodified lines
14601461 if finalize.src is not None:1462 self.write(finalize.src)14631348 def _output_child_post(self, node, frame, finalize):1464 def _output_child_post(1465 self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo1466 ) -> None:1467 """Output extra source code after visiting a child of an1468 ``Output`` node.1469 """1470 self.write(")")14711472 if finalize.src is not None:1473 self.write(")")14741357 def visit_Output(self, node, frame):1475 def visit_Output(self, node: nodes.Output, frame: Frame) -> None:1476 # If an extends is active, don't render outside a block.1477 if frame.require_output_check:1478 # A top-level extends is known to exist at compile time.1479 if self.has_known_extends:
2 unmodified lines
1482 self.writeline("if parent_template is None:")1483 self.indent()14841485 finalize = self._make_finalize()1368 body = []1486 body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = []14871488 # Evaluate constants at compile time if possible. Each item in1489 # body will be either a list of static data or a node to be1490 # evaluated at runtime.
59 unmodified lines
15501551 if frame.require_output_check:1552 self.outdent()15531436 def visit_Assign(self, node, frame):1554 def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:1555 self.push_assign_tracking()1556 self.newline(node)1557 self.visit(node.target, frame)1558 self.write(" = ")1559 self.visit(node.node, frame)1560 self.pop_assign_tracking(frame)15611444 def visit_AssignBlock(self, node, frame):1562 def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None:1563 self.push_assign_tracking()1564 block_frame = frame.inner()1565 # This is a special case. Since a set block always captures we1566 # will disable output checks. This way one can use set blocks
15 unmodified lines
1582 self.leave_frame(block_frame)15831584 # -- Expression Visitors15851468 def visit_Name(self, node, frame):1586 def visit_Name(self, node: nodes.Name, frame: Frame) -> None:1587 if node.ctx == "store" and (1588 frame.toplevel or frame.loop_frame or frame.block_frame1589 ):1590 if self._assign_stack:
16 unmodified lines
1607 return16081609 self.write(ref)16101493 def visit_NSRef(self, node, frame):1611 def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:1612 # NSRefs can only be used to store values; since they use the normal1613 # `foo.bar` notation they will be parsed as a normal attribute access1614 # when used anywhere but in a `set` context1615 ref = frame.symbols.ref(node.name)
5 unmodified lines
1621 )1622 self.outdent()1623 self.writeline(f"{ref}[{node.attr!r}]")16241507 def visit_Const(self, node, frame):1625 def visit_Const(self, node: nodes.Const, frame: Frame) -> None:1626 val = node.as_const(frame.eval_ctx)1627 if isinstance(val, float):1628 self.write(str(val))1629 else:1630 self.write(repr(val))16311514 def visit_TemplateData(self, node, frame):1632 def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None:1633 try:1634 self.write(repr(node.as_const(frame.eval_ctx)))1635 except nodes.Impossible:1636 self.write(1637 f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"1638 )16391522 def visit_Tuple(self, node, frame):1640 def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None:1641 self.write("(")1642 idx = -11643 for idx, item in enumerate(node.items):1644 if idx:1645 self.write(", ")1646 self.visit(item, frame)1647 self.write(",)" if idx == 0 else ")")16481531 def visit_List(self, node, frame):1649 def visit_List(self, node: nodes.List, frame: Frame) -> None:1650 self.write("[")1651 for idx, item in enumerate(node.items):1652 if idx:1653 self.write(", ")1654 self.visit(item, frame)1655 self.write("]")16561539 def visit_Dict(self, node, frame):1657 def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None:1658 self.write("{")1659 for idx, item in enumerate(node.items):1660 if idx:1661 self.write(", ")
1 unmodified line
1663 self.write(": ")1664 self.visit(item.value, frame)1665 self.write("}")16661549 def binop(operator, interceptable=True): # noqa: B9021550 @optimizeconst1551 def visitor(self, node, frame):1552 if (1553 self.environment.sandboxed1554 and operator in self.environment.intercepted_binops1555 ):1556 self.write(f"environment.call_binop(context, {operator!r}, ")1557 self.visit(node.left, frame)1558 self.write(", ")1559 self.visit(node.right, frame)1560 else:1561 self.write("(")1562 self.visit(node.left, frame)1563 self.write(f" {operator} ")1564 self.visit(node.right, frame)1565 self.write(")")1667 visit_Add = _make_binop("+")1668 visit_Sub = _make_binop("-")1669 visit_Mul = _make_binop("*")1670 visit_Div = _make_binop("/")1671 visit_FloorDiv = _make_binop("//")1672 visit_Pow = _make_binop("**")1673 visit_Mod = _make_binop("%")1674 visit_And = _make_binop("and")1675 visit_Or = _make_binop("or")1676 visit_Pos = _make_unop("+")1677 visit_Neg = _make_unop("-")1678 visit_Not = _make_unop("not ")16791567 return visitor15681569 def uaop(operator, interceptable=True): # noqa: B9021570 @optimizeconst1571 def visitor(self, node, frame):1572 if (1573 self.environment.sandboxed1574 and operator in self.environment.intercepted_unops1575 ):1576 self.write(f"environment.call_unop(context, {operator!r}, ")1577 self.visit(node.node, frame)1578 else:1579 self.write("(" + operator)1580 self.visit(node.node, frame)1581 self.write(")")15821583 return visitor15841585 visit_Add = binop("+") # type:ignore1586 visit_Sub = binop("-") # type:ignore1587 visit_Mul = binop("*") # type:ignore1588 visit_Div = binop("/") # type:ignore1589 visit_FloorDiv = binop("//") # type:ignore1590 visit_Pow = binop("**") # type:ignore1591 visit_Mod = binop("%") # type:ignore1592 visit_And = binop("and", interceptable=False) # type:ignore1593 visit_Or = binop("or", interceptable=False) # type:ignore1594 visit_Pos = uaop("+") # type:ignore1595 visit_Neg = uaop("-") # type:ignore1596 visit_Not = uaop("not ", interceptable=False) # type:ignore1597 del binop, uaop15981680 @optimizeconst1600 def visit_Concat(self, node, frame):1681 def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None:1682 if frame.eval_ctx.volatile:1683 func_name = "(markup_join if context.eval_ctx.volatile else str_join)"1684 elif frame.eval_ctx.autoescape:1685 func_name = "markup_join"
5 unmodified lines
1691 self.write(", ")1692 self.write("))")16931694 @optimizeconst1614 def visit_Compare(self, node, frame):1695 def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None:1696 self.write("(")1697 self.visit(node.expr, frame)1698 for op in node.ops:1699 self.visit(op, frame)1700 self.write(")")17011621 def visit_Operand(self, node, frame):1702 def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None:1703 self.write(f" {operators[node.op]} ")1704 self.visit(node.expr, frame)17051706 @optimizeconst1626 def visit_Getattr(self, node, frame):1707 def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None:1708 if self.environment.is_async:1709 self.write("(await auto_await(")17101711 self.write("environment.getattr(")
3 unmodified lines
1715 if self.environment.is_async:1716 self.write("))")17171718 @optimizeconst1638 def visit_Getitem(self, node, frame):1719 def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None:1720 # slices bypass the environment getitem method.1721 if isinstance(node.arg, nodes.Slice):1722 self.visit(node.node, frame)1723 self.write("[")
11 unmodified lines
17351736 if self.environment.is_async:1737 self.write("))")17381658 def visit_Slice(self, node, frame):1739 def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None:1740 if node.start is not None:1741 self.visit(node.start, frame)1742 self.write(":")1743 if node.stop is not None:
2 unmodified lines
1746 self.write(":")1747 self.visit(node.step, frame)17481749 @contextmanager1669 def _filter_test_common(self, node, frame, is_filter):1670 if is_filter:1671 compiler_map = self.filters1672 env_map = self.environment.filters1673 type_name = "filter"1674 else:1675 compiler_map = self.tests1676 env_map = self.environment.tests1677 type_name = "test"16781750 def _filter_test_common(1751 self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool1752 ) -> t.Iterator[None]:1753 if self.environment.is_async:1754 self.write("await auto_await(")17551682 self.write(compiler_map[node.name] + "(")1683 func = env_map.get(node.name)1756 if is_filter:1757 self.write(f"{self.filters[node.name]}(")1758 func = self.environment.filters.get(node.name)1759 else:1760 self.write(f"{self.tests[node.name]}(")1761 func = self.environment.tests.get(node.name)17621763 # When inside an If or CondExpr frame, allow the filter to be1764 # undefined at compile time and only raise an error if it's1765 # actually called at runtime. See pull_dependencies.1766 if func is None and not frame.soft_frame:1767 type_name = "filter" if is_filter else "test"1768 self.fail(f"No {type_name} named {node.name!r}.", node.lineno)17691770 pass_arg = {1771 _PassArg.context: "context",1772 _PassArg.eval_context: "context.eval_ctx",1773 _PassArg.environment: "environment",1695 }.get(_PassArg.from_obj(func))1774 }.get(1775 _PassArg.from_obj(func) # type: ignore1776 )17771778 if pass_arg is not None:1779 self.write(f"{pass_arg}, ")1780
7 unmodified lines
1788 if self.environment.is_async:1789 self.write(")")17901791 @optimizeconst1711 def visit_Filter(self, node, frame):1792 def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None:1793 with self._filter_test_common(node, frame, True):1794 # if the filter node is None we are inside a filter block1795 # and want to write to the current buffer1796 if node.node is not None:
8 unmodified lines
1805 else:1806 self.write(f"concat({frame.buffer})")18071808 @optimizeconst1728 def visit_Test(self, node, frame):1809 def visit_Test(self, node: nodes.Test, frame: Frame) -> None:1810 with self._filter_test_common(node, frame, False):1811 self.visit(node.node, frame)18121813 @optimizeconst1733 def visit_CondExpr(self, node, frame):1814 def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None:1815 frame = frame.soft()18161736 def write_expr2():1817 def write_expr2() -> None:1818 if node.expr2 is not None:1738 return self.visit(node.expr2, frame)1819 self.visit(node.expr2, frame)1820 return18211822 self.write(1823 f'cond_expr_undefined("the inline if-expression on'1824 f" {self.position(node)} evaluated to false and no else"1825 f' section was defined.")'
7 unmodified lines
1833 write_expr2()1834 self.write(")")18351836 @optimizeconst1754 def visit_Call(self, node, frame, forward_caller=False):1837 def visit_Call(1838 self, node: nodes.Call, frame: Frame, forward_caller: bool = False1839 ) -> None:1840 if self.environment.is_async:1841 self.write("await auto_await(")1842 if self.environment.sandboxed:1843 self.write("environment.call(context, ")
11 unmodified lines
1855 self.write(")")1856 if self.environment.is_async:1857 self.write(")")18581774 def visit_Keyword(self, node, frame):1859 def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None:1860 self.write(node.key + "=")1861 self.visit(node.value, frame)18621863 # -- Unused nodes for extensions18641780 def visit_MarkSafe(self, node, frame):1865 def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None:1866 self.write("Markup(")1867 self.visit(node.expr, frame)1868 self.write(")")18691785 def visit_MarkSafeIfAutoescape(self, node, frame):1870 def visit_MarkSafeIfAutoescape(1871 self, node: nodes.MarkSafeIfAutoescape, frame: Frame1872 ) -> None:1873 self.write("(Markup if context.eval_ctx.autoescape else identity)(")1874 self.visit(node.expr, frame)1875 self.write(")")18761790 def visit_EnvironmentAttribute(self, node, frame):1877 def visit_EnvironmentAttribute(1878 self, node: nodes.EnvironmentAttribute, frame: Frame1879 ) -> None:1880 self.write("environment." + node.name)18811793 def visit_ExtensionAttribute(self, node, frame):1882 def visit_ExtensionAttribute(1883 self, node: nodes.ExtensionAttribute, frame: Frame1884 ) -> None:1885 self.write(f"environment.extensions[{node.identifier!r}].{node.name}")18861796 def visit_ImportedName(self, node, frame):1887 def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None:1888 self.write(self.import_aliases[node.importname])18891799 def visit_InternalName(self, node, frame):1890 def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None:1891 self.write(node.name)18921802 def visit_ContextReference(self, node, frame):1893 def visit_ContextReference(1894 self, node: nodes.ContextReference, frame: Frame1895 ) -> None:1896 self.write("context")18971805 def visit_DerivedContextReference(self, node, frame):1898 def visit_DerivedContextReference(1899 self, node: nodes.DerivedContextReference, frame: Frame1900 ) -> None:1901 self.write(self.derive_context(frame))19021808 def visit_Continue(self, node, frame):1903 def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:1904 self.writeline("continue", node)19051811 def visit_Break(self, node, frame):1906 def visit_Break(self, node: nodes.Break, frame: Frame) -> None:1907 self.writeline("break", node)19081814 def visit_Scope(self, node, frame):1909 def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None:1910 scope_frame = frame.inner()1911 scope_frame.symbols.analyze_node(node)1912 self.enter_frame(scope_frame)1913 self.blockvisit(node.body, scope_frame)1914 self.leave_frame(scope_frame)19151821 def visit_OverlayScope(self, node, frame):1916 def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None:1917 ctx = self.temporary_identifier()1918 self.writeline(f"{ctx} = {self.derive_context(frame)}")1919 self.writeline(f"{ctx}.vars = ")1920 self.visit(node.context, frame)
5 unmodified lines
1926 self.blockvisit(node.body, scope_frame)1927 self.leave_frame(scope_frame)1928 self.pop_context_reference()19291835 def visit_EvalContextModifier(self, node, frame):1930 def visit_EvalContextModifier(1931 self, node: nodes.EvalContextModifier, frame: Frame1932 ) -> None:1933 for keyword in node.options:1934 self.writeline(f"context.eval_ctx.{keyword.key} = ")1935 self.visit(keyword.value, frame)1936 try:
2 unmodified lines
1939 frame.eval_ctx.volatile = True1940 else:1941 setattr(frame.eval_ctx, keyword.key, val)19421846 def visit_ScopedEvalContextModifier(self, node, frame):1943 def visit_ScopedEvalContextModifier(1944 self, node: nodes.ScopedEvalContextModifier, frame: Frame1945 ) -> None:1946 old_ctx_name = self.temporary_identifier()1947 saved_ctx = frame.eval_ctx.save()1948 self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")1949 self.visit_EvalContextModifier(node, frame)
4 unmodified lines
modified:src/jinja2/debug.py+35 added-18 removed
1import platform2import sys3import typing as t4from types import CodeType5from types import TracebackType65from . import TemplateSyntaxError7from .exceptions import TemplateSyntaxError8from .utils import internal_code9from .utils import missing1011if t.TYPE_CHECKING:12 from .runtime import Context1310def rewrite_traceback_stack(source=None):1415def rewrite_traceback_stack(source: t.Optional[str] = None) -> BaseException:16 """Rewrite the current exception to replace any tracebacks from17 within compiled template code with tracebacks that look like they18 came from the template source.19
3 unmodified lines
23 known.24 :return: The original exception with the rewritten traceback.25 """26 _, exc_value, tb = sys.exc_info()27 exc_value = t.cast(BaseException, exc_value)28 tb = t.cast(TracebackType, tb)2930 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:31 exc_value.translated = True32 exc_value.source = source
39 unmodified lines
7273 return exc_value.with_traceback(tb_next)747569def fake_traceback(exc_value, tb, filename, lineno):76def fake_traceback( # type: ignore77 exc_value: BaseException, tb: t.Optional[TracebackType], filename: str, lineno: int78) -> TracebackType:79 """Produce a new traceback object that looks like it came from the80 template source instead of the compiled code. The filename, line81 number, and location name will point to the template, and the local82 variables will be the current template context.
64 unmodified lines
147 continue148149 try:150 # Copy original value if it exists.142 code_args.append(getattr(code, "co_" + attr))151 code_args.append(getattr(code, "co_" + t.cast(str, attr)))152 except AttributeError:153 # Some arguments were added later.154 continue155
7 unmodified lines
163 # the new traceback without this frame.164 try:165 exec(code, globals, locals)166 except BaseException:158 return sys.exc_info()[2].tb_next167 return sys.exc_info()[2].tb_next # type: ignore168169161def get_template_locals(real_locals):170def get_template_locals(real_locals: t.Mapping[str, t.Any]) -> t.Dict[str, t.Any]:171 """Based on the runtime locals, get the context that would be172 available at that point in the template.173 """174 # Start with the current template context.166 ctx = real_locals.get("context")175 ctx: "t.Optional[Context]" = real_locals.get("context")176168 if ctx:169 data = ctx.get_all().copy()177 if ctx is not None:178 data: t.Dict[str, t.Any] = ctx.get_all().copy()179 else:180 data = {}181182 # Might be in a derived context that only sets local variables183 # rather than pushing a context. Local variables follow the scheme184 # l_depth_name. Find the highest-depth local that has a value for185 # each name.177 local_overrides = {}186 local_overrides: t.Dict[str, t.Tuple[int, t.Any]] = {}187188 for name, value in real_locals.items():189 if not name.startswith("l_") or value is missing:190 # Not a template variable, or no longer relevant.191 continue192193 try:185 _, depth, name = name.split("_", 2)186 depth = int(depth)194 _, depth_str, name = name.split("_", 2)195 depth = int(depth_str)196 except ValueError:197 continue198199 cur_depth = local_overrides.get(name, (-1,))[0]
12 unmodified lines
212213214if sys.version_info >= (3, 7):215 # tb_next is directly assignable as of Python 3.7207 def tb_set_next(tb, tb_next):216 def tb_set_next(217 tb: TracebackType, tb_next: t.Optional[TracebackType]218 ) -> TracebackType:219 tb.tb_next = tb_next220 return tb221222
2 unmodified lines
225 try:226 import tputil # type: ignore227 except ImportError:228 # Without tproxy support, use the original traceback.218 def tb_set_next(tb, tb_next):229 def tb_set_next(230 tb: TracebackType, tb_next: t.Optional[TracebackType]231 ) -> TracebackType:232 return tb233234 else:235 # With tproxy support, create a proxy around the traceback that236 # returns the new tb_next.224 def tb_set_next(tb, tb_next):225 def controller(op):237 def tb_set_next(238 tb: TracebackType, tb_next: t.Optional[TracebackType]239 ) -> TracebackType:240 def controller(op): # type: ignore241 if op.opname == "__getattribute__" and op.args[0] == "tb_next":242 return tb_next243244 return op.delegate()245231 return tputil.make_proxy(controller, obj=tb)246 return tputil.make_proxy(controller, obj=tb) # type: ignore247248249else:250 # Use ctypes to assign tb_next at the C level since it's read-only
7 unmodified lines
258 # Only care about tb_next as an object, not a traceback.259 ("tb_next", ctypes.py_object),260 ]261247 def tb_set_next(tb, tb_next):262 def tb_set_next(263 tb: TracebackType, tb_next: t.Optional[TracebackType]264 ) -> TracebackType:265 c_tb = _CTraceback.from_address(id(tb))266267 # Clear out the old tb_next.268 if tb.tb_next is not None:
11 unmodified lines
modified:src/jinja2/defaults.py+5 added-2 removed
5 unmodified lines
6from .utils import generate_lorem_ipsum7from .utils import Joiner8from .utils import Namespace910if t.TYPE_CHECKING:11 import typing_extensions as te1213# defaults for the parser / lexer14BLOCK_START_STRING = "{%"15BLOCK_END_STRING = "%}"16VARIABLE_START_STRING = "{{"
3 unmodified lines
20LINE_STATEMENT_PREFIX: t.Optional[str] = None21LINE_COMMENT_PREFIX: t.Optional[str] = None22TRIM_BLOCKS = False23LSTRIP_BLOCKS = False21NEWLINE_SEQUENCE = "\n"24NEWLINE_SEQUENCE: "te.Literal['\\n', '\\r\\n', '\\r']" = "\n"25KEEP_TRAILING_NEWLINE = False2627# default filters, tests and namespace28
6 unmodified lines
35 "namespace": Namespace,36}3738# default policies36DEFAULT_POLICIES = {39DEFAULT_POLICIES: t.Dict[str, t.Any] = {40 "compiler.ascii_str": True,41 "urlize.rel": "noopener",42 "urlize.target": None,43 "urlize.extra_schemes": None,
5 unmodified lines
modified:src/jinja2/environment.py+402 added-201 removed
1"""Classes for managing templates and their runtime and compile time2options.3"""4import os5import sys5import typing6import typing as t7import weakref8from collections import ChainMap9from functools import lru_cache10from functools import partial11from functools import reduce12from types import CodeType1314from markupsafe import Markup1516from . import nodes
20 unmodified lines
37from .exceptions import TemplatesNotFound38from .exceptions import TemplateSyntaxError39from .exceptions import UndefinedError40from .lexer import get_lexer41from .lexer import Lexer42from .lexer import TokenStream43from .nodes import EvalContext44from .parser import Parser45from .runtime import Context
6 unmodified lines
52from .utils import internalcode53from .utils import LRUCache54from .utils import missing5553# for direct template usage we have up to ten living environments54_spontaneous_environments = LRUCache(10)56if t.TYPE_CHECKING:57 import typing_extensions as te58 from .bccache import BytecodeCache59 from .ext import Extension60 from .loaders import BaseLoader6162_env_bound = t.TypeVar("_env_bound", bound="Environment")6357def get_spontaneous_environment(cls, *args):6465# for direct template usage we have up to ten living environments66@lru_cache(maxsize=10)67def get_spontaneous_environment(cls: t.Type[_env_bound], *args: t.Any) -> _env_bound:68 """Return a new spontaneous environment. A spontaneous environment69 is used for templates created directly rather than through an70 existing environment.7172 :param cls: Environment class to create.73 :param args: Positional arguments passed to environment.74 """65 key = (cls, args)75 env = cls(*args)76 env.shared = True77 return env7867 try:68 return _spontaneous_environments[key]69 except KeyError:70 _spontaneous_environments[key] = env = cls(*args)71 env.shared = True72 return env797475def create_cache(size):80def create_cache(81 size: int,82) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:83 """Return the cache class for the given size."""84 if size == 0:85 return None8687 if size < 0:88 return {}81 return LRUCache(size)8990 return LRUCache(size) # type: ignore919284def copy_cache(cache):93def copy_cache(94 cache: t.Optional[t.MutableMapping],95) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:96 """Create an empty copy of the given cache."""97 if cache is None:98 return None9988 elif type(cache) is dict:100 if type(cache) is dict:101 return {}90 return LRUCache(cache.capacity)102103 return LRUCache(cache.capacity) # type: ignore10493def load_extensions(environment, extensions):105106def load_extensions(107 environment: "Environment",108 extensions: t.Sequence[t.Union[str, t.Type["Extension"]]],109) -> t.Dict[str, "Extension"]:110 """Load the extensions from the list and bind it to the environment.95 Returns a dict of instantiated environments.111 Returns a dict of instantiated extensions.112 """113 result = {}114115 for extension in extensions:116 if isinstance(extension, str):100 extension = import_string(extension)117 extension = t.cast(t.Type["Extension"], import_string(extension))118119 result[extension.identifier] = extension(environment)120121 return result122123105def _environment_sanity_check(environment):124def _environment_config_check(environment: "Environment") -> "Environment":125 """Perform a sanity check on the environment."""126 assert issubclass(127 environment.undefined, Undefined109 ), "undefined must be a subclass of undefined because filters depend on it."128 ), "'undefined' must be a subclass of 'jinja2.Undefined'."129 assert (130 environment.block_start_string131 != environment.variable_start_string132 != environment.comment_start_string114 ), "block, variable and comment start strings must be different"133 ), "block, variable and comment start strings must be different."134 assert environment.newline_sequence in {135 "\r",136 "\r\n",137 "\n",119 }, "newline_sequence set to unknown line ending string."138 }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."139 return environment140141142class Environment:
135 unmodified lines
278 shared = False279280 #: the class that is used for code generation. See281 #: :class:`~jinja2.compiler.CodeGenerator` for more information.263 code_generator_class = CodeGenerator282 code_generator_class: t.Type["CodeGenerator"] = CodeGenerator283284 #: the context class that is used for templates. See285 #: :class:`~jinja2.runtime.Context` for more information.267 context_class = Context286 context_class: t.Type[Context] = Context287288 template_class: t.Type["Template"]289290 def __init__(291 self,273 block_start_string=BLOCK_START_STRING,274 block_end_string=BLOCK_END_STRING,275 variable_start_string=VARIABLE_START_STRING,276 variable_end_string=VARIABLE_END_STRING,277 comment_start_string=COMMENT_START_STRING,278 comment_end_string=COMMENT_END_STRING,279 line_statement_prefix=LINE_STATEMENT_PREFIX,280 line_comment_prefix=LINE_COMMENT_PREFIX,281 trim_blocks=TRIM_BLOCKS,282 lstrip_blocks=LSTRIP_BLOCKS,283 newline_sequence=NEWLINE_SEQUENCE,284 keep_trailing_newline=KEEP_TRAILING_NEWLINE,285 extensions=(),286 optimized=True,287 undefined=Undefined,288 finalize=None,289 autoescape=False,290 loader=None,291 cache_size=400,292 auto_reload=True,293 bytecode_cache=None,294 enable_async=False,292 block_start_string: str = BLOCK_START_STRING,293 block_end_string: str = BLOCK_END_STRING,294 variable_start_string: str = VARIABLE_START_STRING,295 variable_end_string: str = VARIABLE_END_STRING,296 comment_start_string: str = COMMENT_START_STRING,297 comment_end_string: str = COMMENT_END_STRING,298 line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,299 line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,300 trim_blocks: bool = TRIM_BLOCKS,301 lstrip_blocks: bool = LSTRIP_BLOCKS,302 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,303 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,304 extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),305 optimized: bool = True,306 undefined: t.Type[Undefined] = Undefined,307 finalize: t.Optional[t.Callable[..., t.Any]] = None,308 autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,309 loader: t.Optional["BaseLoader"] = None,310 cache_size: int = 400,311 auto_reload: bool = True,312 bytecode_cache: t.Optional["BytecodeCache"] = None,313 enable_async: bool = False,314 ):315 # !!Important notice!!316 # The constructor accepts quite a few arguments that should be317 # passed by keyword rather than position. However it's important to
42 unmodified lines
360 # load extensions361 self.extensions = load_extensions(self, extensions)362363 self.is_async = enable_async345 _environment_sanity_check(self)364 _environment_config_check(self)365347 def add_extension(self, extension):366 def add_extension(self, extension: t.Union[str, t.Type["Extension"]]) -> None:367 """Adds an extension after the environment was created.368369 .. versionadded:: 2.5370 """371 self.extensions.update(load_extensions(self, [extension]))372354 def extend(self, **attributes):373 def extend(self, **attributes: t.Any) -> None:374 """Add the items to the instance of the environment if they do not exist375 yet. This is used by :ref:`extensions <writing-extensions>` to register376 callbacks and configuration values without breaking inheritance.377 """
2 unmodified lines
380 setattr(self, key, value)381382 def overlay(383 self,365 block_start_string=missing,366 block_end_string=missing,367 variable_start_string=missing,368 variable_end_string=missing,369 comment_start_string=missing,370 comment_end_string=missing,371 line_statement_prefix=missing,372 line_comment_prefix=missing,373 trim_blocks=missing,374 lstrip_blocks=missing,375 extensions=missing,376 optimized=missing,377 undefined=missing,378 finalize=missing,379 autoescape=missing,380 loader=missing,381 cache_size=missing,382 auto_reload=missing,383 bytecode_cache=missing,384 ):384 block_start_string: str = missing,385 block_end_string: str = missing,386 variable_start_string: str = missing,387 variable_end_string: str = missing,388 comment_start_string: str = missing,389 comment_end_string: str = missing,390 line_statement_prefix: t.Optional[str] = missing,391 line_comment_prefix: t.Optional[str] = missing,392 trim_blocks: bool = missing,393 lstrip_blocks: bool = missing,394 extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = missing,395 optimized: bool = missing,396 undefined: t.Type[Undefined] = missing,397 finalize: t.Optional[t.Callable[..., t.Any]] = missing,398 autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = missing,399 loader: t.Optional["BaseLoader"] = missing,400 cache_size: int = missing,401 auto_reload: bool = missing,402 bytecode_cache: t.Optional["BytecodeCache"] = missing,403 ) -> "Environment":404 """Create a new overlay environment that shares all the data with the405 current environment except for cache and the overridden attributes.406 Extensions cannot be removed for an overlayed environment. An overlayed407 environment automatically gets all the extensions of the environment it
26 unmodified lines
434 rv.extensions[key] = value.bind(rv)435 if extensions is not missing:436 rv.extensions.update(load_extensions(rv, extensions))437419 return _environment_sanity_check(rv)438 return _environment_config_check(rv)439421 lexer = property(get_lexer, doc="The lexer for this environment.")440 @property441 def lexer(self) -> Lexer:442 """The lexer for this environment."""443 return get_lexer(self)444423 def iter_extensions(self):445 def iter_extensions(self) -> t.Iterator["Extension"]:446 """Iterates over the extensions by priority."""447 return iter(sorted(self.extensions.values(), key=lambda x: x.priority))448427 def getitem(self, obj, argument):449 def getitem(450 self, obj: t.Any, argument: t.Union[str, t.Any]451 ) -> t.Union[t.Any, Undefined]:452 """Get an item or attribute of an object but prefer the item."""453 try:454 return obj[argument]455 except (AttributeError, TypeError, LookupError):
8 unmodified lines
464 except AttributeError:465 pass466 return self.undefined(obj=obj, name=argument)467444 def getattr(self, obj, attribute):468 def getattr(self, obj: t.Any, attribute: str) -> t.Any:469 """Get an item or attribute of an object but prefer the attribute.446 Unlike :meth:`getitem` the attribute *must* be a bytestring.470 Unlike :meth:`getitem` the attribute *must* be a string.471 """472 try:473 return getattr(obj, attribute)474 except AttributeError:
3 unmodified lines
478 except (TypeError, LookupError, AttributeError):479 return self.undefined(obj=obj, name=attribute)480481 def _filter_test_common(458 self, name, value, args, kwargs, context, eval_ctx, is_filter459 ):482 self,483 name: t.Union[str, Undefined],484 value: t.Any,485 args: t.Optional[t.Sequence[t.Any]],486 kwargs: t.Optional[t.Mapping[str, t.Any]],487 context: t.Optional[Context],488 eval_ctx: t.Optional[EvalContext],489 is_filter: bool,490 ) -> t.Any:491 if is_filter:492 env_map = self.filters493 type_name = "filter"494 else:495 env_map = self.tests496 type_name = "test"497467 func = env_map.get(name)498 func = env_map.get(name) # type: ignore499500 if func is None:501 msg = f"No {type_name} named {name!r}."502
29 unmodified lines
532533 return func(*args, **kwargs)534535 def call_filter(505 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None506 ):536 self,537 name: str,538 value: t.Any,539 args: t.Optional[t.Sequence[t.Any]] = None,540 kwargs: t.Optional[t.Mapping[str, t.Any]] = None,541 context: t.Optional[Context] = None,542 eval_ctx: t.Optional[EvalContext] = None,543 ) -> t.Any:544 """Invoke a filter on a value the same way the compiler does.545546 This might return a coroutine if the filter is running from an547 environment in async mode and the filter supports async
5 unmodified lines
553 name, value, args, kwargs, context, eval_ctx, True554 )555556 def call_test(520 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None521 ):557 self,558 name: str,559 value: t.Any,560 args: t.Optional[t.Sequence[t.Any]] = None,561 kwargs: t.Optional[t.Mapping[str, t.Any]] = None,562 context: t.Optional[Context] = None,563 eval_ctx: t.Optional[EvalContext] = None,564 ) -> t.Any:565 """Invoke a test on a value the same way the compiler does.566567 This might return a coroutine if the test is running from an568 environment in async mode and the test supports async execution.
9 unmodified lines
578 name, value, args, kwargs, context, eval_ctx, False579 )580581 @internalcode539 def parse(self, source, name=None, filename=None):582 def parse(583 self,584 source: str,585 name: t.Optional[str] = None,586 filename: t.Optional[str] = None,587 ) -> nodes.Template:588 """Parse the sourcecode and return the abstract syntax tree. This589 tree of nodes is used by the compiler to convert the template into590 executable source- or bytecode. This is useful for debugging or to591 extract information from templates.
5 unmodified lines
597 return self._parse(source, name, filename)598 except TemplateSyntaxError:599 self.handle_exception(source=source)600553 def _parse(self, source, name, filename):601 def _parse(602 self, source: str, name: t.Optional[str], filename: t.Optional[str]603 ) -> nodes.Template:604 """Internal parsing function used by `parse` and `compile`."""605 return Parser(self, source, name, filename).parse()606557 def lex(self, source, name=None, filename=None):607 def lex(608 self,609 source: str,610 name: t.Optional[str] = None,611 filename: t.Optional[str] = None,612 ) -> t.Iterator[t.Tuple[int, str, str]]:613 """Lex the given sourcecode and return a generator that yields614 tokens as tuples in the form ``(lineno, token_type, value)``.615 This can be useful for :ref:`extension development <writing-extensions>`616 and debugging templates.
7 unmodified lines
624 return self.lexer.tokeniter(source, name, filename)625 except TemplateSyntaxError:626 self.handle_exception(source=source)627573 def preprocess(self, source, name=None, filename=None):628 def preprocess(629 self,630 source: str,631 name: t.Optional[str] = None,632 filename: t.Optional[str] = None,633 ) -> str:634 """Preprocesses the source with all extensions. This is automatically635 called for all parsing and compiling methods but *not* for :meth:`lex`636 because there you usually only want the actual source tokenized.637 """
2 unmodified lines
640 self.iter_extensions(),641 str(source),642 )643584 def _tokenize(self, source, name, filename=None, state=None):644 def _tokenize(645 self,646 source: str,647 name: t.Optional[str],648 filename: t.Optional[str] = None,649 state: t.Optional[str] = None,650 ) -> TokenStream:651 """Called by the parser to do the preprocessing and filtering652 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.653 """654 source = self.preprocess(source, name, filename)655 stream = self.lexer.tokenize(source, name, filename, state)656657 for ext in self.iter_extensions():591 stream = ext.filter_stream(stream)658 stream = ext.filter_stream(stream) # type: ignore659660 if not isinstance(stream, TokenStream):593 stream = TokenStream(stream, name, filename)661 stream = TokenStream(stream, name, filename) # type: ignore662663 return stream664596 def _generate(self, source, name, filename, defer_init=False):665 def _generate(666 self,667 source: nodes.Template,668 name: t.Optional[str],669 filename: t.Optional[str],670 defer_init: bool = False,671 ) -> str:672 """Internal hook that can be overridden to hook a different generate673 method in.674675 .. versionadded:: 2.5676 """602 return generate(677 return generate( # type: ignore678 source,679 self,680 name,681 filename,682 defer_init=defer_init,683 optimized=self.optimized,684 )685611 def _compile(self, source, filename):686 def _compile(self, source: str, filename: str) -> CodeType:687 """Internal hook that can be overridden to hook a different compile688 method in.689690 .. versionadded:: 2.5691 """617 return compile(source, filename, "exec")692 return compile(source, filename, "exec") # type: ignore693694 @typing.overload695 def compile( # type: ignore696 self,697 source: t.Union[str, nodes.Template],698 name: t.Optional[str] = None,699 filename: t.Optional[str] = None,700 raw: "te.Literal[False]" = False,701 defer_init: bool = False,702 ) -> CodeType:703 ...704705 @typing.overload706 def compile(707 self,708 source: t.Union[str, nodes.Template],709 name: t.Optional[str] = None,710 filename: t.Optional[str] = None,711 raw: "te.Literal[True]" = ...,712 defer_init: bool = False,713 ) -> str:714 ...715716 @internalcode620 def compile(self, source, name=None, filename=None, raw=False, defer_init=False):717 def compile(718 self,719 source: t.Union[str, nodes.Template],720 name: t.Optional[str] = None,721 filename: t.Optional[str] = None,722 raw: bool = False,723 defer_init: bool = False,724 ) -> t.Union[str, CodeType]:725 """Compile a node or template source code. The `name` parameter is726 the load name of the template after it was joined using727 :meth:`join_path` if necessary, not the filename on the file system.728 the `filename` parameter is the estimated filename of the template on
25 unmodified lines
754 return self._compile(source, filename)755 except TemplateSyntaxError:756 self.handle_exception(source=source_hint)757654 def compile_expression(self, source, undefined_to_none=True):758 def compile_expression(759 self, source: str, undefined_to_none: bool = True760 ) -> "TemplateExpression":761 """A handy helper method that returns a callable that accepts keyword762 arguments that appear as variables in the expression. If called it763 returns the result of the expression.764
28 unmodified lines
793 "chunk after expression", parser.stream.current.lineno, None, None794 )795 expr.set_environment(self)796 except TemplateSyntaxError:691 if sys.exc_info() is not None:692 self.handle_exception(source=source)797 self.handle_exception(source=source)798799 body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]800 template = self.from_string(nodes.Template(body, lineno=1))801 return TemplateExpression(template, undefined_to_none)802803 def compile_templates(804 self,700 target,701 extensions=None,702 filter_func=None,703 zip="deflated",704 log_function=None,705 ignore_errors=True,706 ):805 target: t.Union[str, os.PathLike],806 extensions: t.Optional[t.Collection[str]] = None,807 filter_func: t.Optional[t.Callable[[str], bool]] = None,808 zip: t.Optional[str] = "deflated",809 log_function: t.Optional[t.Callable[[str], None]] = None,810 ignore_errors: bool = True,811 ) -> None:812 """Finds all the templates the loader can find, compiles them813 and stores them in `target`. If `zip` is `None`, instead of in a814 zipfile, the templates will be stored in a directory.815 By default a deflate zip algorithm is used. To switch to
13 unmodified lines
829 from .loaders import ModuleLoader830831 if log_function is None:832728 def log_function(x):833 def log_function(x: str) -> None:834 pass835836 assert log_function is not None837 assert self.loader is not None, "No loader configured."838731 def write_file(filename, data):839 def write_file(filename: str, data: str) -> None:840 if zip:841 info = ZipInfo(filename)842 info.external_attr = 0o755 << 16843 zip_file.writestr(info, data)844 else:737 if isinstance(data, str):738 data = data.encode("utf8")739845 with open(os.path.join(target, filename), "wb") as f:741 f.write(data)846 f.write(data.encode("utf8"))847848 if zip is not None:849 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED850
26 unmodified lines
877 zip_file.close()878879 log_function("Finished compiling templates")880776 def list_templates(self, extensions=None, filter_func=None):881 def list_templates(882 self,883 extensions: t.Optional[t.Collection[str]] = None,884 filter_func: t.Optional[t.Callable[[str], bool]] = None,885 ) -> t.List[str]:886 """Returns a list of templates for this environment. This requires887 that the loader supports the loader's888 :meth:`~BaseLoader.list_templates` method.889
7 unmodified lines
897 If the loader does not support that, a :exc:`TypeError` is raised.898899 .. versionadded:: 2.4900 """901 assert self.loader is not None, "No loader configured."902 names = self.loader.list_templates()903904 if extensions is not None:905 if filter_func is not None:906 raise TypeError(907 "either extensions or filter_func can be passed, but not both"908 )909800 def filter_func(x):801 return "." in x and x.rsplit(".", 1)[1] in extensions910 def filter_func(x: str) -> bool:911 return "." in x and x.rsplit(".", 1)[1] in extensions # type: ignore912913 if filter_func is not None:914 names = [name for name in names if filter_func(name)]915916 return names917808 def handle_exception(self, source=None):918 def handle_exception(self, source: t.Optional[str] = None) -> t.NoReturn:919 """Exception handling helper. This is used internally to either raise920 rewritten exceptions or return a rendered traceback for the template.921 """922 from .debug import rewrite_traceback_stack923924 raise rewrite_traceback_stack(source=source)925816 def join_path(self, template, parent):926 def join_path(self, template: str, parent: str) -> str:927 """Join a template with the parent. By default all the lookups are928 relative to the loader root so this method returns the `template`929 parameter unchanged, but if the paths should be relative to the930 parent template, this function can be used to calculate the real
4 unmodified lines
935 """936 return template937938 @internalcode829 def _load_template(self, name, globals):939 def _load_template(940 self, name: str, globals: t.Optional[t.Mapping[str, t.Any]]941 ) -> "Template":942 if self.loader is None:943 raise TypeError("no loader for this environment specified")944 cache_key = (weakref.ref(self.loader), name)945 if self.cache is not None:
14 unmodified lines
960 self.cache[cache_key] = template961 return template962963 @internalcode852 def get_template(self, name, parent=None, globals=None):964 def get_template(965 self,966 name: t.Union[str, "Template"],967 parent: t.Optional[str] = None,968 globals: t.Optional[t.Mapping[str, t.Any]] = None,969 ) -> "Template":970 """Load a template by name with :attr:`loader` and return a971 :class:`Template`. If the template does not exist a972 :exc:`TemplateNotFound` exception is raised.973
21 unmodified lines
995996 return self._load_template(name, globals)997998 @internalcode882 def select_template(self, names, parent=None, globals=None):999 def select_template(1000 self,1001 names: t.Iterable[t.Union[str, "Template"]],1002 parent: t.Optional[str] = None,1003 globals: t.Optional[t.Mapping[str, t.Any]] = None,1004 ) -> "Template":1005 """Like :meth:`get_template`, but tries loading multiple names.1006 If none of the names can be loaded a :exc:`TemplatesNotFound`1007 exception is raised.1008
37 unmodified lines
1046 try:1047 return self._load_template(name, globals)1048 except (TemplateNotFound, UndefinedError):1049 pass928 raise TemplatesNotFound(names)1050 raise TemplatesNotFound(names) # type: ignore10511052 @internalcode931 def get_or_select_template(self, template_name_or_list, parent=None, globals=None):1053 def get_or_select_template(1054 self,1055 template_name_or_list: t.Union[1056 str, "Template", t.List[t.Union[str, "Template"]]1057 ],1058 parent: t.Optional[str] = None,1059 globals: t.Optional[t.Mapping[str, t.Any]] = None,1060 ) -> "Template":1061 """Use :meth:`select_template` if an iterable of template names1062 is given, or :meth:`get_template` if one name is given.10631064 .. versionadded:: 2.3
3 unmodified lines
1068 elif isinstance(template_name_or_list, Template):1069 return template_name_or_list1070 return self.select_template(template_name_or_list, parent, globals)1071943 def from_string(self, source, globals=None, template_class=None):1072 def from_string(1073 self,1074 source: t.Union[str, nodes.Template],1075 globals: t.Optional[t.Mapping[str, t.Any]] = None,1076 template_class: t.Optional[t.Type["Template"]] = None,1077 ) -> "Template":1078 """Load a template from a source string without using1079 :attr:`loader`.10801081 :param source: Jinja source to compile into a template.
3 unmodified lines
1085 cached, its globals are updated with any new items.1086 :param template_class: Return an instance of this1087 :class:`Template` class.1088 """955 globals = self.make_globals(globals)1089 gs = self.make_globals(globals)1090 cls = template_class or self.template_class957 return cls.from_code(self, self.compile(source), globals, None)1091 return cls.from_code(self, self.compile(source), gs, None)1092959 def make_globals(self, d):1093 def make_globals(1094 self, d: t.Optional[t.Mapping[str, t.Any]]1095 ) -> t.MutableMapping[str, t.Any]:1096 """Make the globals map for a template. Any given template1097 globals overlay the environment :attr:`globals`.10981099 Returns a :class:`collections.ChainMap`. This allows any changes
44 unmodified lines
1144 """11451146 #: Type of environment to create when creating a template directly1147 #: rather than through an existing environment.1012 environment_class = Environment1148 environment_class: t.Type[Environment] = Environment11491150 environment: Environment1151 globals: t.MutableMapping[str, t.Any]1152 name: t.Optional[str]1153 filename: t.Optional[str]1154 blocks: t.Dict[str, t.Callable[[Context], t.Iterator[str]]]1155 root_render_func: t.Callable[[Context], t.Iterator[str]]1156 _module: t.Optional["TemplateModule"]1157 _debug_info: str1158 _uptodate: t.Optional[t.Callable[[], bool]]11591160 def __new__(1161 cls,1016 source,1017 block_start_string=BLOCK_START_STRING,1018 block_end_string=BLOCK_END_STRING,1019 variable_start_string=VARIABLE_START_STRING,1020 variable_end_string=VARIABLE_END_STRING,1021 comment_start_string=COMMENT_START_STRING,1022 comment_end_string=COMMENT_END_STRING,1023 line_statement_prefix=LINE_STATEMENT_PREFIX,1024 line_comment_prefix=LINE_COMMENT_PREFIX,1025 trim_blocks=TRIM_BLOCKS,1026 lstrip_blocks=LSTRIP_BLOCKS,1027 newline_sequence=NEWLINE_SEQUENCE,1028 keep_trailing_newline=KEEP_TRAILING_NEWLINE,1029 extensions=(),1030 optimized=True,1031 undefined=Undefined,1032 finalize=None,1033 autoescape=False,1034 enable_async=False,1035 ):1162 source: t.Union[str, nodes.Template],1163 block_start_string: str = BLOCK_START_STRING,1164 block_end_string: str = BLOCK_END_STRING,1165 variable_start_string: str = VARIABLE_START_STRING,1166 variable_end_string: str = VARIABLE_END_STRING,1167 comment_start_string: str = COMMENT_START_STRING,1168 comment_end_string: str = COMMENT_END_STRING,1169 line_statement_prefix: t.Optional[str] = LINE_STATEMENT_PREFIX,1170 line_comment_prefix: t.Optional[str] = LINE_COMMENT_PREFIX,1171 trim_blocks: bool = TRIM_BLOCKS,1172 lstrip_blocks: bool = LSTRIP_BLOCKS,1173 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,1174 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,1175 extensions: t.Sequence[t.Union[str, t.Type["Extension"]]] = (),1176 optimized: bool = True,1177 undefined: t.Type[Undefined] = Undefined,1178 finalize: t.Optional[t.Callable[..., t.Any]] = None,1179 autoescape: t.Union[bool, t.Callable[[t.Optional[str]], bool]] = False,1180 enable_async: bool = False,1181 ) -> "Template":1182 env = get_spontaneous_environment(1037 cls.environment_class,1183 cls.environment_class, # type: ignore1184 block_start_string,1185 block_end_string,1186 variable_start_string,1187 variable_end_string,
6 unmodified lines
1194 newline_sequence,1195 keep_trailing_newline,1196 frozenset(extensions),1197 optimized,1052 undefined,1198 undefined, # type: ignore1199 finalize,1200 autoescape,1201 None,1202 0,
3 unmodified lines
1206 )1207 return env.from_string(source, template_class=cls)12081209 @classmethod1064 def from_code(cls, environment, code, globals, uptodate=None):1210 def from_code(1211 cls,1212 environment: Environment,1213 code: CodeType,1214 globals: t.MutableMapping[str, t.Any],1215 uptodate: t.Optional[t.Callable[[], bool]] = None,1216 ) -> "Template":1217 """Creates a template object from compiled code and the globals. This1218 is used by the loaders and environment to create a template object.1219 """1220 namespace = {"environment": environment, "__file__": code.co_filename}
2 unmodified lines
1223 rv._uptodate = uptodate1224 return rv12251226 @classmethod1075 def from_module_dict(cls, environment, module_dict, globals):1227 def from_module_dict(1228 cls,1229 environment: Environment,1230 module_dict: t.MutableMapping[str, t.Any],1231 globals: t.MutableMapping[str, t.Any],1232 ) -> "Template":1233 """Creates a template object from a module. This is used by the1234 module loader to create a template object.12351236 .. versionadded:: 2.41237 """1238 return cls._from_namespace(environment, module_dict, globals)12391240 @classmethod1084 def _from_namespace(cls, environment, namespace, globals):1085 t = object.__new__(cls)1241 def _from_namespace(1242 cls,1243 environment: Environment,1244 namespace: t.MutableMapping[str, t.Any],1245 globals: t.MutableMapping[str, t.Any],1246 ) -> "Template":1247 t: "Template" = object.__new__(cls)1248 t.environment = environment1249 t.globals = globals1250 t.name = namespace["name"]1251 t.filename = namespace["__file__"]1252 t.blocks = namespace["blocks"]12531254 # render function and module1093 t.root_render_func = namespace["root"]1255 t.root_render_func = namespace["root"] # type: ignore1256 t._module = None12571258 # debug and loader helpers1259 t._debug_info = namespace["debug_info"]
4 unmodified lines
1264 namespace["__jinja_template__"] = t12651266 return t12671106 def render(self, *args, **kwargs):1268 def render(self, *args: t.Any, **kwargs: t.Any) -> str:1269 """This method accepts the same arguments as the `dict` constructor:1270 A dict, a dict subclass or some keyword arguments. If no arguments1271 are given the context will be empty. These two calls do the same::1272
10 unmodified lines
12831284 ctx = self.new_context(dict(*args, **kwargs))12851286 try:1125 return concat(self.root_render_func(ctx))1287 return concat(self.root_render_func(ctx)) # type: ignore1288 except Exception:1289 self.environment.handle_exception()12901129 async def render_async(self, *args, **kwargs):1291 async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:1292 """This works similar to :meth:`render` but returns a coroutine1293 that when awaited returns the entire rendered template string. This1294 requires the async feature to be enabled.1295
8 unmodified lines
13041305 ctx = self.new_context(dict(*args, **kwargs))13061307 try:1146 return concat([n async for n in self.root_render_func(ctx)])1308 return concat([n async for n in self.root_render_func(ctx)]) # type: ignore1309 except Exception:1310 return self.environment.handle_exception()13111150 def stream(self, *args, **kwargs):1312 def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":1313 """Works exactly like :meth:`generate` but returns a1314 :class:`TemplateStream`.1315 """1316 return TemplateStream(self.generate(*args, **kwargs))13171156 def generate(self, *args, **kwargs):1318 def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:1319 """For very large templates it can be useful to not render the whole1320 template at once but evaluate each statement after another and yield1321 piece for piece. This method basically does exactly that and returns1322 a generator that yields one item after another as strings.
14 unmodified lines
13371338 ctx = self.new_context(dict(*args, **kwargs))13391340 try:1179 yield from self.root_render_func(ctx)1341 yield from self.root_render_func(ctx) # type: ignore1342 except Exception:1343 yield self.environment.handle_exception()13441183 async def generate_async(self, *args, **kwargs):1345 async def generate_async(1346 self, *args: t.Any, **kwargs: t.Any1347 ) -> t.AsyncIterator[str]:1348 """An async version of :meth:`generate`. Works very similarly but1349 returns an async iterator instead.1350 """1351 if not self.environment.is_async:
3 unmodified lines
13551356 ctx = self.new_context(dict(*args, **kwargs))13571358 try:1195 async for event in self.root_render_func(ctx):1359 async for event in self.root_render_func(ctx): # type: ignore1360 yield event1361 except Exception:1362 yield self.environment.handle_exception()13631200 def new_context(self, vars=None, shared=False, locals=None):1364 def new_context(1365 self,1366 vars: t.Optional[t.Dict[str, t.Any]] = None,1367 shared: bool = False,1368 locals: t.Optional[t.Mapping[str, t.Any]] = None,1369 ) -> Context:1370 """Create a new :class:`Context` for this template. The vars1371 provided will be passed to the template. Per default the globals1372 are added to the context. If shared is set to `True` the data1373 is passed as is to the context without adding the globals.
3 unmodified lines
1377 return new_context(1378 self.environment, self.name, self.blocks, vars, shared, self.globals, locals1379 )13801212 def make_module(self, vars=None, shared=False, locals=None):1381 def make_module(1382 self,1383 vars: t.Optional[t.Dict[str, t.Any]] = None,1384 shared: bool = False,1385 locals: t.Optional[t.Mapping[str, t.Any]] = None,1386 ) -> "TemplateModule":1387 """This method works like the :attr:`module` attribute when called1388 without arguments but it will evaluate the template on every call1389 rather than caching it. It's also possible to provide1390 a dict which is then used as context. The arguments are the same
1 unmodified line
1392 """1393 ctx = self.new_context(vars, shared, locals)1394 return TemplateModule(self, ctx)13951222 async def make_module_async(self, vars=None, shared=False, locals=None):1396 async def make_module_async(1397 self,1398 vars: t.Optional[t.Dict[str, t.Any]] = None,1399 shared: bool = False,1400 locals: t.Optional[t.Mapping[str, t.Any]] = None,1401 ) -> "TemplateModule":1402 """As template module creation can invoke template code for1403 asynchronous executions this method must be used instead of the1404 normal :meth:`make_module` one. Likewise the module attribute1405 becomes unavailable in async mode.1406 """1407 ctx = self.new_context(vars, shared, locals)1229 return TemplateModule(self, ctx, [x async for x in self.root_render_func(ctx)])1408 return TemplateModule(1409 self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore1410 )14111412 @internalcode1232 def _get_default_module(self, ctx=None):1413 def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":1414 """If a context is passed in, this means that the template was1415 imported. Imported templates have access to the current1416 template's globals by default, but they can only be accessed via1417 the context during runtime.
17 unmodified lines
1435 self._module = self.make_module()14361437 return self._module14381258 async def _get_default_module_async(self, ctx=None):1439 async def _get_default_module_async(1440 self, ctx: t.Optional[Context] = None1441 ) -> "TemplateModule":1442 if ctx is not None:1443 keys = ctx.globals_keys - self.globals.keys()14441445 if keys:
4 unmodified lines
14501451 return self._module14521453 @property1271 def module(self):1454 def module(self) -> "TemplateModule":1455 """The template as module. This is used for imports in the1456 template runtime but is also useful if one wants to access1457 exported template variables from the Python layer:1458
6 unmodified lines
1465 This attribute is not available if async mode is enabled.1466 """1467 return self._get_default_module()14681286 def get_corresponding_lineno(self, lineno):1469 def get_corresponding_lineno(self, lineno: int) -> int:1470 """Return the source line number of a line number in the1471 generated bytecode as they are not in sync.1472 """1473 for template_line, code_line in reversed(self.debug_info):
1 unmodified line
1475 return template_line1476 return 114771478 @property1296 def is_up_to_date(self):1479 def is_up_to_date(self) -> bool:1480 """If this variable is `False` there is a newer version available."""1481 if self._uptodate is None:1482 return True1483 return self._uptodate()14841485 @property1303 def debug_info(self):1486 def debug_info(self) -> t.List[t.Tuple[int, int]]:1487 """The debug info mapping."""1488 if self._debug_info:1306 return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")]1489 return [1490 tuple(map(int, x.split("="))) # type: ignore1491 for x in self._debug_info.split("&")1492 ]14931494 return []14951309 def __repr__(self):1496 def __repr__(self) -> str:1497 if self.name is None:1498 name = f"memory:{id(self):x}"1499 else:1500 name = repr(self.name)1314 return f"<{self.__class__.__name__} {name}>"1501 return f"<{type(self).__name__} {name}>"150215031504class TemplateModule:1505 """Represents an imported template. All the exported names of the1506 template are available as attributes on this object. Additionally1507 converting it into a string renders the contents.1508 """15091323 def __init__(self, template, context, body_stream=None):1510 def __init__(1511 self,1512 template: Template,1513 context: Context,1514 body_stream: t.Optional[t.Iterable[str]] = None,1515 ) -> None:1516 if body_stream is None:1517 if context.environment.is_async:1518 raise RuntimeError(1327 "Async mode requires a body stream "1328 "to be passed to a template module. Use "1329 "the async methods of the API you are "1330 "using."1519 "Async mode requires a body stream to be passed to"1520 " a template module. Use the async methods of the"1521 " API you are using."1522 )15231332 body_stream = list(template.root_render_func(context))1524 body_stream = list(template.root_render_func(context)) # type: ignore15251526 self._body_stream = body_stream1527 self.__dict__.update(context.get_exported())1528 self.__name__ = template.name15291337 def __html__(self):1530 def __html__(self) -> Markup:1531 return Markup(concat(self._body_stream))15321340 def __str__(self):1533 def __str__(self) -> str:1534 return concat(self._body_stream)15351343 def __repr__(self):1536 def __repr__(self) -> str:1537 if self.__name__ is None:1538 name = f"memory:{id(self):x}"1539 else:1540 name = repr(self.__name__)1348 return f"<{self.__class__.__name__} {name}>"1541 return f"<{type(self).__name__} {name}>"154215431544class TemplateExpression:1545 """The :meth:`jinja2.Environment.compile_expression` method returns an1546 instance of this object. It encapsulates the expression-like access1547 to the template with an expression it wraps.1548 """15491357 def __init__(self, template, undefined_to_none):1550 def __init__(self, template: Template, undefined_to_none: bool) -> None:1551 self._template = template1552 self._undefined_to_none = undefined_to_none15531361 def __call__(self, *args, **kwargs):1554 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Optional[t.Any]:1555 context = self._template.new_context(dict(*args, **kwargs))1363 consume(self._template.root_render_func(context))1556 consume(self._template.root_render_func(context)) # type: ignore1557 rv = context.vars["result"]1558 if self._undefined_to_none and isinstance(rv, Undefined):1559 rv = None1560 return rv
9 unmodified lines
1570 into a new string. This is mainly useful if you are streaming1571 big templates to a client via WSGI which flushes after each iteration.1572 """15731381 def __init__(self, gen):1574 def __init__(self, gen: t.Iterator[str]) -> None:1575 self._gen = gen1576 self.disable_buffering()15771385 def dump(self, fp, encoding=None, errors="strict"):1578 def dump(1579 self,1580 fp: t.Union[str, t.IO],1581 encoding: t.Optional[str] = None,1582 errors: t.Optional[str] = "strict",1583 ) -> None:1584 """Dump the complete stream into a file or file-like object.1585 Per default strings are written, if you want to encode1586 before writing specify an `encoding`.1587
1 unmodified line
15891590 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1591 """1592 close = False15931594 if isinstance(fp, str):1595 if encoding is None:1596 encoding = "utf-8"15971598 fp = open(fp, "wb")1599 close = True1600 try:1601 if encoding is not None:1402 iterable = (x.encode(encoding, errors) for x in self)1602 iterable = (x.encode(encoding, errors) for x in self) # type: ignore1603 else:1404 iterable = self1604 iterable = self # type: ignore16051606 if hasattr(fp, "writelines"):1607 fp.writelines(iterable)1608 else:1609 for item in iterable:
1 unmodified line
1611 finally:1612 if close:1613 fp.close()16141414 def disable_buffering(self):1615 def disable_buffering(self) -> None:1616 """Disable the output buffering."""1617 self._next = partial(next, self._gen)1618 self.buffered = False16191419 def _buffered_generator(self, size):1420 buf = []1620 def _buffered_generator(self, size: int) -> t.Iterator[str]:1621 buf: t.List[str] = []1622 c_size = 01623 push = buf.append16241424 while 1:1625 while True:1626 try:1627 while c_size < size:1628 c = next(self._gen)1629 push(c)
5 unmodified lines
1635 yield concat(buf)1636 del buf[:]1637 c_size = 016381438 def enable_buffering(self, size=5):1639 def enable_buffering(self, size: int = 5) -> None:1640 """Enable buffering. Buffer `size` items before yielding them."""1641 if size <= 1:1642 raise ValueError("buffer size too small")16431644 self.buffered = True1645 self._next = partial(next, self._buffered_generator(size))16461446 def __iter__(self):1647 def __iter__(self) -> "TemplateStream":1648 return self16491449 def __next__(self):1450 return self._next()1650 def __next__(self) -> str:1651 return self._next() # type: ignore165216531654# hook in default template class. if anyone reads this comment: ignore that1655# it's possible to use custom templates ;-)
1 unmodified line
modified:src/jinja2/exceptions.py+41 added-22 removed
1import typing as t23if t.TYPE_CHECKING:4 from .runtime import Undefined567class TemplateError(Exception):8 """Baseclass for all template errors."""94 def __init__(self, message=None):10 def __init__(self, message: t.Optional[str] = None) -> None:11 super().__init__(message)1213 @property8 def message(self):9 if self.args:10 return self.args[0]14 def message(self) -> t.Optional[str]:15 return self.args[0] if self.args else None161718class TemplateNotFound(IOError, LookupError, TemplateError):19 """Raised if a template does not exist.
4 unmodified lines
24 """2526 # Silence the Python warning about message being deprecated since27 # it's not valid here.23 message = None28 message: t.Optional[str] = None2925 def __init__(self, name, message=None):30 def __init__(31 self,32 name: t.Optional[t.Union[str, "Undefined"]],33 message: t.Optional[str] = None,34 ) -> None:35 IOError.__init__(self, name)3637 if message is None:38 from .runtime import Undefined
6 unmodified lines
45 self.message = message46 self.name = name47 self.templates = [name]4840 def __str__(self):41 return self.message49 def __str__(self) -> str:50 return str(self.message)515253class TemplatesNotFound(TemplateNotFound):54 """Like :class:`TemplateNotFound` but raised if multiple templates
6 unmodified lines
6162 .. versionadded:: 2.263 """6456 def __init__(self, names=(), message=None):65 def __init__(66 self,67 names: t.Sequence[t.Union[str, "Undefined"]] = (),68 message: t.Optional[str] = None,69 ) -> None:70 if message is None:71 from .runtime import Undefined7273 parts = []
3 unmodified lines
77 parts.append(name._undefined_message)78 else:79 parts.append(name)8068 message = "none of the templates given were found: " + ", ".join(69 map(str, parts)70 )71 TemplateNotFound.__init__(self, names[-1] if names else None, message)81 parts_str = ", ".join(map(str, parts))82 message = f"none of the templates given were found: {parts_str}"8384 super().__init__(names[-1] if names else None, message)85 self.templates = list(names)868788class TemplateSyntaxError(TemplateError):89 """Raised to tell the user that there is a problem with the template."""9078 def __init__(self, message, lineno, name=None, filename=None):79 TemplateError.__init__(self, message)91 def __init__(92 self,93 message: str,94 lineno: int,95 name: t.Optional[str] = None,96 filename: t.Optional[str] = None,97 ) -> None:98 super().__init__(message)99 self.lineno = lineno100 self.name = name101 self.filename = filename83 self.source = None102 self.source: t.Optional[str] = None103104 # this is set to True if the debug.translate_syntax_error105 # function translated the syntax error into a new traceback106 self.translated = False10789 def __str__(self):108 def __str__(self) -> str:109 # for translated errors we only return the message110 if self.translated:92 return self.message111 return t.cast(str, self.message)112113 # otherwise attach some stuff114 location = f"line {self.lineno}"115 name = self.filename or self.name116 if name:117 location = f'File "{name}", {location}'99 lines = [self.message, " " + location]118 lines = [t.cast(str, self.message), " " + location]119120 # if the source is set, add the line to the output121 if self.source is not None:122 try:123 line = self.source.splitlines()[self.lineno - 1]124 except IndexError:106 line = None107 if line:125 pass126 else:127 lines.append(" " + line.strip())128129 return "\n".join(lines)130112 def __reduce__(self):131 def __reduce__(self): # type: ignore132 # https://bugs.python.org/issue1692335 Exceptions that take133 # multiple required arguments have problems with pickling.134 # Without this, raises TypeError: __init__() missing 1 required135 # positional argument: 'lineno'
31 unmodified lines
modified:src/jinja2/ext.py+251 added-139 removed
1"""Extension API for adding custom tags and behavior."""2import pprint3import re4import typing as t5import warnings5from sys import version_info6from typing import Set67from markupsafe import Markup89from . import defaults10from . import nodes11from .defaults import BLOCK_END_STRING12from .defaults import BLOCK_START_STRING13from .defaults import COMMENT_END_STRING14from .defaults import COMMENT_START_STRING15from .defaults import KEEP_TRAILING_NEWLINE16from .defaults import LINE_COMMENT_PREFIX17from .defaults import LINE_STATEMENT_PREFIX18from .defaults import LSTRIP_BLOCKS19from .defaults import NEWLINE_SEQUENCE20from .defaults import TRIM_BLOCKS21from .defaults import VARIABLE_END_STRING22from .defaults import VARIABLE_START_STRING11from .environment import Environment12from .exceptions import TemplateAssertionError13from .exceptions import TemplateSyntaxError26from .nodes import ContextReference27from .runtime import concat14from .runtime import concat # type: ignore15from .runtime import Context16from .runtime import Undefined17from .utils import import_string18from .utils import pass_context1931# I18N functions available in Jinja templates. If the I18N library32# provides ugettext, it will be assigned to gettext.33GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext", "pgettext", "npgettext")34_ws_re = re.compile(r"\s*\n\s*")20if t.TYPE_CHECKING:21 import typing_extensions as te22 from .lexer import Token23 from .lexer import TokenStream24 from .parser import Parser2526 class _TranslationsBasic(te.Protocol):27 def gettext(self, message: str) -> str:28 ...2937class ExtensionRegistry(type):38 """Gives the extension an unique identifier."""30 def ngettext(self, singular: str, plural: str, n: int) -> str:31 pass3240 def __new__(mcs, name, bases, d):41 rv = type.__new__(mcs, name, bases, d)42 rv.identifier = f"{rv.__module__}.{rv.__name__}"43 return rv33 class _TranslationsContext(_TranslationsBasic):34 def pgettext(self, context: str, message: str) -> str:35 ...3637 def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:38 ...3946class Extension(metaclass=ExtensionRegistry):40 _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]414243# I18N functions available in Jinja templates. If the I18N library44# provides ugettext, it will be assigned to gettext.45GETTEXT_FUNCTIONS: t.Tuple[str, ...] = (46 "_",47 "gettext",48 "ngettext",49 "pgettext",50 "npgettext",51)52_ws_re = re.compile(r"\s*\n\s*")535455class Extension:56 """Extensions can be used to add extra functionality to the Jinja template57 system at the parser level. Custom extensions are bound to an environment58 but may not store environment specific data on `self`. The reason for59 this is that an extension can be bound to another environment (for
10 unmodified lines
70 is a terrible name, ``fragment_cache_prefix`` on the other hand is a good71 name as includes the name of the extension (fragment cache).72 """7374 identifier: t.ClassVar[str]7576 def __init_subclass__(cls) -> None:77 cls.identifier = f"{cls.__module__}.{cls.__name__}"7879 #: if this extension parses this is the list of tags it's listening to.66 tags: Set[str] = set()80 tags: t.Set[str] = set()8182 #: the priority of that extension. This is especially useful for83 #: extensions that preprocess values. A lower value means higher84 #: priority.85 #:86 #: .. versionadded:: 2.487 priority = 1008875 def __init__(self, environment):89 def __init__(self, environment: Environment) -> None:90 self.environment = environment9178 def bind(self, environment):92 def bind(self, environment: Environment) -> "Extension":93 """Create a copy of this extension bound to another environment."""80 rv = object.__new__(self.__class__)94 rv = t.cast(Extension, object.__new__(self.__class__))95 rv.__dict__.update(self.__dict__)96 rv.environment = environment97 return rv9885 def preprocess(self, source, name, filename=None):99 def preprocess(100 self, source: str, name: t.Optional[str], filename: t.Optional[str] = None101 ) -> str:102 """This method is called before the actual lexing and can be used to103 preprocess the source. The `filename` is optional. The return value104 must be the preprocessed source.105 """106 return source10792 def filter_stream(self, stream):108 def filter_stream(109 self, stream: "TokenStream"110 ) -> t.Union["TokenStream", t.Iterable["Token"]]:111 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used112 to filter tokens returned. This method has to return an iterable of113 :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a114 :class:`~jinja2.lexer.TokenStream`.115 """116 return stream117100 def parse(self, parser):118 def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:119 """If any of the :attr:`tags` matched this method is called with the120 parser as first argument. The token the parser stream is pointing at121 is the name token that matched. This method has to return one or a122 list of multiple nodes.123 """124 raise NotImplementedError()125108 def attr(self, name, lineno=None):126 def attr(127 self, name: str, lineno: t.Optional[int] = None128 ) -> nodes.ExtensionAttribute:129 """Return an attribute node for the current extension. This is useful130 to pass constants on extensions to generated template code.131132 ::
2 unmodified lines
135 """136 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)137138 def call_method(119 self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None120 ):139 self,140 name: str,141 args: t.Optional[t.List[nodes.Expr]] = None,142 kwargs: t.Optional[t.List[nodes.Keyword]] = None,143 dyn_args: t.Optional[nodes.Expr] = None,144 dyn_kwargs: t.Optional[nodes.Expr] = None,145 lineno: t.Optional[int] = None,146 ) -> nodes.Call:147 """Call a method of the extension. This is a shortcut for148 :meth:`attr` + :class:`jinja2.nodes.Call`.149 """150 if args is None:
10 unmodified lines
161 )162163164@pass_context139def _gettext_alias(__context, *args, **kwargs):165def _gettext_alias(166 __context: Context, *args: t.Any, **kwargs: t.Any167) -> t.Union[t.Any, Undefined]:168 return __context.call(__context.resolve("gettext"), *args, **kwargs)169170143def _make_new_gettext(func):171def _make_new_gettext(func: t.Callable[[str], str]) -> t.Callable[..., str]:172 @pass_context145 def gettext(__context, __string, **variables):173 def gettext(__context: Context, __string: str, **variables: t.Any) -> str:174 rv = __context.call(func, __string)175 if __context.eval_ctx.autoescape:176 rv = Markup(rv)177 # Always treat as a format string, even if there are no178 # variables. This makes translation strings more consistent179 # and predictable. This requires escaping152 return rv % variables180 return rv % variables # type: ignore181182 return gettext183184157def _make_new_ngettext(func):185def _make_new_ngettext(func: t.Callable[[str, str, int], str]) -> t.Callable[..., str]:186 @pass_context159 def ngettext(__context, __singular, __plural, __num, **variables):187 def ngettext(188 __context: Context,189 __singular: str,190 __plural: str,191 __num: int,192 **variables: t.Any,193 ) -> str:194 variables.setdefault("num", __num)195 rv = __context.call(func, __singular, __plural, __num)196 if __context.eval_ctx.autoescape:197 rv = Markup(rv)198 # Always treat as a format string, see gettext comment above.165 return rv % variables199 return rv % variables # type: ignore200201 return ngettext202203170def _make_new_pgettext(func):204def _make_new_pgettext(func: t.Callable[[str, str], str]) -> t.Callable[..., str]:205 @pass_context172 def pgettext(__context, __string_ctx, __string, **variables):206 def pgettext(207 __context: Context, __string_ctx: str, __string: str, **variables: t.Any208 ) -> str:209 variables.setdefault("context", __string_ctx)210 rv = __context.call(func, __string_ctx, __string)211212 if __context.eval_ctx.autoescape:213 rv = Markup(rv)214215 # Always treat as a format string, see gettext comment above.180 return rv % variables216 return rv % variables # type: ignore217218 return pgettext219220185def _make_new_npgettext(func):221def _make_new_npgettext(222 func: t.Callable[[str, str, str, int], str]223) -> t.Callable[..., str]:224 @pass_context187 def npgettext(__context, __string_ctx, __singular, __plural, __num, **variables):225 def npgettext(226 __context: Context,227 __string_ctx: str,228 __singular: str,229 __plural: str,230 __num: int,231 **variables: t.Any,232 ) -> str:233 variables.setdefault("context", __string_ctx)234 variables.setdefault("num", __num)235 rv = __context.call(func, __string_ctx, __singular, __plural, __num)236237 if __context.eval_ctx.autoescape:238 rv = Markup(rv)239240 # Always treat as a format string, see gettext comment above.196 return rv % variables241 return rv % variables # type: ignore242243 return npgettext244245
8 unmodified lines
254 # %}{{ count }} fooss{% endtrans %}255 # something is called twice here. One time for the gettext value and256 # the other time for the n-parameter of the ngettext function.257213 def __init__(self, environment):214 Extension.__init__(self, environment)258 def __init__(self, environment: Environment) -> None:259 super().__init__(environment)260 environment.globals["_"] = _gettext_alias261 environment.extend(262 install_gettext_translations=self._install,263 install_null_translations=self._install_null,
2 unmodified lines
266 extract_translations=self._extract,267 newstyle_gettext=False,268 )269225 def _install(self, translations, newstyle=None):270 def _install(271 self, translations: "_SupportedTranslations", newstyle: t.Optional[bool] = None272 ) -> None:273 # ugettext and ungettext are preferred in case the I18N library274 # is providing compatibility with older Python versions.275 gettext = getattr(translations, "ugettext", None)276 if gettext is None:
7 unmodified lines
284 self._install_callables(285 gettext, ngettext, newstyle=newstyle, pgettext=pgettext, npgettext=npgettext286 )287241 def _install_null(self, newstyle=None):288 def _install_null(self, newstyle: t.Optional[bool] = None) -> None:289 import gettext290291 translations = gettext.NullTranslations()292293 if hasattr(translations, "pgettext"):294 # Python < 3.8295 pgettext = translations.pgettext # type: ignore296 else:297298 def pgettext(c: str, s: str) -> str:299 return s300301 if hasattr(translations, "npgettext"):302 npgettext = translations.npgettext # type: ignore303 else:304305 def npgettext(c: str, s: str, p: str, n: int) -> str:306 return s if n == 1 else p307308 self._install_callables(243 lambda s: s,244 lambda s, p, n: s if n == 1 else p,309 gettext=translations.gettext,310 ngettext=translations.ngettext,311 newstyle=newstyle,246 pgettext=lambda c, s: s,247 npgettext=lambda c, s, p, n: s if n == 1 else p,312 pgettext=pgettext,313 npgettext=npgettext,314 )315316 def _install_callables(251 self, gettext, ngettext, newstyle=None, pgettext=None, npgettext=None252 ):317 self,318 gettext: t.Callable[[str], str],319 ngettext: t.Callable[[str, str, int], str],320 newstyle: t.Optional[bool] = None,321 pgettext: t.Optional[t.Callable[[str, str], str]] = None,322 npgettext: t.Optional[t.Callable[[str, str, str, int], str]] = None,323 ) -> None:324 if newstyle is not None:254 self.environment.newstyle_gettext = newstyle255 if self.environment.newstyle_gettext:325 self.environment.newstyle_gettext = newstyle # type: ignore326 if self.environment.newstyle_gettext: # type: ignore327 gettext = _make_new_gettext(gettext)328 ngettext = _make_new_ngettext(ngettext)329330 if pgettext is not None:
5 unmodified lines
336 self.environment.globals.update(337 gettext=gettext, ngettext=ngettext, pgettext=pgettext, npgettext=npgettext338 )339269 def _uninstall(self, translations):340 def _uninstall(self, translations: "_SupportedTranslations") -> None:341 for key in ("gettext", "ngettext", "pgettext", "npgettext"):342 self.environment.globals.pop(key, None)343273 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):344 def _extract(345 self,346 source: t.Union[str, nodes.Template],347 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,348 ) -> t.Iterator[349 t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]350 ]:351 if isinstance(source, str):352 source = self.environment.parse(source)353 return extract_from_ast(source, gettext_functions)354278 def parse(self, parser):355 def parse(self, parser: "Parser") -> t.Union[nodes.Node, t.List[nodes.Node]]:356 """Parse a translatable tag."""357 lineno = next(parser.stream).lineno358 num_called_num = False359360 # find all the variables referenced. Additionally a variable can be361 # defined in the body of the trans block too, but this is checked at362 # a later state.286 plural_expr = None287 plural_expr_assignment = None288 variables = {}363 plural_expr: t.Optional[nodes.Expr] = None364 plural_expr_assignment: t.Optional[nodes.Assign] = None365 variables: t.Dict[str, nodes.Expr] = {}366 trimmed = None367 while parser.stream.current.type != "block_end":368 if variables:369 parser.stream.expect("comma")
1 unmodified line
371 # skip colon for python compatibility372 if parser.stream.skip_if("colon"):373 break374298 name = parser.stream.expect("name")299 if name.value in variables:375 token = parser.stream.expect("name")376 if token.value in variables:377 parser.fail(301 f"translatable variable {name.value!r} defined twice.",302 name.lineno,378 f"translatable variable {token.value!r} defined twice.",379 token.lineno,380 exc=TemplateAssertionError,381 )382383 # expressions384 if parser.stream.current.type == "assign":385 next(parser.stream)309 variables[name.value] = var = parser.parse_expression()310 elif trimmed is None and name.value in ("trimmed", "notrimmed"):311 trimmed = name.value == "trimmed"386 variables[token.value] = var = parser.parse_expression()387 elif trimmed is None and token.value in ("trimmed", "notrimmed"):388 trimmed = token.value == "trimmed"389 continue390 else:314 variables[name.value] = var = nodes.Name(name.value, "load")391 variables[token.value] = var = nodes.Name(token.value, "load")392393 if plural_expr is None:394 if isinstance(var, nodes.Call):395 plural_expr = nodes.Name("_trans", "load")319 variables[name.value] = plural_expr396 variables[token.value] = plural_expr397 plural_expr_assignment = nodes.Assign(398 nodes.Name("_trans", "store"), var399 )400 else:401 plural_expr = var325 num_called_num = name.value == "num"402 num_called_num = token.value == "num"403404 parser.stream.expect("block_end")405406 plural = None
12 unmodified lines
419 if parser.stream.current.test("name:pluralize"):420 have_plural = True421 next(parser.stream)422 if parser.stream.current.type != "block_end":346 name = parser.stream.expect("name")347 if name.value not in variables:423 token = parser.stream.expect("name")424 if token.value not in variables:425 parser.fail(349 f"unknown variable {name.value!r} for pluralization",350 name.lineno,426 f"unknown variable {token.value!r} for pluralization",427 token.lineno,428 exc=TemplateAssertionError,429 )353 plural_expr = variables[name.value]354 num_called_num = name.value == "num"430 plural_expr = variables[token.value]431 num_called_num = token.value == "num"432 parser.stream.expect("block_end")433 plural_names, plural = self._parse_block(parser, False)434 next(parser.stream)435 referenced.update(plural_names)436 else:437 next(parser.stream)438439 # register free names as simple name expressions363 for var in referenced:364 if var not in variables:365 variables[var] = nodes.Name(var, "load")440 for name in referenced:441 if name not in variables:442 variables[name] = nodes.Name(name, "load")443444 if not have_plural:445 plural_expr = None446 elif plural_expr is None:
19 unmodified lines
466 return [plural_expr_assignment, node]467 else:468 return node469393 def _trim_whitespace(self, string, _ws_re=_ws_re):470 def _trim_whitespace(self, string: str, _ws_re: t.Pattern[str] = _ws_re) -> str:471 return _ws_re.sub(" ", string.strip())472396 def _parse_block(self, parser, allow_pluralize):473 def _parse_block(474 self, parser: "Parser", allow_pluralize: bool475 ) -> t.Tuple[t.List[str], str]:476 """Parse until the next block tag with a given name."""477 referenced = []478 buf = []479400 while 1:480 while True:481 if parser.stream.current.type == "data":482 buf.append(parser.stream.current.value.replace("%", "%%"))483 next(parser.stream)484 elif parser.stream.current.type == "variable_begin":
22 unmodified lines
507508 return referenced, concat(buf)509510 def _make_node(431 self, singular, plural, variables, plural_expr, vars_referenced, num_called_num432 ):511 self,512 singular: str,513 plural: t.Optional[str],514 variables: t.Dict[str, nodes.Expr],515 plural_expr: t.Optional[nodes.Expr],516 vars_referenced: bool,517 num_called_num: bool,518 ) -> nodes.Output:519 """Generates a useful node from the data provided."""520 newstyle = self.environment.newstyle_gettext # type: ignore521 node: nodes.Expr522523 # no variables referenced? no need to escape for old style524 # gettext invocations only if there are vars.436 if not vars_referenced and not self.environment.newstyle_gettext:525 if not vars_referenced and not newstyle:526 singular = singular.replace("%%", "%")527 if plural:528 plural = plural.replace("%%", "%")529
15 unmodified lines
545546 # in case newstyle gettext is used, the method is powerful547 # enough to handle the variable expansion and autoescape548 # handling itself460 if self.environment.newstyle_gettext:549 if newstyle:550 for key, value in variables.items():551 # the function adds that later anyways in case num was552 # called num, so just skip it.553 if num_called_num and key == "num":
24 unmodified lines
578 """579580 tags = {"do"}581493 def parse(self, parser):582 def parse(self, parser: "Parser") -> nodes.ExprStmt:583 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)584 node.node = parser.parse_tuple()585 return node586
2 unmodified lines
589 """Adds break and continue to the template engine."""590591 tags = {"break", "continue"}592504 def parse(self, parser):593 def parse(self, parser: "Parser") -> t.Union[nodes.Break, nodes.Continue]:594 token = next(parser.stream)595 if token.value == "break":596 return nodes.Break(lineno=token.lineno)597 return nodes.Continue(lineno=token.lineno)598599600class WithExtension(Extension):512 def __init__(self, environment):601 def __init__(self, environment: Environment) -> None:602 super().__init__(environment)603 warnings.warn(604 "The 'with' extension is deprecated and will be removed in"605 " Jinja 3.1. This is built in now.",
2 unmodified lines
608 )609610611class AutoEscapeExtension(Extension):523 def __init__(self, environment):612 def __init__(self, environment: Environment) -> None:613 super().__init__(environment)614 warnings.warn(615 "The 'autoescape' extension is deprecated and will be"616 " removed in Jinja 3.1. This is built in now.",
24 unmodified lines
641 """642643 tags = {"debug"}644556 def parse(self, parser):645 def parse(self, parser: "Parser") -> nodes.Output:646 lineno = parser.stream.expect("name:debug").lineno558 context = ContextReference()647 context = nodes.ContextReference()648 result = self.call_method("_render", [context], lineno=lineno)649 return nodes.Output([result], lineno=lineno)650562 def _render(self, context):651 def _render(self, context: Context) -> str:652 result = {653 "context": context.get_all(),654 "filters": sorted(self.environment.filters.keys()),655 "tests": sorted(self.environment.tests.keys()),656 }657658 # Set the depth since the intent is to show the top few names.570 if version_info[:2] >= (3, 4):571 return pprint.pformat(result, depth=3, compact=True)659 return pprint.pformat(result, depth=3, compact=True)572 else:573 return pprint.pformat(result, depth=3)660661576def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True):662def extract_from_ast(663 ast: nodes.Template,664 gettext_functions: t.Sequence[str] = GETTEXT_FUNCTIONS,665 babel_style: bool = True,666) -> t.Iterator[667 t.Tuple[int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]]668]:669 """Extract localizable strings from the given template node. Per670 default this function returns matches in babel style that means non string671 parameters as well as keyword arguments are returned as `None`. This672 allows Babel to figure out what you really meant if you are using
26 unmodified lines
699 This extraction function operates on the AST and is because of that unable700 to extract any comments. For comment support you have to use the babel701 extraction interface or extract comments yourself.702 """703 out: t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]]704611 for node in node.find_all(nodes.Call):705 for node in ast.find_all(nodes.Call):706 if (707 not isinstance(node.node, nodes.Name)708 or node.node.name not in gettext_functions709 ):710 continue711618 strings = []712 strings: t.List[t.Optional[str]] = []713714 for arg in node.args:715 if isinstance(arg, nodes.Const) and isinstance(arg.value, str):716 strings.append(arg.value)717 else:
6 unmodified lines
724 if node.dyn_kwargs is not None:725 strings.append(None)726727 if not babel_style:633 strings = tuple(x for x in strings if x is not None)634 if not strings:728 out = tuple(x for x in strings if x is not None)729730 if not out:731 continue732 else:733 if len(strings) == 1:638 strings = strings[0]734 out = strings[0]735 else:640 strings = tuple(strings)641 yield node.lineno, node.node.name, strings736 out = tuple(strings)737738 yield node.lineno, node.node.name, out739740741class _CommentFinder:742 """Helper class to find comments in a token stream. Can only743 find comments for gettext calls forwards. Once the comment744 from line 4 is found, a comment for line 1 will not return a745 usable value.746 """747651 def __init__(self, tokens, comment_tags):748 def __init__(749 self, tokens: t.Sequence[t.Tuple[int, str, str]], comment_tags: t.Sequence[str]750 ) -> None:751 self.tokens = tokens752 self.comment_tags = comment_tags753 self.offset = 0754 self.last_lineno = 0755657 def find_backwards(self, offset):756 def find_backwards(self, offset: int) -> t.List[str]:757 try:758 for _, token_type, token_value in reversed(759 self.tokens[self.offset : offset]760 ):
7 unmodified lines
768 return []769 finally:770 self.offset = offset771673 def find_comments(self, lineno):772 def find_comments(self, lineno: int) -> t.List[str]:773 if not self.comment_tags or self.last_lineno > lineno:774 return []775 for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):776 if token_lineno > lineno:777 return self.find_backwards(self.offset + idx)778 return self.find_backwards(len(self.tokens))779780682def babel_extract(fileobj, keywords, comment_tags, options):781def babel_extract(782 fileobj: t.BinaryIO,783 keywords: t.Sequence[str],784 comment_tags: t.Sequence[str],785 options: t.Dict[str, t.Any],786) -> t.Iterator[787 t.Tuple[788 int, str, t.Union[t.Optional[str], t.Tuple[t.Optional[str], ...]], t.List[str]789 ]790]:791 """Babel extraction method for Jinja templates.792793 .. versionchanged:: 2.3794 Basic support for translation comments was added. If `comment_tags`
19 unmodified lines
814 :param options: a dictionary of additional options (optional)815 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.816 (comments will be empty currently)817 """710 extensions = set()711 for extension in options.get("extensions", "").split(","):712 extension = extension.strip()713 if not extension:818 extensions: t.Dict[t.Type[Extension], None] = {}819820 for extension_name in options.get("extensions", "").split(","):821 extension_name = extension_name.strip()822823 if not extension_name:824 continue715 extensions.add(import_string(extension))825826 extensions[import_string(extension_name)] = None827828 if InternationalizationExtension not in extensions:717 extensions.add(InternationalizationExtension)829 extensions[InternationalizationExtension] = None830719 def getbool(options, key, default=False):720 return options.get(key, str(default)).lower() in ("1", "on", "yes", "true")831 def getbool(options: t.Mapping[str, str], key: str, default: bool = False) -> bool:832 return options.get(key, str(default)).lower() in {"1", "on", "yes", "true"}833834 silent = getbool(options, "silent", True)835 environment = Environment(724 options.get("block_start_string", BLOCK_START_STRING),725 options.get("block_end_string", BLOCK_END_STRING),726 options.get("variable_start_string", VARIABLE_START_STRING),727 options.get("variable_end_string", VARIABLE_END_STRING),728 options.get("comment_start_string", COMMENT_START_STRING),729 options.get("comment_end_string", COMMENT_END_STRING),730 options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,731 options.get("line_comment_prefix") or LINE_COMMENT_PREFIX,732 getbool(options, "trim_blocks", TRIM_BLOCKS),733 getbool(options, "lstrip_blocks", LSTRIP_BLOCKS),734 NEWLINE_SEQUENCE,735 getbool(options, "keep_trailing_newline", KEEP_TRAILING_NEWLINE),736 frozenset(extensions),836 options.get("block_start_string", defaults.BLOCK_START_STRING),837 options.get("block_end_string", defaults.BLOCK_END_STRING),838 options.get("variable_start_string", defaults.VARIABLE_START_STRING),839 options.get("variable_end_string", defaults.VARIABLE_END_STRING),840 options.get("comment_start_string", defaults.COMMENT_START_STRING),841 options.get("comment_end_string", defaults.COMMENT_END_STRING),842 options.get("line_statement_prefix") or defaults.LINE_STATEMENT_PREFIX,843 options.get("line_comment_prefix") or defaults.LINE_COMMENT_PREFIX,844 getbool(options, "trim_blocks", defaults.TRIM_BLOCKS),845 getbool(options, "lstrip_blocks", defaults.LSTRIP_BLOCKS),846 defaults.NEWLINE_SEQUENCE,847 getbool(options, "keep_trailing_newline", defaults.KEEP_TRAILING_NEWLINE),848 tuple(extensions),849 cache_size=0,850 auto_reload=False,851 )852853 if getbool(options, "trimmed"):854 environment.policies["ext.i18n.trimmed"] = True855 if getbool(options, "newstyle_gettext"):744 environment.newstyle_gettext = True856 environment.newstyle_gettext = True # type: ignore857858 source = fileobj.read().decode(options.get("encoding", "utf-8"))859 try:860 node = environment.parse(source)
19 unmodified lines
modified:src/jinja2/filters.py+51 added-42 removed
32 unmodified lines
33 from .nodes import EvalContext34 from .runtime import Context35 from .sandbox import SandboxedEnvironment # noqa: F4013637 K = t.TypeVar("K")38 V = t.TypeVar("V")3937 class HasHTML(te.Protocol):38 def __html__(self) -> str:39 pass404142F = t.TypeVar("F", bound=t.Callable[..., t.Any])43K = t.TypeVar("K")44V = t.TypeVar("V")454645def contextfilter(f):47def contextfilter(f: F) -> F:48 """Pass the context as the first argument to the decorated function.4950 .. deprecated:: 3.051 Will be removed in Jinja 3.1. Use :func:`~jinja2.pass_context`
7 unmodified lines
59 )60 return pass_context(f)616261def evalcontextfilter(f):63def evalcontextfilter(f: F) -> F:64 """Pass the eval context as the first argument to the decorated65 function.6667 .. deprecated:: 3.0
10 unmodified lines
78 )79 return pass_eval_context(f)808180def environmentfilter(f):82def environmentfilter(f: F) -> F:83 """Pass the environment as the first argument to the decorated84 function.8586 .. deprecated:: 3.0
8 unmodified lines
95 )96 return pass_environment(f)979897def ignore_case(value: "V") -> "V":99def ignore_case(value: V) -> V:100 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings101 to lowercase and returns other types as-is."""102 if isinstance(value, str):101 return t.cast("V", value.lower())103 return t.cast(V, value.lower())104105 return value106107
227 unmodified lines
335 )336337338def do_dictsort(337 value: "t.Mapping[K, V]",339 value: t.Mapping[K, V],340 case_sensitive: bool = False,341 by: 'te.Literal["key", "value"]' = "key",342 reverse: bool = False,341) -> "t.List[t.Tuple[K, V]]":343) -> t.List[t.Tuple[K, V]]:344 """Sort a dict and yield (key, value) pairs. Python dicts may not345 be in the order you want to display them in, so sort them first.346347 .. sourcecode:: jinja
16 unmodified lines
364 pos = 1365 else:366 raise FilterArgumentError('You can only sort by either "key" or "value"')367366 def sort_func(item):368 def sort_func(item: t.Tuple[t.Any, t.Any]) -> t.Any:369 value = item[pos]370371 if not case_sensitive:372 value = ignore_case(value)
152 unmodified lines
525 return _min_or_max(environment, value, max, case_sensitive, attribute)526527528def do_default(527 value: "V",528 default_value: "V" = "", # type: ignore529 value: V,530 default_value: V = "", # type: ignore531 boolean: bool = False,530) -> "V":532) -> V:533 """If the value is undefined it will return the passed default value,534 otherwise the value of the variable:535536 .. sourcecode:: jinja
78 unmodified lines
615 # no html involved, to normal joining616 return soft_str(d).join(map(soft_str, value))617618617@async_variant(sync_do_join)619@async_variant(sync_do_join) # type: ignore620async def do_join(621 eval_ctx: "EvalContext",622 value: t.Union[t.AsyncIterable, t.Iterable],623 d: str = "",
17 unmodified lines
641 except StopIteration:642 return environment.undefined("No first item, sequence was empty.")643644643@async_variant(sync_do_first)645@async_variant(sync_do_first) # type: ignore646async def do_first(647 environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"648) -> "t.Union[V, Undefined]":649 try:648 return t.cast("V", await auto_aiter(seq).__anext__())650 return await auto_aiter(seq).__anext__()651 except StopAsyncIteration:652 return environment.undefined("No first item, sequence was empty.")653654
62 unmodified lines
717718719def do_pprint(value: t.Any) -> str:720 """Pretty print a variable. Useful for debugging."""719 return t.cast(str, pformat(value))721 return pformat(value)722723724_uri_scheme_re = re.compile(r"^([\w.+-]{2,}:(/){0,2})$")725
354 unmodified lines
10801081 yield tmp108210831082@async_variant(sync_do_slice)1084@async_variant(sync_do_slice) # type: ignore1085async def do_slice(1086 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1087 slices: int,1088 fill_with: t.Optional[t.Any] = None,
83 unmodified lines
1172 list: t.List11731174 # Use the regular tuple repr to hide this subclass if users print1175 # out the value during debugging.1174 def __repr__(self):1176 def __repr__(self) -> str:1177 return tuple.__repr__(self)11781177 def __str__(self):1179 def __str__(self) -> str:1180 return tuple.__str__(self)118111821183@pass_environment
54 unmodified lines
1238 for key, values in groupby(sorted(value, key=expr), expr)1239 ]124012411240@async_variant(sync_do_groupby)1242@async_variant(sync_do_groupby) # type: ignore1243async def do_groupby(1244 environment: "Environment",1245 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1246 attribute: t.Union[str, int],
10 unmodified lines
1257def sync_do_sum(1258 environment: "Environment",1259 iterable: "t.Iterable[V]",1260 attribute: t.Optional[t.Union[str, int]] = None,1259 start: "V" = 0, # type: ignore1260) -> "V":1261 start: V = 0, # type: ignore1262) -> V:1263 """Returns the sum of a sequence of numbers plus the value of parameter1264 'start' (which defaults to 0). When the sequence is empty it returns1265 start.1266
12 unmodified lines
12791280 return sum(iterable, start)128112821281@async_variant(sync_do_sum)1283@async_variant(sync_do_sum) # type: ignore1284async def do_sum(1285 environment: "Environment",1286 iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1287 attribute: t.Optional[t.Union[str, int]] = None,1286 start: "V" = 0, # type: ignore1287) -> "V":1288 start: V = 0, # type: ignore1289) -> V:1290 rv = start12911292 if attribute is not None:1293 func = make_attrgetter(environment, attribute)1294 else:12951294 def func(x):1296 def func(x: V) -> V:1297 return x12981299 async for item in auto_aiter(iterable):1300 rv += func(item)
7 unmodified lines
1308 """1309 return list(value)131013111310@async_variant(sync_do_list)1312@async_variant(sync_do_list) # type: ignore1313async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":1314 return await auto_to_list(value)13151316
18 unmodified lines
1335def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1336 ...133713381337def do_reverse(value):1339def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:1340 """Reverse the object or return an iterator that iterates over it the other1341 way round.1342 """1343 if isinstance(value, str):1344 return value[::-1]13451346 try:1345 return reversed(value)1347 return reversed(value) # type: ignore1348 except TypeError:1349 try:1350 rv = list(value)1351 rv.reverse()
51 unmodified lines
1403 ...140414051406@pass_context1405def sync_do_map(context, value, *args, **kwargs):1407def sync_do_map(1408 context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any1409) -> t.Iterable:1410 """Applies a filter on a sequence of objects or looks up an attribute.1411 This is useful when dealing with lists of objects but you are really1412 only interested in a certain value of it.1413
60 unmodified lines
1474) -> t.Iterable:1475 ...147614771474@async_variant(sync_do_map)1475async def do_map(context, value, *args, **kwargs):1478@async_variant(sync_do_map) # type: ignore1479async def do_map(1480 context: "Context",1481 value: t.Union[t.AsyncIterable, t.Iterable],1482 *args: t.Any,1483 **kwargs: t.Any,1484) -> t.AsyncIterable:1485 if value:1486 func = prepare_map(context, args, kwargs)14871488 async for item in auto_aiter(value):
30 unmodified lines
1519 """1520 return select_or_reject(context, value, args, kwargs, lambda x: x, False)152115221514@async_variant(sync_do_select)1523@async_variant(sync_do_select) # type: ignore1524async def do_select(1525 context: "Context",1526 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1527 *args: t.Any,
27 unmodified lines
1555 """1556 return select_or_reject(context, value, args, kwargs, lambda x: not x, False)155715581550@async_variant(sync_do_reject)1559@async_variant(sync_do_reject) # type: ignore1560async def do_reject(1561 context: "Context",1562 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1563 *args: t.Any,
31 unmodified lines
1595 """1596 return select_or_reject(context, value, args, kwargs, lambda x: x, True)159715981590@async_variant(sync_do_selectattr)1599@async_variant(sync_do_selectattr) # type: ignore1600async def do_selectattr(1601 context: "Context",1602 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1603 *args: t.Any,
29 unmodified lines
1633 """1634 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)163516361628@async_variant(sync_do_rejectattr)1637@async_variant(sync_do_rejectattr) # type: ignore1638async def do_rejectattr(1639 context: "Context",1640 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1641 *args: t.Any,
50 unmodified lines
1692 args = args[1:]1693 except LookupError:1694 raise FilterArgumentError("map requires a filter argument")16951687 def func(item):1696 def func(item: t.Any) -> t.Any:1697 return context.environment.call_filter(1698 name, item, args, kwargs, context=context1699 )1700
17 unmodified lines
1718 off = 11719 else:1720 off = 017211713 def transfunc(x):1722 def transfunc(x: V) -> V:1723 return x17241725 try:1726 name = args[off]1727 args = args[1 + off :]17281720 def func(item):1729 def func(item: t.Any) -> t.Any:1730 return context.environment.call_test(name, item, args, kwargs)17311732 except LookupError:1724 func = bool1733 func = bool # type: ignore17341735 return lambda item: modfunc(func(transfunc(item)))17361737
87 unmodified lines
modified:src/jinja2/idtracking.py+96 added-67 removed
1import typing as t23from . import nodes4from .visitor import NodeVisitor56VAR_LOAD_PARAMETER = "param"7VAR_LOAD_RESOLVE = "resolve"8VAR_LOAD_ALIAS = "alias"9VAR_LOAD_UNDEFINED = "undefined"10119def find_symbols(nodes, parent_symbols=None):12def find_symbols(13 nodes: t.Iterable[nodes.Node], parent_symbols: t.Optional["Symbols"] = None14) -> "Symbols":15 sym = Symbols(parent=parent_symbols)16 visitor = FrameSymbolVisitor(sym)17 for node in nodes:18 visitor.visit(node)19 return sym202117def symbols_for_node(node, parent_symbols=None):22def symbols_for_node(23 node: nodes.Node, parent_symbols: t.Optional["Symbols"] = None24) -> "Symbols":25 sym = Symbols(parent=parent_symbols)26 sym.analyze_node(node)27 return sym282930class Symbols:24 def __init__(self, parent=None, level=None):31 def __init__(32 self, parent: t.Optional["Symbols"] = None, level: t.Optional[int] = None33 ) -> None:34 if level is None:35 if parent is None:36 level = 037 else:38 level = parent.level + 13930 self.level = level40 self.level: int = level41 self.parent = parent32 self.refs = {}33 self.loads = {}34 self.stores = set()42 self.refs: t.Dict[str, str] = {}43 self.loads: t.Dict[str, t.Any] = {}44 self.stores: t.Set[str] = set()4536 def analyze_node(self, node, **kwargs):46 def analyze_node(self, node: nodes.Node, **kwargs: t.Any) -> None:47 visitor = RootVisitor(self)48 visitor.visit(node, **kwargs)4940 def _define_ref(self, name, load=None):50 def _define_ref(51 self, name: str, load: t.Optional[t.Tuple[str, t.Optional[str]]] = None52 ) -> str:53 ident = f"l_{self.level}_{name}"54 self.refs[name] = ident55 if load is not None:56 self.loads[ident] = load57 return ident5847 def find_load(self, target):59 def find_load(self, target: str) -> t.Optional[t.Any]:60 if target in self.loads:61 return self.loads[target]6263 if self.parent is not None:64 return self.parent.find_load(target)6553 def find_ref(self, name):66 return None6768 def find_ref(self, name: str) -> t.Optional[str]:69 if name in self.refs:70 return self.refs[name]7172 if self.parent is not None:73 return self.parent.find_ref(name)7475 return None7659 def ref(self, name):77 def ref(self, name: str) -> str:78 rv = self.find_ref(name)79 if rv is None:80 raise AssertionError(81 "Tried to resolve a name to a reference that was"82 f" unknown to the frame ({name!r})"83 )84 return rv8568 def copy(self):69 rv = object.__new__(self.__class__)86 def copy(self) -> "Symbols":87 rv = t.cast(Symbols, object.__new__(self.__class__))88 rv.__dict__.update(self.__dict__)89 rv.refs = self.refs.copy()90 rv.loads = self.loads.copy()91 rv.stores = self.stores.copy()92 return rv9376 def store(self, name):94 def store(self, name: str) -> None:95 self.stores.add(name)9697 # If we have not see the name referenced yet, we need to figure98 # out what to set it to.
9 unmodified lines
108109 # Otherwise we can just set it to undefined.110 self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))11194 def declare_parameter(self, name):112 def declare_parameter(self, name: str) -> str:113 self.stores.add(name)114 return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))11598 def load(self, name):99 target = self.find_ref(name)100 if target is None:116 def load(self, name: str) -> None:117 if self.find_ref(name) is None:118 self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))119103 def branch_update(self, branch_symbols):104 stores = {}120 def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:121 stores: t.Dict[str, int] = {}122 for branch in branch_symbols:123 for target in branch.stores:124 if target in self.stores:125 continue
6 unmodified lines
132133 for name, branch_count in stores.items():134 if branch_count == len(branch_symbols):135 continue136119 target = self.find_ref(name)137 target = self.find_ref(name) # type: ignore138 assert target is not None, "should not happen"139140 if self.parent is not None:141 outer_target = self.parent.find_ref(name)
1 unmodified line
143 self.loads[target] = (VAR_LOAD_ALIAS, outer_target)144 continue145 self.loads[target] = (VAR_LOAD_RESOLVE, name)146129 def dump_stores(self):130 rv = {}131 node = self147 def dump_stores(self) -> t.Dict[str, str]:148 rv: t.Dict[str, str] = {}149 node: t.Optional["Symbols"] = self150151 while node is not None:152 for name in node.stores:153 if name not in rv:135 rv[name] = self.find_ref(name)154 rv[name] = self.find_ref(name) # type: ignore155156 node = node.parent157158 return rv159139 def dump_param_targets(self):160 def dump_param_targets(self) -> t.Set[str]:161 rv = set()141 node = self162 node: t.Optional["Symbols"] = self163164 while node is not None:165 for target, (instr, _) in self.loads.items():166 if instr == VAR_LOAD_PARAMETER:167 rv.add(target)168169 node = node.parent170171 return rv172173174class RootVisitor(NodeVisitor):151 def __init__(self, symbols):175 def __init__(self, symbols: "Symbols") -> None:176 self.sym_visitor = FrameSymbolVisitor(symbols)177154 def _simple_visit(self, node, **kwargs):178 def _simple_visit(self, node: nodes.Node, **kwargs: t.Any) -> None:179 for child in node.iter_child_nodes():180 self.sym_visitor.visit(child)181158 visit_Template = (159 visit_Block160 ) = (161 visit_Macro162 ) = (163 visit_FilterBlock164 ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit182 visit_Template = _simple_visit183 visit_Block = _simple_visit184 visit_Macro = _simple_visit185 visit_FilterBlock = _simple_visit186 visit_Scope = _simple_visit187 visit_If = _simple_visit188 visit_ScopedEvalContextModifier = _simple_visit189166 def visit_AssignBlock(self, node, **kwargs):190 def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:191 for child in node.body:192 self.sym_visitor.visit(child)193170 def visit_CallBlock(self, node, **kwargs):194 def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:195 for child in node.iter_child_nodes(exclude=("call",)):196 self.sym_visitor.visit(child)197174 def visit_OverlayScope(self, node, **kwargs):198 def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:199 for child in node.body:200 self.sym_visitor.visit(child)201178 def visit_For(self, node, for_branch="body", **kwargs):202 def visit_For(203 self, node: nodes.For, for_branch: str = "body", **kwargs: t.Any204 ) -> None:205 if for_branch == "body":206 self.sym_visitor.visit(node.target, store_as_param=True)207 branch = node.body208 elif for_branch == "else":
4 unmodified lines
213 self.sym_visitor.visit(node.test)214 return215 else:216 raise RuntimeError("Unknown for branch")191 for item in branch or ():192 self.sym_visitor.visit(item)217194 def visit_With(self, node, **kwargs):218 if branch:219 for item in branch:220 self.sym_visitor.visit(item)221222 def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:223 for target in node.targets:224 self.sym_visitor.visit(target)225 for child in node.body:226 self.sym_visitor.visit(child)227200 def generic_visit(self, node, *args, **kwargs):201 raise NotImplementedError(202 f"Cannot find symbols for {node.__class__.__name__!r}"203 )228 def generic_visit(self, node: nodes.Node, *args: t.Any, **kwargs: t.Any) -> None:229 raise NotImplementedError(f"Cannot find symbols for {type(node).__name__!r}")230231232class FrameSymbolVisitor(NodeVisitor):233 """A visitor for `Frame.inspect`."""234209 def __init__(self, symbols):235 def __init__(self, symbols: "Symbols") -> None:236 self.symbols = symbols237212 def visit_Name(self, node, store_as_param=False, **kwargs):238 def visit_Name(239 self, node: nodes.Name, store_as_param: bool = False, **kwargs: t.Any240 ) -> None:241 """All assignments to names go through this function."""242 if store_as_param or node.ctx == "param":243 self.symbols.declare_parameter(node.name)244 elif node.ctx == "store":245 self.symbols.store(node.name)246 elif node.ctx == "load":247 self.symbols.load(node.name)248221 def visit_NSRef(self, node, **kwargs):249 def visit_NSRef(self, node: nodes.NSRef, **kwargs: t.Any) -> None:250 self.symbols.load(node.name)251224 def visit_If(self, node, **kwargs):252 def visit_If(self, node: nodes.If, **kwargs: t.Any) -> None:253 self.visit(node.test, **kwargs)226254 original_symbols = self.symbols255229 def inner_visit(nodes):256 def inner_visit(nodes: t.Iterable[nodes.Node]) -> "Symbols":257 self.symbols = rv = original_symbols.copy()258259 for subnode in nodes:260 self.visit(subnode, **kwargs)261262 self.symbols = original_symbols263 return rv264265 body_symbols = inner_visit(node.body)266 elif_symbols = inner_visit(node.elif_)267 else_symbols = inner_visit(node.else_ or ())239268 self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])269242 def visit_Macro(self, node, **kwargs):270 def visit_Macro(self, node: nodes.Macro, **kwargs: t.Any) -> None:271 self.symbols.store(node.name)272245 def visit_Import(self, node, **kwargs):273 def visit_Import(self, node: nodes.Import, **kwargs: t.Any) -> None:274 self.generic_visit(node, **kwargs)275 self.symbols.store(node.target)276249 def visit_FromImport(self, node, **kwargs):277 def visit_FromImport(self, node: nodes.FromImport, **kwargs: t.Any) -> None:278 self.generic_visit(node, **kwargs)279280 for name in node.names:281 if isinstance(name, tuple):282 self.symbols.store(name[1])283 else:284 self.symbols.store(name)285257 def visit_Assign(self, node, **kwargs):286 def visit_Assign(self, node: nodes.Assign, **kwargs: t.Any) -> None:287 """Visit assignments in the correct order."""288 self.visit(node.node, **kwargs)289 self.visit(node.target, **kwargs)290262 def visit_For(self, node, **kwargs):291 def visit_For(self, node: nodes.For, **kwargs: t.Any) -> None:292 """Visiting stops at for blocks. However the block sequence293 is visited as part of the outer scope.294 """295 self.visit(node.iter, **kwargs)296268 def visit_CallBlock(self, node, **kwargs):297 def visit_CallBlock(self, node: nodes.CallBlock, **kwargs: t.Any) -> None:298 self.visit(node.call, **kwargs)299271 def visit_FilterBlock(self, node, **kwargs):300 def visit_FilterBlock(self, node: nodes.FilterBlock, **kwargs: t.Any) -> None:301 self.visit(node.filter, **kwargs)302274 def visit_With(self, node, **kwargs):303 def visit_With(self, node: nodes.With, **kwargs: t.Any) -> None:304 for target in node.values:305 self.visit(target)306278 def visit_AssignBlock(self, node, **kwargs):307 def visit_AssignBlock(self, node: nodes.AssignBlock, **kwargs: t.Any) -> None:308 """Stop visiting at block assigns."""309 self.visit(node.target, **kwargs)310282 def visit_Scope(self, node, **kwargs):311 def visit_Scope(self, node: nodes.Scope, **kwargs: t.Any) -> None:312 """Stop visiting at scopes."""313285 def visit_Block(self, node, **kwargs):314 def visit_Block(self, node: nodes.Block, **kwargs: t.Any) -> None:315 """Stop visiting at blocks."""316288 def visit_OverlayScope(self, node, **kwargs):317 def visit_OverlayScope(self, node: nodes.OverlayScope, **kwargs: t.Any) -> None:318 """Do not visit into overlay scopes."""
modified:src/jinja2/lexer.py+149 added-102 removed
2 unmodified lines
3the bitshift operators we don't allow in templates. It separates4template code and python code in expressions.5"""6import re7import typing as t8from ast import literal_eval9from collections import deque9from operator import itemgetter10from sys import intern1112from ._identifier import pattern as name_re13from .exceptions import TemplateSyntaxError14from .utils import LRUCache1516if t.TYPE_CHECKING:17 from .environment import Environment1819# cache for the lexers. Exists in order to be able to have multiple20# environments with the same lexer18_lexer_cache = LRUCache(50)21_lexer_cache: t.MutableMapping[t.Tuple, "Lexer"] = LRUCache(50) # type: ignore2223# static regular expressions24whitespace_re = re.compile(r"\s+")25newline_re = re.compile(r"(\r\n|\r|\n)")
132 unmodified lines
158 [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]159)160161159def _describe_token_type(token_type):162def _describe_token_type(token_type: str) -> str:163 if token_type in reverse_operators:164 return reverse_operators[token_type]165166 return {167 TOKEN_COMMENT_BEGIN: "begin of comment",168 TOKEN_COMMENT_END: "end of comment",169 TOKEN_COMMENT: "comment",
8 unmodified lines
178 TOKEN_EOF: "end of template",179 }.get(token_type, token_type)180181178def describe_token(token):182def describe_token(token: "Token") -> str:183 """Returns a description of the token."""184 if token.type == TOKEN_NAME:185 return token.value186187 return _describe_token_type(token.type)188189185def describe_token_expr(expr):190def describe_token_expr(expr: str) -> str:191 """Like `describe_token` but for token expressions."""192 if ":" in expr:193 type, value = expr.split(":", 1)194195 if type == TOKEN_NAME:196 return value197 else:198 type = expr199200 return _describe_token_type(type)201202196def count_newlines(value):203def count_newlines(value: str) -> int:204 """Count the number of newline characters in the string. This is205 useful for extensions that filter a stream.206 """207 return len(newline_re.findall(value))208209203def compile_rules(environment):210def compile_rules(environment: "Environment") -> t.List[t.Tuple[str, str]]:211 """Compiles all the rules from the environment into a list of rules."""212 e = re.escape213 rules = [214 (
37 unmodified lines
252 """Class that raises a `TemplateSyntaxError` if called.253 Used by the `Lexer` to specify known errors.254 """255249 def __init__(self, message, cls=TemplateSyntaxError):256 def __init__(257 self, message: str, cls: t.Type[TemplateSyntaxError] = TemplateSyntaxError258 ) -> None:259 self.message = message260 self.error_class = cls261253 def __call__(self, lineno, filename):262 def __call__(self, lineno: int, filename: str) -> t.NoReturn:263 raise self.error_class(self.message, lineno, filename)264265257class Token(tuple):258 """Token class."""266class Token(t.NamedTuple):267 lineno: int268 type: str269 value: str270260 __slots__ = ()261 lineno, type, value = (property(itemgetter(x)) for x in range(3))271 def __str__(self) -> str:272 return describe_token(self)273263 def __new__(cls, lineno, type, value):264 return tuple.__new__(cls, (lineno, intern(str(type)), value))265266 def __str__(self):267 if self.type in reverse_operators:268 return reverse_operators[self.type]269 elif self.type == "name":270 return self.value271 return self.type272273 def test(self, expr):274 def test(self, expr: str) -> bool:275 """Test a token against a token expression. This can either be a276 token type or ``'token_type:token_value'``. This can only test277 against string values and types.278 """279 # here we do a regular string equality check as test_any is usually280 # passed an iterable of not interned strings.281 if self.type == expr:282 return True283282 elif ":" in expr:284 if ":" in expr:285 return expr.split(":", 1) == [self.type, self.value]286287 return False288286 def test_any(self, *iterable):289 def test_any(self, *iterable: str) -> bool:290 """Test against multiple token expressions."""288 for expr in iterable:289 if self.test(expr):290 return True291 return False291 return any(self.test(expr) for expr in iterable)292293 def __repr__(self):294 return f"Token({self.lineno!r}, {self.type!r}, {self.value!r})"293296294class TokenStreamIterator:295 """The iterator for tokenstreams. Iterate over the stream296 until the eof token is reached.297 """298302 def __init__(self, stream):299 def __init__(self, stream: "TokenStream") -> None:300 self.stream = stream301305 def __iter__(self):302 def __iter__(self) -> "TokenStreamIterator":303 return self304308 def __next__(self):305 def __next__(self) -> Token:306 token = self.stream.current307308 if token.type is TOKEN_EOF:309 self.stream.close()312 raise StopIteration()310 raise StopIteration311312 next(self.stream)313 return token314315
2 unmodified lines
318 parser however does not iterate over it but calls :meth:`next` to go319 one token ahead. The current active token is stored as :attr:`current`.320 """321323 def __init__(self, generator, name, filename):322 def __init__(323 self,324 generator: t.Iterable[Token],325 name: t.Optional[str],326 filename: t.Optional[str],327 ):328 self._iter = iter(generator)325 self._pushed = deque()329 self._pushed: t.Deque[Token] = deque()330 self.name = name331 self.filename = filename332 self.closed = False333 self.current = Token(1, TOKEN_INITIAL, "")334 next(self)335332 def __iter__(self):336 def __iter__(self) -> TokenStreamIterator:337 return TokenStreamIterator(self)338335 def __bool__(self):339 def __bool__(self) -> bool:340 return bool(self._pushed) or self.current.type is not TOKEN_EOF341338 __nonzero__ = __bool__ # py2339342 @property341 def eos(self):343 def eos(self) -> bool:344 """Are we at the end of the stream?"""345 return not self346345 def push(self, token):347 def push(self, token: Token) -> None:348 """Push a token back to the stream."""349 self._pushed.append(token)350349 def look(self):351 def look(self) -> Token:352 """Look at the next token."""353 old_token = next(self)354 result = self.current355 self.push(result)356 self.current = old_token357 return result358357 def skip(self, n=1):359 def skip(self, n: int = 1) -> None:360 """Got n tokens ahead."""361 for _ in range(n):362 next(self)363362 def next_if(self, expr):364 def next_if(self, expr: str) -> t.Optional[Token]:365 """Perform the token test and return the token if it matched.366 Otherwise the return value is `None`.367 """368 if self.current.test(expr):369 return next(self)370371 return None372369 def skip_if(self, expr):373 def skip_if(self, expr: str) -> bool:374 """Like :meth:`next_if` but only returns `True` or `False`."""375 return self.next_if(expr) is not None376373 def __next__(self):377 def __next__(self) -> Token:378 """Go one token ahead and return the old one.379380 Use the built-in :func:`next` instead of calling this directly.381 """382 rv = self.current383384 if self._pushed:385 self.current = self._pushed.popleft()386 elif self.current.type is not TOKEN_EOF:387 try:388 self.current = next(self._iter)389 except StopIteration:390 self.close()391392 return rv393388 def close(self):394 def close(self) -> None:395 """Close the stream."""396 self.current = Token(self.current.lineno, TOKEN_EOF, "")391 self._iter = None397 self._iter = iter(())398 self.closed = True399394 def expect(self, expr):400 def expect(self, expr: str) -> Token:401 """Expect a given token type and return it. This accepts the same402 argument as :meth:`jinja2.lexer.Token.test`.403 """404 if not self.current.test(expr):405 expr = describe_token_expr(expr)406407 if self.current.type is TOKEN_EOF:408 raise TemplateSyntaxError(409 f"unexpected end of template, expected {expr!r}.",410 self.current.lineno,411 self.name,412 self.filename,413 )414415 raise TemplateSyntaxError(416 f"expected token {expr!r}, got {describe_token(self.current)!r}",417 self.current.lineno,418 self.name,419 self.filename,420 )413 try:414 return self.current415 finally:416 next(self)421422 return next(self)423424419def get_lexer(environment):425def get_lexer(environment: "Environment") -> "Lexer":426 """Return a lexer which is probably cached."""427 key = (428 environment.block_start_string,429 environment.block_end_string,
8 unmodified lines
438 environment.newline_sequence,439 environment.keep_trailing_newline,440 )441 lexer = _lexer_cache.get(key)442443 if lexer is None:437 lexer = Lexer(environment)438 _lexer_cache[key] = lexer444 _lexer_cache[key] = lexer = Lexer(environment)445446 return lexer447448449class OptionalLStrip(tuple):
4 unmodified lines
454 __slots__ = ()455456 # Even though it looks like a no-op, creating instances fails457 # without this.451 def __new__(cls, *members, **kwargs):458 def __new__(cls, *members, **kwargs): # type: ignore459 return super().__new__(cls, members)460461462class _Rule(t.NamedTuple):463 pattern: t.Pattern[str]464 tokens: t.Union[str, t.Tuple[str, ...], t.Tuple[Failure]]465 command: t.Optional[str]466467468class Lexer:469 """Class that implements a lexer for a given environment. Automatically470 created by the environment class, usually you don't have to do that.471472 Note that the lexer is not automatically bound to an environment.473 Multiple environments can share the same lexer.474 """475463 def __init__(self, environment):476 def __init__(self, environment: "Environment") -> None:477 # shortcuts478 e = re.escape479467 def c(x):480 def c(x: str) -> t.Pattern[str]:481 return re.compile(x, re.M | re.S)482483 # lexing rules for tags471 tag_rules = [472 (whitespace_re, TOKEN_WHITESPACE, None),473 (float_re, TOKEN_FLOAT, None),474 (integer_re, TOKEN_INTEGER, None),475 (name_re, TOKEN_NAME, None),476 (string_re, TOKEN_STRING, None),477 (operator_re, TOKEN_OPERATOR, None),484 tag_rules: t.List[_Rule] = [485 _Rule(whitespace_re, TOKEN_WHITESPACE, None),486 _Rule(float_re, TOKEN_FLOAT, None),487 _Rule(integer_re, TOKEN_INTEGER, None),488 _Rule(name_re, TOKEN_NAME, None),489 _Rule(string_re, TOKEN_STRING, None),490 _Rule(operator_re, TOKEN_OPERATOR, None),491 ]492493 # assemble the root lexing rule. because "|" is ungreedy494 # we have to sort by length so that the lexer continues working
26 unmodified lines
521 [root_raw_re] + [fr"(?P<{n}>{r}(\-|\+|))" for n, r in root_tag_rules]522 )523524 # global lexing rules512 self.rules = {525 self.rules: t.Dict[str, t.List[_Rule]] = {526 "root": [527 # directives515 (528 _Rule(529 c(fr"(.*?)(?:{root_parts_re})"),517 OptionalLStrip(TOKEN_DATA, "#bygroup"),530 OptionalLStrip(TOKEN_DATA, "#bygroup"), # type: ignore531 "#bygroup",532 ),533 # data521 (c(".+"), TOKEN_DATA, None),534 _Rule(c(".+"), TOKEN_DATA, None),535 ],536 # comments537 TOKEN_COMMENT_BEGIN: [525 (538 _Rule(539 c(540 fr"(.*?)((?:\+{comment_end_re}|\-{comment_end_re}\s*"541 fr"|{comment_end_re}{block_suffix_re}))"542 ),543 (TOKEN_COMMENT, TOKEN_COMMENT_END),544 "#pop",545 ),533 (c(r"(.)"), (Failure("Missing end of comment tag"),), None),546 _Rule(c(r"(.)"), (Failure("Missing end of comment tag"),), None),547 ],548 # blocks549 TOKEN_BLOCK_BEGIN: [537 (550 _Rule(551 c(552 fr"(?:\+{block_end_re}|\-{block_end_re}\s*"553 fr"|{block_end_re}{block_suffix_re})"554 ),
3 unmodified lines
558 ]559 + tag_rules,560 # variables561 TOKEN_VARIABLE_BEGIN: [549 (562 _Rule(563 c(fr"\-{variable_end_re}\s*|{variable_end_re}"),564 TOKEN_VARIABLE_END,565 "#pop",566 )567 ]568 + tag_rules,569 # raw block570 TOKEN_RAW_BEGIN: [558 (571 _Rule(572 c(573 fr"(.*?)((?:{block_start_re}(\-|\+|))\s*endraw\s*"574 fr"(?:\+{block_end_re}|\-{block_end_re}\s*"575 fr"|{block_end_re}{block_suffix_re}))"576 ),564 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),577 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END), # type: ignore578 "#pop",579 ),567 (c(r"(.)"), (Failure("Missing end of raw directive"),), None),580 _Rule(c(r"(.)"), (Failure("Missing end of raw directive"),), None),581 ],582 # line statements583 TOKEN_LINESTATEMENT_BEGIN: [571 (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")584 _Rule(c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")585 ]586 + tag_rules,587 # line comments588 TOKEN_LINECOMMENT_BEGIN: [576 (589 _Rule(590 c(r"(.*?)()(?=\n|$)"),591 (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),592 "#pop",593 )594 ],595 }596584 def _normalize_newlines(self, value):597 def _normalize_newlines(self, value: str) -> str:598 """Replace all newlines with the configured sequence in strings599 and template data.600 """601 return newline_re.sub(self.newline_sequence, value)602590 def tokenize(self, source, name=None, filename=None, state=None):603 def tokenize(604 self,605 source: str,606 name: t.Optional[str] = None,607 filename: t.Optional[str] = None,608 state: t.Optional[str] = None,609 ) -> TokenStream:610 """Calls tokeniter + tokenize and wraps it in a token stream."""611 stream = self.tokeniter(source, name, filename, state)612 return TokenStream(self.wrap(stream, name, filename), name, filename)613595 def wrap(self, stream, name=None, filename=None):614 def wrap(615 self,616 stream: t.Iterable[t.Tuple[int, str, str]],617 name: t.Optional[str] = None,618 filename: t.Optional[str] = None,619 ) -> t.Iterator[Token]:620 """This is called with the stream as returned by `tokenize` and wraps621 every token in a :class:`Token` and converts the value.622 """599 for lineno, token, value in stream:623 for lineno, token, value_str in stream:624 if token in ignored_tokens:625 continue626627 value: t.Any = value_str628602 elif token == TOKEN_LINESTATEMENT_BEGIN:629 if token == TOKEN_LINESTATEMENT_BEGIN:630 token = TOKEN_BLOCK_BEGIN631 elif token == TOKEN_LINESTATEMENT_END:632 token = TOKEN_BLOCK_END633 # we are not interested in those tokens in the parser634 elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):635 continue636 elif token == TOKEN_DATA:610 value = self._normalize_newlines(value)637 value = self._normalize_newlines(value_str)638 elif token == "keyword":612 token = value639 token = value_str640 elif token == TOKEN_NAME:614 value = str(value)641 value = value_str642643 if not value.isidentifier():644 raise TemplateSyntaxError(645 "Invalid character in identifier", lineno, name, filename646 )647 elif token == TOKEN_STRING:648 # try to unescape string649 try:650 value = (623 self._normalize_newlines(value[1:-1])651 self._normalize_newlines(value_str[1:-1])652 .encode("ascii", "backslashreplace")653 .decode("unicode-escape")654 )655 except Exception as e:656 msg = str(e).split(":")[-1].strip()657 raise TemplateSyntaxError(msg, lineno, name, filename)658 elif token == TOKEN_INTEGER:631 value = int(value.replace("_", ""), 0)659 value = int(value_str.replace("_", ""), 0)660 elif token == TOKEN_FLOAT:661 # remove all "_" first to support more Python versions634 value = literal_eval(value.replace("_", ""))662 value = literal_eval(value_str.replace("_", ""))663 elif token == TOKEN_OPERATOR:636 token = operators[value]664 token = operators[value_str]665666 yield Token(lineno, token, value)667639 def tokeniter(self, source, name, filename=None, state=None):668 def tokeniter(669 self,670 source: str,671 name: t.Optional[str],672 filename: t.Optional[str] = None,673 state: t.Optional[str] = None,674 ) -> t.Iterator[t.Tuple[int, str, str]]:675 """This method tokenizes the text and returns the tokens in a676 generator. Use this method if you just want to tokenize a template.677678 .. versionchanged:: 3.0
8 unmodified lines
687 source = "\n".join(lines)688 pos = 0689 lineno = 1690 stack = ["root"]691692 if state is not None and state != "root":693 assert state in ("variable", "block"), "invalid state"694 stack.append(state + "_begin")695696 statetokens = self.rules[stack[-1]]697 source_length = len(source)661 balancing_stack = []698 balancing_stack: t.List[str] = []699 lstrip_unless_re = self.lstrip_unless_re700 newlines_stripped = 0701 line_starting = True702666 while 1:703 while True:704 # tokenizer loop705 for regex, tokens, new_state in statetokens:706 m = regex.match(source, pos)707708 # if no match we try again with the next rule709 if m is None:710 continue711
15 unmodified lines
727 if isinstance(tokens, OptionalLStrip):728 # Rule supports lstrip. Match will look like729 # text, block type, whitespace control, type, control, ...730 text = groups[0]693731 # 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)
1 unmodified line
736 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")703 groups = (stripped,) + groups[1:]740 groups = [stripped, *groups[1:]]741 elif (742 # Not marked for preserving whitespace.743 strip_sign != "+"744 # lstrip is enabled.
2 unmodified lines
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") + 1751752 if l_pos > 0 or line_starting:753 # If there's only whitespace between the newline and the754 # tag, strip it.755 if not lstrip_unless_re.search(text, l_pos):718 groups = (text[:l_pos],) + groups[1:]756 groups = [text[:l_pos], *groups[1:]]757758 for idx, token in enumerate(tokens):759 # failure group760 if token.__class__ is Failure:
14 unmodified lines
775 )776 # normal group777 else:778 data = groups[idx]779780 if data or token not in ignore_if_empty:781 yield lineno, token, data782783 lineno += data.count("\n") + newlines_stripped784 newlines_stripped = 0785786 # strings as token just are yielded as it.787 else:788 data = m.group()789790 # update brace/parentheses balance791 if tokens == TOKEN_OPERATOR:792 if data == "{":793 balancing_stack.append("}")
5 unmodified lines
799 if not balancing_stack:800 raise TemplateSyntaxError(801 f"unexpected '{data}'", lineno, name, filename802 )803804 expected_op = balancing_stack.pop()805806 if expected_op != data:807 raise TemplateSyntaxError(808 f"unexpected '{data}', expected '{expected_op}'",809 lineno,810 name,811 filename,812 )813814 # yield items815 if data or tokens not in ignore_if_empty:816 yield lineno, tokens, data817818 lineno += data.count("\n")819820 line_starting = m.group()[-1:] == "\n"776821 # 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()
16 unmodified lines
841 )842 # direct state name given843 else:844 stack.append(new_state)845846 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 )854855 # publish new function and start again856 pos = pos2857 break858 # if loop terminated without break we haven't found a single match
1 unmodified line
860 else:861 # end of text862 if pos >= source_length:863 return864865 # something went wrong866 raise TemplateSyntaxError(867 f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename868 )
modified:src/jinja2/loaders.py+119 added-43 removed
2 unmodified lines
3"""4import importlib.util5import os6import sys7import typing as t8import weakref9import zipimport10from collections import abc11from hashlib import sha1
3 unmodified lines
15from .exceptions import TemplateNotFound16from .utils import internalcode17from .utils import open_if_exists1819if t.TYPE_CHECKING:20 from .environment import Environment21 from .environment import Template222319def split_template_path(template):24def split_template_path(template: str) -> t.List[str]:25 """Split a path into segments and perform a sanity check. If it detects26 '..' in the path it will raise a `TemplateNotFound` error.27 """28 pieces = []
41 unmodified lines
70 #:71 #: .. versionadded:: 2.472 has_source_access = True7369 def get_source(self, environment, template):74 def get_source(75 self, environment: "Environment", template: str76 ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:77 """Get the template source, filename and reload helper for a template.78 It's passed the environment and template name and has to return a79 tuple in the form ``(source, filename, uptodate)`` or raise a80 `TemplateNotFound` error if it can't locate the template.
11 unmodified lines
92 the template will be reloaded.93 """94 if not self.has_source_access:95 raise RuntimeError(89 f"{self.__class__.__name__} cannot provide access to the source"96 f"{type(self).__name__} cannot provide access to the source"97 )98 raise TemplateNotFound(template)9993 def list_templates(self):100 def list_templates(self) -> t.List[str]:101 """Iterates over all templates. If the loader does not support that102 it should raise a :exc:`TypeError` which is the default behavior.103 """104 raise TypeError("this loader cannot iterate over all templates")105106 @internalcode100 def load(self, environment, name, globals=None):107 def load(108 self,109 environment: "Environment",110 name: str,111 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,112 ) -> "Template":113 """Loads a template. This method looks up the template in the cache114 or loads one by calling :meth:`get_source`. Subclasses should not115 override this method as loaders working on collections of other116 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
57 unmodified lines
174 .. versionchanged:: 2.8175 Added the ``followlinks`` parameter.176 """177166 def __init__(self, searchpath, encoding="utf-8", followlinks=False):178 def __init__(179 self,180 searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],181 encoding: str = "utf-8",182 followlinks: bool = False,183 ) -> None:184 if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):185 searchpath = [searchpath]186170 self.searchpath = list(searchpath)187 self.searchpath = [os.fspath(p) for p in searchpath]188 self.encoding = encoding189 self.followlinks = followlinks190174 def get_source(self, environment, template):191 def get_source(192 self, environment: "Environment", template: str193 ) -> t.Tuple[str, str, t.Callable[[], bool]]:194 pieces = split_template_path(template)195 for searchpath in self.searchpath:196 filename = os.path.join(searchpath, *pieces)197 f = open_if_exists(filename)
5 unmodified lines
203 f.close()204205 mtime = os.path.getmtime(filename)206188 def uptodate():207 def uptodate() -> bool:208 try:209 return os.path.getmtime(filename) == mtime210 except OSError:211 return False212213 return contents, filename, uptodate214 raise TemplateNotFound(template)215197 def list_templates(self):216 def list_templates(self) -> t.List[str]:217 found = set()218 for searchpath in self.searchpath:219 walk_dir = os.walk(searchpath, followlinks=self.followlinks)220 for dirpath, _, filenames in walk_dir:
42 unmodified lines
263 .. versionchanged:: 3.0264 Limited PEP 420 namespace package support.265 """266248 def __init__(self, package_name, package_path="templates", encoding="utf-8"):267 def __init__(268 self,269 package_name: str,270 package_path: "str" = "templates",271 encoding: str = "utf-8",272 ) -> None:273 if package_path == os.path.curdir:274 package_path = ""275 elif package_path[:2] == os.path.curdir + os.path.sep:276 package_path = package_path[2:]
6 unmodified lines
283 # Make sure the package exists. This also makes namespace284 # packages work, otherwise get_loader returns None.285 import_module(package_name)286 spec = importlib.util.find_spec(package_name)287 assert spec is not None, "An import spec was not found for the package."288 loader = spec.loader289 assert loader is not None, "A loader was not found for the package."263 self._loader = loader = spec.loader290 self._loader = loader291 self._archive = None265 self._template_root = None292 template_root = None293294 if isinstance(loader, zipimport.zipimporter):295 self._archive = loader.archive269 pkgdir = next(iter(spec.submodule_search_locations))270 self._template_root = os.path.join(pkgdir, package_path)296 pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore297 template_root = os.path.join(pkgdir, package_path)298 elif spec.submodule_search_locations:299 # This will be one element for regular packages and multiple300 # for namespace packages.301 for root in spec.submodule_search_locations:302 root = os.path.join(root, package_path)303304 if os.path.isdir(root):278 self._template_root = root305 template_root = root306 break307281 if self._template_root is None:308 if template_root is None:309 raise ValueError(310 f"The {package_name!r} package was not installed in a"311 " way that PackageLoader understands."312 )313287 def get_source(self, environment, template):314 self._template_root = template_root315316 def get_source(317 self, environment: "Environment", template: str318 ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:319 p = os.path.join(self._template_root, *split_template_path(template))320 up_to_date: t.Optional[t.Callable[[], bool]]321322 if self._archive is None:323 # Package is a directory.324 if not os.path.isfile(p):
3 unmodified lines
328 source = f.read()329330 mtime = os.path.getmtime(p)331300 def up_to_date():332 def up_to_date() -> bool:333 return os.path.isfile(p) and os.path.getmtime(p) == mtime334335 else:336 # Package is a zip file.337 try:306 source = self._loader.get_data(p)338 source = self._loader.get_data(p) # type: ignore339 except OSError:340 raise TemplateNotFound(template)341342 # Could use the zip's mtime for all template mtimes, but
2 unmodified lines
345 up_to_date = None346347 return source.decode(self.encoding), p, up_to_date348317 def list_templates(self):318 results = []349 def list_templates(self) -> t.List[str]:350 results: t.List[str] = []351352 if self._archive is None:353 # Package is a directory.354 offset = len(self._template_root)
17 unmodified lines
372 + os.path.sep373 )374 offset = len(prefix)375344 for name in self._loader._files.keys():376 for name in self._loader._files.keys(): # type: ignore377 # Find names under the templates directory that aren't directories.378 if name.startswith(prefix) and name[-1] != os.path.sep:379 results.append(name[offset:].replace(os.path.sep, "/"))380
9 unmodified lines
390391 Because auto reloading is rarely useful this is disabled per default.392 """393362 def __init__(self, mapping):394 def __init__(self, mapping: t.Mapping[str, str]) -> None:395 self.mapping = mapping396365 def get_source(self, environment, template):397 def get_source(398 self, environment: "Environment", template: str399 ) -> t.Tuple[str, None, t.Callable[[], bool]]:400 if template in self.mapping:401 source = self.mapping[template]402 return source, None, lambda: source == self.mapping.get(template)403 raise TemplateNotFound(template)404371 def list_templates(self):405 def list_templates(self) -> t.List[str]:406 return sorted(self.mapping)407408409class FunctionLoader(BaseLoader):
13 unmodified lines
423 details have a look at :meth:`BaseLoader.get_source` which has the same424 return value.425 """426393 def __init__(self, load_func):427 def __init__(428 self,429 load_func: t.Callable[430 [str],431 t.Optional[432 t.Union[433 str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]434 ]435 ],436 ],437 ) -> None:438 self.load_func = load_func439396 def get_source(self, environment, template):440 def get_source(441 self, environment: "Environment", template: str442 ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:443 rv = self.load_func(template)444445 if rv is None:446 raise TemplateNotFound(template)447400 elif isinstance(rv, str):448 if isinstance(rv, str):449 return rv, None, None450451 return rv452453454class PrefixLoader(BaseLoader):
10 unmodified lines
465 By loading ``'app1/index.html'`` the file from the app1 package is loaded,466 by loading ``'app2/index.html'`` the file from the second.467 """468420 def __init__(self, mapping, delimiter="/"):469 def __init__(470 self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"471 ) -> None:472 self.mapping = mapping473 self.delimiter = delimiter474424 def get_loader(self, template):475 def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:476 try:477 prefix, name = template.split(self.delimiter, 1)478 loader = self.mapping[prefix]479 except (ValueError, KeyError):480 raise TemplateNotFound(template)481 return loader, name482432 def get_source(self, environment, template):483 def get_source(484 self, environment: "Environment", template: str485 ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:486 loader, name = self.get_loader(template)487 try:488 return loader.get_source(environment, name)489 except TemplateNotFound:
1 unmodified line
491 # (the one that includes the prefix)492 raise TemplateNotFound(template)493494 @internalcode442 def load(self, environment, name, globals=None):495 def load(496 self,497 environment: "Environment",498 name: str,499 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,500 ) -> "Template":501 loader, local_name = self.get_loader(name)502 try:503 return loader.load(environment, local_name, globals)504 except TemplateNotFound:505 # re-raise the exception with the correct filename here.506 # (the one that includes the prefix)507 raise TemplateNotFound(name)508451 def list_templates(self):509 def list_templates(self) -> t.List[str]:510 result = []511 for prefix, loader in self.mapping.items():512 for template in loader.list_templates():513 result.append(prefix + self.delimiter + template)
13 unmodified lines
527 This is useful if you want to allow users to override builtin templates528 from a different location.529 """530473 def __init__(self, loaders):531 def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:532 self.loaders = loaders533476 def get_source(self, environment, template):534 def get_source(535 self, environment: "Environment", template: str536 ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:537 for loader in self.loaders:538 try:539 return loader.get_source(environment, template)540 except TemplateNotFound:541 pass542 raise TemplateNotFound(template)543544 @internalcode485 def load(self, environment, name, globals=None):545 def load(546 self,547 environment: "Environment",548 name: str,549 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,550 ) -> "Template":551 for loader in self.loaders:552 try:553 return loader.load(environment, name, globals)554 except TemplateNotFound:555 pass556 raise TemplateNotFound(name)557493 def list_templates(self):558 def list_templates(self) -> t.List[str]:559 found = set()560 for loader in self.loaders:561 found.update(loader.list_templates())562 return sorted(found)
17 unmodified lines
580 """581582 has_source_access = False583519 def __init__(self, path):584 def __init__(585 self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]586 ) -> None:587 package_name = f"_jinja2_module_templates_{id(self):x}"588589 # create a fake module that looks for the templates in the590 # path given.
1 unmodified line
592593 if not isinstance(path, abc.Iterable) or isinstance(path, str):594 path = [path]595529 mod.__path__ = [os.fspath(p) for p in path]596 mod.__path__ = [os.fspath(p) for p in path] # type: ignore597598 sys.modules[package_name] = weakref.proxy(599 mod, lambda x: sys.modules.pop(package_name, None)600 )
4 unmodified lines
605 self.module = mod606 self.package_name = package_name607608 @staticmethod542 def get_template_key(name):609 def get_template_key(name: str) -> str:610 return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()611612 @staticmethod546 def get_module_filename(name):613 def get_module_filename(name: str) -> str:614 return ModuleLoader.get_template_key(name) + ".py"615616 @internalcode550 def load(self, environment, name, globals=None):617 def load(618 self,619 environment: "Environment",620 name: str,621 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,622 ) -> "Template":623 key = self.get_template_key(name)624 module = f"{self.package_name}.{key}"625 mod = getattr(self.module, module, None)626627 if mod is None:628 try:629 mod = __import__(module, None, None, ["root"])630 except ImportError:
2 unmodified lines
633 # remove the entry from sys.modules, we only want the attribute634 # on the module object we have stored on the loader.635 sys.modules.pop(module, None)636637 if globals is None:638 globals = {}639640 return environment.template_class.from_module_dict(641 environment, mod.__dict__, globals642 )
modified:src/jinja2/meta.py+32 added-19 removed
1"""Functions that expose information about templates that might be2interesting for introspection.3"""4import typing as t56from . import nodes7from .compiler import CodeGenerator8from .compiler import Frame910if t.TYPE_CHECKING:11 from .environment import Environment121314class TrackingCodeGenerator(CodeGenerator):15 """We abuse the code generator for introspection."""1611 def __init__(self, environment):12 CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")13 self.undeclared_identifiers = set()17 def __init__(self, environment: "Environment") -> None:18 super().__init__(environment, "<introspection>", "<introspection>")19 self.undeclared_identifiers: t.Set[str] = set()2015 def write(self, x):21 def write(self, x: str) -> None:22 """Don't write."""2318 def enter_frame(self, frame):24 def enter_frame(self, frame: Frame) -> None:25 """Remember all undeclared identifiers."""20 CodeGenerator.enter_frame(self, frame)26 super().enter_frame(frame)2728 for _, (action, param) in frame.symbols.loads.items():29 if action == "resolve" and param not in self.environment.globals:30 self.undeclared_identifiers.add(param)313226def find_undeclared_variables(ast):33def find_undeclared_variables(ast: nodes.Template) -> t.Set[str]:34 """Returns a set of all variables in the AST that will be looked up from35 the context at runtime. Because at compile time it's not known which36 variables will be used depending on the path the execution takes at37 runtime, all variables are returned.
10 unmodified lines
48 This is good to know because the code generator might raise a49 :exc:`TemplateAssertionError` during compilation and as a matter of50 fact this function can currently raise that exception as well.51 """45 codegen = TrackingCodeGenerator(ast.environment)52 codegen = TrackingCodeGenerator(ast.environment) # type: ignore53 codegen.visit(ast)54 return codegen.undeclared_identifiers555650def find_referenced_templates(ast):57_ref_types = (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)58_RefType = t.Union[nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include]596061def find_referenced_templates(ast: nodes.Template) -> t.Iterator[t.Optional[str]]:62 """Finds all the referenced templates from the AST. This will return an63 iterator over all the hardcoded template extensions, inclusions and64 imports. If dynamic inheritance or inclusion is used, `None` will be65 yielded.
6 unmodified lines
7273 This function is useful for dependency tracking. For example if you want74 to rebuild parts of the website after a layout template has changed.75 """65 for node in ast.find_all(66 (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)67 ):68 if not isinstance(node.template, nodes.Const):76 template_name: t.Any7778 for node in ast.find_all(_ref_types):79 template: nodes.Expr = node.template # type: ignore8081 if not isinstance(template, nodes.Const):82 # a tuple with some non consts in there70 if isinstance(node.template, (nodes.Tuple, nodes.List)):71 for template_name in node.template.items:83 if isinstance(template, (nodes.Tuple, nodes.List)):84 for template_name in template.items:85 # something const, only yield the strings and ignore86 # non-string consts that really just make no sense87 if isinstance(template_name, nodes.Const):88 if isinstance(template_name.value, str):
5 unmodified lines
94 else:95 yield None96 continue97 # constant is a basestring, direct template name85 if isinstance(node.template.value, str):86 yield node.template.value98 if isinstance(template.value, str):99 yield template.value100 # a tuple or list (latter *should* not happen) made of consts,101 # yield the consts that are strings. We could warn here for102 # non string values103 elif isinstance(node, nodes.Include) and isinstance(91 node.template.value, (tuple, list)104 template.value, (tuple, list)105 ):93 for template_name in node.template.value:106 for template_name in template.value:107 if isinstance(template_name, str):108 yield template_name109 # something else we don't care about, we could warn here110 else:
1 unmodified line
modified:src/jinja2/nativetypes.py+24 added-16 removed
1import typing as t2from ast import literal_eval3from itertools import chain4from itertools import islice4from typing import Any56from . import nodes7from .compiler import CodeGenerator8from .compiler import Frame9from .compiler import has_safe_repr10from .environment import Environment11from .environment import Template121313def native_concat(nodes):14def native_concat(values: t.Iterable[t.Any]) -> t.Optional[t.Any]:15 """Return a native Python type from the list of compiled nodes. If16 the result is a single node, its value is returned. Otherwise, the17 nodes are concatenated as strings. If the result can be parsed with18 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,19 the string is returned.2020 :param nodes: Iterable of nodes to concatenate.21 :param values: Iterable of outputs to concatenate.22 """22 head = list(islice(nodes, 2))23 head = list(islice(values, 2))2425 if not head:26 return None27
1 unmodified line
29 raw = head[0]30 if not isinstance(raw, str):31 return raw32 else:32 raw = "".join([str(v) for v in chain(head, nodes)])33 raw = "".join([str(v) for v in chain(head, values)])3435 try:36 return literal_eval(raw)37 except (ValueError, SyntaxError, MemoryError):
5 unmodified lines
43 ``str()`` around output nodes.44 """4546 @staticmethod46 def _default_finalize(value):47 def _default_finalize(value: t.Any) -> t.Any:48 return value4949 def _output_const_repr(self, group):50 def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:51 return repr("".join([str(v) for v in group]))5252 def _output_child_to_const(self, node, frame, finalize):53 def _output_child_to_const(54 self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo55 ) -> t.Any:56 const = node.as_const(frame.eval_ctx)5758 if not has_safe_repr(const):59 raise nodes.Impossible()6061 if isinstance(node, nodes.TemplateData):62 return const6361 return finalize.const(const)64 return finalize.const(const) # type: ignore6563 def _output_child_pre(self, node, frame, finalize):66 def _output_child_pre(67 self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo68 ) -> None:69 if finalize.src is not None:70 self.write(finalize.src)7167 def _output_child_post(self, node, frame, finalize):72 def _output_child_post(73 self, node: nodes.Expr, frame: Frame, finalize: CodeGenerator._FinalizeInfo74 ) -> None:75 if finalize.src is not None:76 self.write(")")777879class NativeEnvironment(Environment):80 """An environment that renders templates to native Python types."""8182 code_generator_class = NativeCodeGenerator76 template_class: Any838485class NativeTemplate(Template):86 environment_class = NativeEnvironment8782 def render(self, *args, **kwargs):88 def render(self, *args: t.Any, **kwargs: t.Any) -> t.Any:89 """Render the template to produce a native Python type. If the90 result is a single node, its value is returned. Otherwise, the91 nodes are concatenated as strings. If the result can be parsed92 with :func:`ast.literal_eval`, the parsed value is returned.
1 unmodified line
94 """95 ctx = self.new_context(dict(*args, **kwargs))9697 try:92 return native_concat(self.root_render_func(ctx))98 return native_concat(self.root_render_func(ctx)) # type: ignore99 except Exception:100 return self.environment.handle_exception()10196 async def render_async(self, *args, **kwargs):102 async def render_async(self, *args: t.Any, **kwargs: t.Any) -> t.Any:103 if not self.environment.is_async:104 raise RuntimeError(105 "The environment was not created with async mode enabled."106 )107108 ctx = self.new_context(dict(*args, **kwargs))109110 try:105 return native_concat([n async for n in self.root_render_func(ctx)])111 return native_concat(112 [n async for n in self.root_render_func(ctx)] # type: ignore113 )114 except Exception:115 return self.environment.handle_exception()116117
1 unmodified line
modified:src/jinja2/nodes.py+221 added-83 removed
2 unmodified lines
3to normalize nodes.4"""5import inspect6import operator7import typing as t8from collections import deque8from typing import Any9from typing import Tuple as TupleType910from markupsafe import Markup1112from .utils import _PassArg1315_binop_to_func = {14if t.TYPE_CHECKING:15 from .environment import Environment1617_NodeBound = t.TypeVar("_NodeBound", bound="Node")1819_binop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {20 "*": operator.mul,21 "/": operator.truediv,22 "//": operator.floordiv,23 "**": operator.pow,
1 unmodified line
25 "+": operator.add,26 "-": operator.sub,27}2825_uaop_to_func = {29_uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] = {30 "not": operator.not_,31 "+": operator.pos,32 "-": operator.neg,33}3431_cmpop_to_func = {35_cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {36 "eq": operator.eq,37 "ne": operator.ne,38 "gt": operator.gt,39 "gteq": operator.ge,
12 unmodified lines
52 """A metaclass for nodes that handles the field and attribute53 inheritance. fields and attributes from the parent class are54 automatically forwarded to the child."""5552 def __new__(mcs, name, bases, d):56 def __new__(mcs, name, bases, d): # type: ignore57 for attr in "fields", "attributes":58 storage = []59 storage.extend(getattr(bases[0] if bases else object, attr, ()))60 storage.extend(d.get(attr, ()))
8 unmodified lines
69 """Holds evaluation time information. Custom attributes can be attached70 to it in extensions.71 """7269 def __init__(self, environment, template_name=None):73 def __init__(74 self, environment: "Environment", template_name: t.Optional[str] = None75 ) -> None:76 self.environment = environment77 if callable(environment.autoescape):78 self.autoescape = environment.autoescape(template_name)79 else:80 self.autoescape = environment.autoescape81 self.volatile = False8277 def save(self):83 def save(self) -> t.Mapping[str, t.Any]:84 return self.__dict__.copy()8580 def revert(self, old):86 def revert(self, old: t.Mapping[str, t.Any]) -> None:87 self.__dict__.clear()88 self.__dict__.update(old)899085def get_eval_context(node, ctx):91def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:92 if ctx is None:93 if node.environment is None:94 raise RuntimeError(95 "if no eval context is passed, the node must have an"
19 unmodified lines
115 The `environment` attribute is set at the end of the parsing process for116 all nodes automatically.117 """118113 fields: TupleType = ()114 attributes = ("lineno", "environment")119 fields: t.Tuple[str, ...] = ()120 attributes: t.Tuple[str, ...] = ("lineno", "environment")121 abstract = True122117 def __init__(self, *fields, **attributes):123 lineno: int124 environment: t.Optional["Environment"]125126 def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:127 if self.abstract:128 raise TypeError("abstract nodes are not instantiable")129 if fields:130 if len(fields) != len(self.fields):131 if not self.fields:123 raise TypeError(f"{self.__class__.__name__!r} takes 0 arguments")132 raise TypeError(f"{type(self).__name__!r} takes 0 arguments")133 raise TypeError(125 f"{self.__class__.__name__!r} takes 0 or {len(self.fields)}"134 f"{type(self).__name__!r} takes 0 or {len(self.fields)}"135 f" argument{'s' if len(self.fields) != 1 else ''}"136 )137 for name, arg in zip(self.fields, fields):138 setattr(self, name, arg)
1 unmodified line
140 setattr(self, attr, attributes.pop(attr, None))141 if attributes:142 raise TypeError(f"unknown attribute {next(iter(attributes))!r}")143135 def iter_fields(self, exclude=None, only=None):144 def iter_fields(145 self,146 exclude: t.Optional[t.Container[str]] = None,147 only: t.Optional[t.Container[str]] = None,148 ) -> t.Iterator[t.Tuple[str, t.Any]]:149 """This method iterates over all fields that are defined and yields150 ``(key, value)`` tuples. Per default all fields are returned, but151 it's possible to limit that to some fields by providing the `only`152 parameter or to exclude some using the `exclude` parameter. Both153 should be sets or tuples of field names.154 """155 for name in self.fields:156 if (144 (exclude is only is None)157 (exclude is None and only is None)158 or (exclude is not None and name not in exclude)159 or (only is not None and name in only)160 ):161 try:162 yield name, getattr(self, name)163 except AttributeError:164 pass165153 def iter_child_nodes(self, exclude=None, only=None):166 def iter_child_nodes(167 self,168 exclude: t.Optional[t.Container[str]] = None,169 only: t.Optional[t.Container[str]] = None,170 ) -> t.Iterator["Node"]:171 """Iterates over all direct child nodes of the node. This iterates172 over all fields and yields the values of they are nodes. If the value173 of a field is a list all the nodes in that list are returned.174 """
4 unmodified lines
179 yield n180 elif isinstance(item, Node):181 yield item182166 def find(self, node_type):183 def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:184 """Find the first node of a given type. If no such node exists the185 return value is `None`.186 """187 for result in self.find_all(node_type):188 return result189173 def find_all(self, node_type):190 return None191192 def find_all(193 self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]194 ) -> t.Iterator[_NodeBound]:195 """Find all the nodes of a given type. If the type is a tuple,196 the check is performed for any of the tuple items.197 """198 for child in self.iter_child_nodes():199 if isinstance(child, node_type):179 yield child200 yield child # type: ignore201 yield from child.find_all(node_type)202182 def set_ctx(self, ctx):203 def set_ctx(self, ctx: str) -> "Node":204 """Reset the context of a node and all child nodes. Per default the205 parser will all generate nodes that have a 'load' context as it's the206 most common one. This method is used in the parser to set assignment207 targets and other nodes to a store context.
1 unmodified line
209 todo = deque([self])210 while todo:211 node = todo.popleft()212 if "ctx" in node.fields:192 node.ctx = ctx213 node.ctx = ctx # type: ignore214 todo.extend(node.iter_child_nodes())215 return self216196 def set_lineno(self, lineno, override=False):217 def set_lineno(self, lineno: int, override: bool = False) -> "Node":218 """Set the line numbers of the node and children."""219 todo = deque([self])220 while todo:221 node = todo.popleft()
2 unmodified lines
224 node.lineno = lineno225 todo.extend(node.iter_child_nodes())226 return self227207 def set_environment(self, environment):228 def set_environment(self, environment: "Environment") -> "Node":229 """Set the environment for all nodes."""230 todo = deque([self])231 while todo:232 node = todo.popleft()233 node.environment = environment234 todo.extend(node.iter_child_nodes())235 return self236216 def __eq__(self, other):237 def __eq__(self, other: t.Any) -> bool:238 if type(self) is not type(other):239 return NotImplemented240241 return tuple(self.iter_fields()) == tuple(other.iter_fields())242222 def __hash__(self):243 def __hash__(self) -> int:244 return hash(tuple(self.iter_fields()))245225 def __repr__(self):246 def __repr__(self) -> str:247 args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)227 return f"{self.__class__.__name__}({args_str})"248 return f"{type(self).__name__}({args_str})"249229 def dump(self):230 def _dump(node):250 def dump(self) -> str:251 def _dump(node: t.Union[Node, t.Any]) -> None:252 if not isinstance(node, Node):253 buf.append(repr(node))254 return255235 buf.append(f"nodes.{node.__class__.__name__}(")256 buf.append(f"nodes.{type(node).__name__}(")257 if not node.fields:258 buf.append(")")259 return260 for idx, field in enumerate(node.fields):
10 unmodified lines
271 else:272 _dump(value)273 buf.append(")")274254 buf = []275 buf: t.List[str] = []276 _dump(self)277 return "".join(buf)278279
14 unmodified lines
294 is passed to the compiler.295 """296297 fields = ("body",)298 body: t.List[Node]299300301class Output(Stmt):302 """A node that holds multiple expressions which are then printed out.303 This is used both for the `print` statement and the regular template data.304 """305306 fields = ("nodes",)307 nodes: t.List["Expr"]308309310class Extends(Stmt):311 """Represents an extends statement."""312313 fields = ("template",)314 template: "Expr"315316317class For(Stmt):318 """The for loop. `target` is the target for the iteration (usually a
4 unmodified lines
323 For filtered nodes an expression can be stored as `test`, otherwise `None`.324 """325326 fields = ("target", "iter", "body", "else_", "test", "recursive")327 target: Node328 iter: Node329 body: t.List[Node]330 else_: t.List[Node]331 test: t.Optional[Node]332 recursive: bool333334335class If(Stmt):336 """If `test` is true, `body` is rendered, else `else_`."""337338 fields = ("test", "body", "elif_", "else_")339 test: Node340 body: t.List[Node]341 elif_: t.List["If"]342 else_: t.List[Node]343344345class Macro(Stmt):346 """A macro definition. `name` is the name of the macro, `args` a list of
1 unmodified line
348 a list of nodes for the macro body.349 """350351 fields = ("name", "args", "defaults", "body")352 name: str353 args: t.List["Name"]354 defaults: t.List["Expr"]355 body: t.List[Node]356357358class CallBlock(Stmt):359 """Like a macro without a name but a call instead. `call` is called with360 the unnamed macro as `caller` argument this node holds.361 """362363 fields = ("call", "args", "defaults", "body")364 call: "Call"365 args: t.List["Name"]366 defaults: t.List["Expr"]367 body: t.List[Node]368369370class FilterBlock(Stmt):371 """Node for filter sections."""372373 fields = ("body", "filter")374 body: t.List[Node]375 filter: "Filter"376377378class With(Stmt):379 """Specific node for with statements. In older versions of Jinja the
2 unmodified lines
382 .. versionadded:: 2.9.3383 """384385 fields = ("targets", "values", "body")386 targets: t.List["Expr"]387 values: t.List["Expr"]388 body: t.List[Node]389390391class Block(Stmt):392 """A node that represents a block.
2 unmodified lines
395 the `required` field was added.396 """397398 fields = ("name", "body", "scoped", "required")399 name: str400 body: t.List[Node]401 scoped: bool402 required: bool403404405class Include(Stmt):406 """A node that represents the include tag."""407408 fields = ("template", "with_context", "ignore_missing")409 template: "Expr"410 with_context: bool411 ignore_missing: bool412413414class Import(Stmt):415 """A node that represents the import tag."""416417 fields = ("template", "target", "with_context")418 template: "Expr"419 target: str420 with_context: bool421422423class FromImport(Stmt):424 """A node that represents the from import tag. It's important to not
7 unmodified lines
432 The list of names may contain tuples if aliases are wanted.433 """434435 fields = ("template", "names", "with_context")436 template: "Expr"437 names: t.List[t.Union[str, t.Tuple[str, str]]]438 with_context: bool439440441class ExprStmt(Stmt):442 """A statement that evaluates an expression and discards the result."""443444 fields = ("node",)445 node: Node446447448class Assign(Stmt):449 """Assigns an expression to a target."""450451 fields = ("target", "node")452 target: "Expr"453 node: Node454455456class AssignBlock(Stmt):457 """Assigns a block to a target."""458459 fields = ("target", "filter", "body")460 target: "Expr"461 filter: t.Optional["Filter"]462 body: t.List[Node]463464465class Expr(Node):466 """Baseclass for all expressions."""467468 abstract = True469404 def as_const(self, eval_ctx=None):470 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:471 """Return the value of the expression as constant or raise472 :exc:`Impossible` if this was not possible.473474 An :class:`EvalContext` can be provided, if none is given
4 unmodified lines
479 the `eval_ctx` parameter was added.480 """481 raise Impossible()482417 def can_assign(self):483 def can_assign(self) -> bool:484 """Check if it's possible to assign something to this node."""485 return False486487488class BinExpr(Expr):489 """Baseclass for all binary expressions."""490491 fields = ("left", "right")492 left: Expr493 right: Expr426 operator: Any = None494 operator: str495 abstract = True496429 def as_const(self, eval_ctx=None):497 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:498 eval_ctx = get_eval_context(self, eval_ctx)499500 # intercepted operators cannot be folded at compile time501 if (433 self.environment.sandboxed434 and self.operator in self.environment.intercepted_binops502 eval_ctx.environment.sandboxed503 and self.operator in eval_ctx.environment.intercepted_binops # type: ignore504 ):505 raise Impossible()506 f = _binop_to_func[self.operator]507 try:
5 unmodified lines
513class UnaryExpr(Expr):514 """Baseclass for all unary expressions."""515516 fields = ("node",)517 node: Expr448 operator: Any = None518 operator: str519 abstract = True520451 def as_const(self, eval_ctx=None):521 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:522 eval_ctx = get_eval_context(self, eval_ctx)523524 # intercepted operators cannot be folded at compile time525 if (455 self.environment.sandboxed456 and self.operator in self.environment.intercepted_unops526 eval_ctx.environment.sandboxed527 and self.operator in eval_ctx.environment.intercepted_unops # type: ignore528 ):529 raise Impossible()530 f = _uaop_to_func[self.operator]531 try:
11 unmodified lines
543 - `param`: like `store` but if the name was defined as function parameter.544 """545546 fields = ("name", "ctx")547 name: str548 ctx: str549477 def can_assign(self):478 return self.name not in ("true", "false", "none", "True", "False", "None")550 def can_assign(self) -> bool:551 return self.name not in {"true", "false", "none", "True", "False", "None"}552553554class NSRef(Expr):555 """Reference to a namespace value assignment"""556557 fields = ("name", "attr")558 name: str559 attr: str560486 def can_assign(self):561 def can_assign(self) -> bool:562 # We don't need any special checks here; NSRef assignments have a563 # runtime check to ensure the target is a namespace object which will564 # have been checked already as it is created using a normal assignment565 # which goes through a `Name` node.
13 unmodified lines
579 representation (objects where ``eval(repr(x)) == x`` is true).580 """581582 fields = ("value",)583 value: t.Any584509 def as_const(self, eval_ctx=None):585 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:586 return self.value587588 @classmethod513 def from_untrusted(cls, value, lineno=None, environment=None):589 def from_untrusted(590 cls,591 value: t.Any,592 lineno: t.Optional[int] = None,593 environment: "t.Optional[Environment]" = None,594 ) -> "Const":595 """Return a const object if the value is representable as596 constant value in the generated code, otherwise it will raise597 an `Impossible` exception.598 """
7 unmodified lines
606class TemplateData(Literal):607 """A constant template string."""608609 fields = ("data",)610 data: str611530 def as_const(self, eval_ctx=None):612 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:613 eval_ctx = get_eval_context(self, eval_ctx)614 if eval_ctx.volatile:615 raise Impossible()616 if eval_ctx.autoescape:
7 unmodified lines
624 is used for loading the names or storing.625 """626627 fields = ("items", "ctx")628 items: t.List[Expr]629 ctx: str630547 def as_const(self, eval_ctx=None):631 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:632 eval_ctx = get_eval_context(self, eval_ctx)633 return tuple(x.as_const(eval_ctx) for x in self.items)634551 def can_assign(self):635 def can_assign(self) -> bool:636 for item in self.items:637 if not item.can_assign():638 return False639 return True
2 unmodified lines
642class List(Literal):643 """Any list literal such as ``[1, 2, 3]``"""644645 fields = ("items",)646 items: t.List[Expr]647563 def as_const(self, eval_ctx=None):648 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:649 eval_ctx = get_eval_context(self, eval_ctx)650 return [x.as_const(eval_ctx) for x in self.items]651652
2 unmodified lines
655 :class:`Pair` nodes.656 """657658 fields = ("items",)659 items: t.List["Pair"]660575 def as_const(self, eval_ctx=None):661 def as_const(662 self, eval_ctx: t.Optional[EvalContext] = None663 ) -> t.Dict[t.Any, t.Any]:664 eval_ctx = get_eval_context(self, eval_ctx)665 return dict(x.as_const(eval_ctx) for x in self.items)666667668class Pair(Helper):669 """A key, value pair for dicts."""670671 fields = ("key", "value")672 key: Expr673 value: Expr674585 def as_const(self, eval_ctx=None):675 def as_const(676 self, eval_ctx: t.Optional[EvalContext] = None677 ) -> t.Tuple[t.Any, t.Any]:678 eval_ctx = get_eval_context(self, eval_ctx)679 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)680681682class Keyword(Helper):683 """A key, value pair for keyword arguments where key is a string."""684685 fields = ("key", "value")686 key: str687 value: Expr688595 def as_const(self, eval_ctx=None):689 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:690 eval_ctx = get_eval_context(self, eval_ctx)691 return self.key, self.value.as_const(eval_ctx)692693
2 unmodified lines
696 foo if bar else baz }}``)697 """698699 fields = ("test", "expr1", "expr2")700 test: Expr701 expr1: Expr702 expr2: t.Optional[Expr]703607 def as_const(self, eval_ctx=None):704 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:705 eval_ctx = get_eval_context(self, eval_ctx)706 if self.test.as_const(eval_ctx):707 return self.expr1.as_const(eval_ctx)708
3 unmodified lines
712713 return self.expr2.as_const(eval_ctx)714715619def args_as_const(node, eval_ctx):716def args_as_const(717 node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]718) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:719 args = [x.as_const(eval_ctx) for x in node.args]720 kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)721722 if node.dyn_args is not None:
12 unmodified lines
735736737class _FilterTestCommon(Expr):738 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")739 node: Expr740 name: str741 args: t.List[Expr]742 kwargs: t.List[Pair]743 dyn_args: t.Optional[Expr]744 dyn_kwargs: t.Optional[Expr]745 abstract = True746 _is_filter = True747643 def as_const(self, eval_ctx=None):748 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:749 eval_ctx = get_eval_context(self, eval_ctx)750751 if eval_ctx.volatile:752 raise Impossible()
3 unmodified lines
756 else:757 env_map = eval_ctx.environment.tests758759 func = env_map.get(self.name)655 pass_arg = _PassArg.from_obj(func)760 pass_arg = _PassArg.from_obj(func) # type: ignore761762 if func is None or pass_arg is _PassArg.context:763 raise Impossible()764
24 unmodified lines
789 If ``node`` is ``None``, the filter is being used in a filter block790 and is applied to the content of the block.791 """792688 def as_const(self, eval_ctx=None):793 node: t.Optional[Expr] # type: ignore794795 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:796 if self.node is None:797 raise Impossible()798799 return super().as_const(eval_ctx=eval_ctx)
20 unmodified lines
820 arguments.821 """822823 fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")824 node: Expr825 args: t.List[Expr]826 kwargs: t.List[Keyword]827 dyn_args: t.Optional[Expr]828 dyn_kwargs: t.Optional[Expr]829830831class Getitem(Expr):832 """Get an attribute or item from an expression and prefer the item."""833834 fields = ("node", "arg", "ctx")835 node: Expr836 arg: Expr837 ctx: str838724 def as_const(self, eval_ctx=None):725 eval_ctx = get_eval_context(self, eval_ctx)839 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:840 if self.ctx != "load":841 raise Impossible()842843 eval_ctx = get_eval_context(self, eval_ctx)844845 try:729 return self.environment.getitem(846 return eval_ctx.environment.getitem(847 self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)848 )849 except Exception:850 raise Impossible()851735 def can_assign(self):736 return False852738853class Getattr(Expr):854 """Get an attribute or item from an expression that is a ascii-only855 bytestring and prefer the attribute.856 """857858 fields = ("node", "attr", "ctx")859 node: Expr860 attr: str861 ctx: str862746 def as_const(self, eval_ctx=None):863 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:864 if self.ctx != "load":865 raise Impossible()866867 eval_ctx = get_eval_context(self, eval_ctx)868869 try:750 eval_ctx = get_eval_context(self, eval_ctx)751 return self.environment.getattr(self.node.as_const(eval_ctx), self.attr)870 return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)871 except Exception:872 raise Impossible()873755 def can_assign(self):756 return False874758875class Slice(Expr):876 """Represents a slice object. This must only be used as argument for877 :class:`Subscript`.878 """879880 fields = ("start", "stop", "step")881 start: t.Optional[Expr]882 stop: t.Optional[Expr]883 step: t.Optional[Expr]884766 def as_const(self, eval_ctx=None):885 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:886 eval_ctx = get_eval_context(self, eval_ctx)887769 def const(obj):888 def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:889 if obj is None:890 return None891 return obj.as_const(eval_ctx)892
5 unmodified lines
898 them to strings.899 """900901 fields = ("nodes",)902 nodes: t.List[Expr]903784 def as_const(self, eval_ctx=None):904 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:905 eval_ctx = get_eval_context(self, eval_ctx)906 return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)907908
2 unmodified lines
911 list of :class:`Operand`\\s.912 """913914 fields = ("expr", "ops")915 expr: Expr916 ops: t.List["Operand"]917796 def as_const(self, eval_ctx=None):918 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:919 eval_ctx = get_eval_context(self, eval_ctx)920 result = value = self.expr.as_const(eval_ctx)921922 try:
14 unmodified lines
937class Operand(Helper):938 """Holds an operator and an expression."""939940 fields = ("op", "expr")941 op: str942 expr: Expr943944945class Mul(BinExpr):946 """Multiplies the left with the right node."""
43 unmodified lines
990 """Short circuited AND."""991992 operator = "and"993870 def as_const(self, eval_ctx=None):994 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:995 eval_ctx = get_eval_context(self, eval_ctx)996 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)997998
1 unmodified line
1000 """Short circuited OR."""10011002 operator = "or"1003880 def as_const(self, eval_ctx=None):1004 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:1005 eval_ctx = get_eval_context(self, eval_ctx)1006 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)10071008
23 unmodified lines
1032 extensions that want to call a callback stored on the environment.1033 """10341035 fields = ("name",)1036 name: str103710381039class ExtensionAttribute(Expr):1040 """Returns the attribute of an extension bound to the environment.
3 unmodified lines
1044 :meth:`~jinja2.ext.Extension.attr` method on an extension.1045 """10461047 fields = ("identifier", "name")1048 identifier: str1049 name: str105010511052class ImportedName(Expr):1053 """If created with an import name the import name is returned on node
2 unmodified lines
1056 compiler so there is no need to assign them to local variables.1057 """10581059 fields = ("importname",)1060 importname: str106110621063class InternalName(Expr):1064 """An internal name in the compiler. You cannot create these nodes1065 yourself but the parser provides a1066 :meth:`~jinja2.parser.Parser.free_identifier` method that creates1067 a new identifier for you. This identifier is not available from the940 template and is not threated specially by the compiler.1068 template and is not treated specially by the compiler.1069 """10701071 fields = ("name",)1072 name: str1073945 def __init__(self):1074 def __init__(self) -> None:1075 raise TypeError(1076 "Can't create internal names. Use the "1077 "`free_identifier` method on a parser."1078 )
2 unmodified lines
1081class MarkSafe(Expr):1082 """Mark the wrapped expression as safe (wrap it as `Markup`)."""10831084 fields = ("expr",)1085 expr: Expr1086957 def as_const(self, eval_ctx=None):1087 def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:1088 eval_ctx = get_eval_context(self, eval_ctx)1089 return Markup(self.expr.as_const(eval_ctx))10901091
4 unmodified lines
1096 .. versionadded:: 2.51097 """10981099 fields = ("expr",)1100 expr: Expr1101971 def as_const(self, eval_ctx=None):1102 def as_const(1103 self, eval_ctx: t.Optional[EvalContext] = None1104 ) -> t.Union[Markup, t.Any]:1105 eval_ctx = get_eval_context(self, eval_ctx)1106 if eval_ctx.volatile:1107 raise Impossible()1108 expr = self.expr.as_const(eval_ctx)
40 unmodified lines
1149class Scope(Stmt):1150 """An artificial scope."""11511152 fields = ("body",)1153 body: t.List[Node]115411551156class OverlayScope(Stmt):1157 """An overlay scope for extensions. This is a largely unoptimized scope
9 unmodified lines
1167 .. versionadded:: 2.101168 """11691170 fields = ("context", "body")1171 context: Expr1172 body: t.List[Node]117311741175class EvalContextModifier(Stmt):1176 """Modifies the eval context. For each option that should be modified,
4 unmodified lines
1181 EvalContextModifier(options=[Keyword('autoescape', Const(True))])1182 """11831184 fields = ("options",)1185 options: t.List[Keyword]118611871188class ScopedEvalContextModifier(EvalContextModifier):1189 """Modifies the eval context and reverts it later. Works exactly like
1 unmodified line
1191 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1192 """11931194 fields = ("body",)1195 body: t.List[Node]119611971198# make sure nobody creates custom nodes1061def _failing_new(*args, **kwargs):1199def _failing_new(*args: t.Any, **kwargs: t.Any) -> t.NoReturn:1200 raise TypeError("can't create custom node types")120112021203NodeType.__new__ = staticmethod(_failing_new) # type: ignore
1 unmodified line
modified:src/jinja2/optimizer.py+11 added-4 removed
5 unmodified lines
6want. For example, loop unrolling doesn't work because unrolled loops7would have a different scope. The solution would be a second syntax tree8that stored the scoping rules.9"""10import typing as t1112from . import nodes13from .visitor import NodeTransformer1415if t.TYPE_CHECKING:16 from .environment import Environment1714def optimize(node, environment):1819def optimize(node: nodes.Node, environment: "Environment") -> nodes.Node:20 """The context hint can be used to perform an static optimization21 based on the context given."""22 optimizer = Optimizer(environment)18 return optimizer.visit(node)23 return t.cast(nodes.Node, optimizer.visit(node))242526class Optimizer(NodeTransformer):22 def __init__(self, environment):27 def __init__(self, environment: "t.Optional[Environment]") -> None:28 self.environment = environment2925 def generic_visit(self, node, *args, **kwargs):30 def generic_visit(31 self, node: nodes.Node, *args: t.Any, **kwargs: t.Any32 ) -> nodes.Node:33 node = super().generic_visit(node, *args, **kwargs)3435 # Do constant folding. Some other nodes besides Expr have36 # as_const, but folding them causes errors later on.
11 unmodified lines
modified:src/jinja2/parser.py+187 added-102 removed
1"""Parse tokens from the lexer into nodes for the compiler."""2import typing3import typing as t45from . import nodes6from .exceptions import TemplateAssertionError7from .exceptions import TemplateSyntaxError8from .lexer import describe_token9from .lexer import describe_token_expr1011if t.TYPE_CHECKING:12 import typing_extensions as te13 from .environment import Environment1415_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)16_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)1718_statement_keywords = frozenset(19 [20 "for",21 "if",
10 unmodified lines
32 ]33)34_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])3526_math_nodes = {36_math_nodes: t.Dict[str, t.Type[nodes.Expr]] = {37 "add": nodes.Add,38 "sub": nodes.Sub,39 "mul": nodes.Mul,40 "div": nodes.Div,
6 unmodified lines
47 """This is the central parsing class Jinja uses. It's passed to48 extensions and can be used to parse expressions or statements.49 """5041 def __init__(self, environment, source, name=None, filename=None, state=None):51 def __init__(52 self,53 environment: "Environment",54 source: str,55 name: t.Optional[str] = None,56 filename: t.Optional[str] = None,57 state: t.Optional[str] = None,58 ) -> None:59 self.environment = environment60 self.stream = environment._tokenize(source, name, filename, state)61 self.name = name62 self.filename = filename63 self.closed = False47 self.extensions = {}64 self.extensions: t.Dict[65 str, t.Callable[["Parser"], t.Union[nodes.Node, t.List[nodes.Node]]]66 ] = {}67 for extension in environment.iter_extensions():68 for tag in extension.tags:69 self.extensions[tag] = extension.parse70 self._last_identifier = 052 self._tag_stack = []53 self._end_token_stack = []71 self._tag_stack: t.List[str] = []72 self._end_token_stack: t.List[t.Tuple[str, ...]] = []7355 def fail(self, msg, lineno=None, exc=TemplateSyntaxError):74 def fail(75 self,76 msg: str,77 lineno: t.Optional[int] = None,78 exc: t.Type[TemplateSyntaxError] = TemplateSyntaxError,79 ) -> t.NoReturn:80 """Convenience method that raises `exc` with the message, passed81 line number or last line number as well as the current name and82 filename.83 """84 if lineno is None:85 lineno = self.stream.current.lineno86 raise exc(msg, lineno, self.name, self.filename)8764 def _fail_ut_eof(self, name, end_token_stack, lineno):65 expected = []88 def _fail_ut_eof(89 self,90 name: t.Optional[str],91 end_token_stack: t.List[t.Tuple[str, ...]],92 lineno: t.Optional[int],93 ) -> t.NoReturn:94 expected: t.Set[str] = set()95 for exprs in end_token_stack:67 expected.extend(map(describe_token_expr, exprs))96 expected.update(map(describe_token_expr, exprs))97 if end_token_stack:69 currently_looking = " or ".join(98 currently_looking: t.Optional[str] = " or ".join(99 map(repr, map(describe_token_expr, end_token_stack[-1]))100 )101 else:102 currently_looking = None
21 unmodified lines
124 )125126 self.fail(" ".join(message), lineno)12799 def fail_unknown_tag(self, name, lineno=None):128 def fail_unknown_tag(self, name: str, lineno: t.Optional[int] = None) -> t.NoReturn:129 """Called if the parser encounters an unknown tag. Tries to fail130 with a human readable error message that could help to identify131 the problem.132 """104 return self._fail_ut_eof(name, self._end_token_stack, lineno)133 self._fail_ut_eof(name, self._end_token_stack, lineno)134106 def fail_eof(self, end_tokens=None, lineno=None):135 def fail_eof(136 self,137 end_tokens: t.Optional[t.Tuple[str, ...]] = None,138 lineno: t.Optional[int] = None,139 ) -> t.NoReturn:140 """Like fail_unknown_tag but for end of template situations."""141 stack = list(self._end_token_stack)142 if end_tokens is not None:143 stack.append(end_tokens)111 return self._fail_ut_eof(None, stack, lineno)144 self._fail_ut_eof(None, stack, lineno)145113 def is_tuple_end(self, extra_end_rules=None):146 def is_tuple_end(147 self, extra_end_rules: t.Optional[t.Tuple[str, ...]] = None148 ) -> bool:149 """Are we at the end of a tuple?"""150 if self.stream.current.type in ("variable_end", "block_end", "rparen"):151 return True152 elif extra_end_rules is not None:118 return self.stream.current.test_any(extra_end_rules)153 return self.stream.current.test_any(extra_end_rules) # type: ignore154 return False155121 def free_identifier(self, lineno=None):156 def free_identifier(self, lineno: t.Optional[int] = None) -> nodes.InternalName:157 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""158 self._last_identifier += 1159 rv = object.__new__(nodes.InternalName)160 nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)126 return rv161 return rv # type: ignore162128 def parse_statement(self):163 def parse_statement(self) -> t.Union[nodes.Node, t.List[nodes.Node]]:164 """Parse a single statement."""165 token = self.stream.current166 if token.type != "name":167 self.fail("tag name expected", token.lineno)168 self._tag_stack.append(token.value)169 pop_tag = True170 try:171 if token.value in _statement_keywords:137 return getattr(self, "parse_" + self.stream.current.value)()172 f = getattr(self, f"parse_{self.stream.current.value}")173 return f() # type: ignore174 if token.value == "call":175 return self.parse_call_block()176 if token.value == "filter":177 return self.parse_filter_block()
10 unmodified lines
188 finally:189 if pop_tag:190 self._tag_stack.pop()191156 def parse_statements(self, end_tokens, drop_needle=False):192 def parse_statements(193 self, end_tokens: t.Tuple[str, ...], drop_needle: bool = False194 ) -> t.List[nodes.Node]:195 """Parse multiple statements into a list until one of the end tokens196 is reached. This is used to parse the body of statements as it also197 parses template data if appropriate. The parser checks first if the198 current token is a colon and skips it if there is one. Then it checks
18 unmodified lines
217 if drop_needle:218 next(self.stream)219 return result220183 def parse_set(self):221 def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:222 """Parse an assign statement."""223 lineno = next(self.stream).lineno224 target = self.parse_assign_target(with_namespace=True)225 if self.stream.skip_if("assign"):
2 unmodified lines
228 filter_node = self.parse_filter(None)229 body = self.parse_statements(("name:endset",), drop_needle=True)230 return nodes.AssignBlock(target, filter_node, body, lineno=lineno)231194 def parse_for(self):232 def parse_for(self) -> nodes.For:233 """Parse a for loop."""234 lineno = self.stream.expect("name:for").lineno235 target = self.parse_assign_target(extra_end_rules=("name:in",))236 self.stream.expect("name:in")
10 unmodified lines
247 else:248 else_ = self.parse_statements(("name:endfor",), drop_needle=True)249 return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)250213 def parse_if(self):251 def parse_if(self) -> nodes.If:252 """Parse an if construct."""253 node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)216 while 1:254 while True:255 node.test = self.parse_tuple(with_condexpr=False)256 node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))257 node.elif_ = []258 node.else_ = []
6 unmodified lines
265 result.else_ = self.parse_statements(("name:endif",), drop_needle=True)266 break267 return result268231 def parse_with(self):269 def parse_with(self) -> nodes.With:270 node = nodes.With(lineno=next(self.stream).lineno)233 targets = []234 values = []271 targets: t.List[nodes.Expr] = []272 values: t.List[nodes.Expr] = []273 while self.stream.current.type != "block_end":274 if targets:275 self.stream.expect("comma")276 target = self.parse_assign_target()
5 unmodified lines
282 node.values = values283 node.body = self.parse_statements(("name:endwith",), drop_needle=True)284 return node285248 def parse_autoescape(self):286 def parse_autoescape(self) -> nodes.Scope:287 node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)288 node.options = [nodes.Keyword("autoescape", self.parse_expression())]289 node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)290 return nodes.Scope([node])291254 def parse_block(self):292 def parse_block(self) -> nodes.Block:293 node = nodes.Block(lineno=next(self.stream).lineno)294 node.name = self.stream.expect("name").value295 node.scoped = self.stream.skip_if("name:scoped")296 node.required = self.stream.skip_if("name:required")
14 unmodified lines
311 # with whitespace data312 if node.required and not all(313 isinstance(child, nodes.TemplateData) and child.data.isspace()314 for body in node.body277 for child in body.nodes315 for child in body.nodes # type: ignore316 ):317 self.fail("Required blocks can only contain comments or whitespace")318319 self.stream.skip_if("name:" + node.name)320 return node321284 def parse_extends(self):322 def parse_extends(self) -> nodes.Extends:323 node = nodes.Extends(lineno=next(self.stream).lineno)324 node.template = self.parse_expression()325 return node326289 def parse_import_context(self, node, default):327 def parse_import_context(328 self, node: _ImportInclude, default: bool329 ) -> _ImportInclude:330 if self.stream.current.test_any(331 "name:with", "name:without"332 ) and self.stream.look().test("name:context"):333 node.with_context = next(self.stream).value == "with"
1 unmodified line
335 else:336 node.with_context = default337 return node338299 def parse_include(self):339 def parse_include(self) -> nodes.Include:340 node = nodes.Include(lineno=next(self.stream).lineno)341 node.template = self.parse_expression()342 if self.stream.current.test("name:ignore") and self.stream.look().test(343 "name:missing"
3 unmodified lines
347 else:348 node.ignore_missing = False349 return self.parse_import_context(node, True)350311 def parse_import(self):351 def parse_import(self) -> nodes.Import:352 node = nodes.Import(lineno=next(self.stream).lineno)353 node.template = self.parse_expression()354 self.stream.expect("name:as")355 node.target = self.parse_assign_target(name_only=True).name356 return self.parse_import_context(node, False)357318 def parse_from(self):358 def parse_from(self) -> nodes.FromImport:359 node = nodes.FromImport(lineno=next(self.stream).lineno)360 node.template = self.parse_expression()361 self.stream.expect("name:import")362 node.names = []363324 def parse_context():364 def parse_context() -> bool:365 if (366 self.stream.current.value367 in {368 "with",
5 unmodified lines
374 self.stream.skip()375 return True376 return False377338 while 1:378 while True:379 if node.names:380 self.stream.expect("comma")381 if self.stream.current.type == "name":382 if parse_context():
17 unmodified lines
400 if not hasattr(node, "with_context"):401 node.with_context = False402 return node403364 def parse_signature(self, node):365 node.args = args = []366 node.defaults = defaults = []404 def parse_signature(self, node: _MacroCall) -> None:405 args = node.args = []406 defaults = node.defaults = []407 self.stream.expect("lparen")408 while self.stream.current.type != "rparen":409 if args:410 self.stream.expect("comma")
5 unmodified lines
416 self.fail("non-default argument follows default argument")417 args.append(arg)418 self.stream.expect("rparen")419380 def parse_call_block(self):420 def parse_call_block(self) -> nodes.CallBlock:421 node = nodes.CallBlock(lineno=next(self.stream).lineno)422 if self.stream.current.type == "lparen":423 self.parse_signature(node)424 else:425 node.args = []426 node.defaults = []427388 node.call = self.parse_expression()389 if not isinstance(node.call, nodes.Call):428 call_node = self.parse_expression()429 if not isinstance(call_node, nodes.Call):430 self.fail("expected call", node.lineno)431 node.call = call_node432 node.body = self.parse_statements(("name:endcall",), drop_needle=True)433 return node434394 def parse_filter_block(self):435 def parse_filter_block(self) -> nodes.FilterBlock:436 node = nodes.FilterBlock(lineno=next(self.stream).lineno)396 node.filter = self.parse_filter(None, start_inline=True)437 node.filter = self.parse_filter(None, start_inline=True) # type: ignore438 node.body = self.parse_statements(("name:endfilter",), drop_needle=True)439 return node440400 def parse_macro(self):441 def parse_macro(self) -> nodes.Macro:442 node = nodes.Macro(lineno=next(self.stream).lineno)443 node.name = self.parse_assign_target(name_only=True).name444 self.parse_signature(node)445 node.body = self.parse_statements(("name:endmacro",), drop_needle=True)446 return node447407 def parse_print(self):448 def parse_print(self) -> nodes.Output:449 node = nodes.Output(lineno=next(self.stream).lineno)450 node.nodes = []451 while self.stream.current.type != "block_end":452 if node.nodes:453 self.stream.expect("comma")454 node.nodes.append(self.parse_expression())455 return node456457 @typing.overload458 def parse_assign_target(459 self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...460 ) -> nodes.Name:461 ...462463 @typing.overload464 def parse_assign_target(465 self,418 with_tuple=True,419 name_only=False,420 extra_end_rules=None,421 with_namespace=False,422 ):466 with_tuple: bool = True,467 name_only: bool = False,468 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,469 with_namespace: bool = False,470 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:471 ...472473 def parse_assign_target(474 self,475 with_tuple: bool = True,476 name_only: bool = False,477 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,478 with_namespace: bool = False,479 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:480 """Parse an assignment target. As Jinja allows assignments to481 tuples, this function can parse all allowed assignment targets. Per482 default assignments to tuples are parsed, that can be disable however483 by setting `with_tuple` to `False`. If only assignments to names are484 wanted `name_only` can be set to `True`. The `extra_end_rules`485 parameter is forwarded to the tuple parsing function. If486 `with_namespace` is enabled, a namespace assignment may be parsed.487 """488 target: nodes.Expr489490 if with_namespace and self.stream.look().type == "dot":491 token = self.stream.expect("name")492 next(self.stream) # dot493 attr = self.stream.expect("name")
7 unmodified lines
501 simplified=True, extra_end_rules=extra_end_rules502 )503 else:504 target = self.parse_primary()505506 target.set_ctx("store")507508 if not target.can_assign():509 self.fail(449 f"can't assign to {target.__class__.__name__.lower()!r}", target.lineno510 f"can't assign to {type(target).__name__.lower()!r}", target.lineno511 )451 return target512513 return target # type: ignore514453 def parse_expression(self, with_condexpr=True):515 def parse_expression(self, with_condexpr: bool = True) -> nodes.Expr:516 """Parse an expression. Per default all expressions are parsed, if517 the optional `with_condexpr` parameter is set to `False` conditional518 expressions are not parsed.519 """520 if with_condexpr:521 return self.parse_condexpr()522 return self.parse_or()523462 def parse_condexpr(self):524 def parse_condexpr(self) -> nodes.Expr:525 lineno = self.stream.current.lineno526 expr1 = self.parse_or()527 expr3: t.Optional[nodes.Expr]528529 while self.stream.skip_if("name:if"):530 expr2 = self.parse_or()531 if self.stream.skip_if("name:else"):532 expr3 = self.parse_condexpr()
2 unmodified lines
535 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)536 lineno = self.stream.current.lineno537 return expr1538475 def parse_or(self):539 def parse_or(self) -> nodes.Expr:540 lineno = self.stream.current.lineno541 left = self.parse_and()542 while self.stream.skip_if("name:or"):543 right = self.parse_and()544 left = nodes.Or(left, right, lineno=lineno)545 lineno = self.stream.current.lineno546 return left547484 def parse_and(self):548 def parse_and(self) -> nodes.Expr:549 lineno = self.stream.current.lineno550 left = self.parse_not()551 while self.stream.skip_if("name:and"):552 right = self.parse_not()553 left = nodes.And(left, right, lineno=lineno)554 lineno = self.stream.current.lineno555 return left556493 def parse_not(self):557 def parse_not(self) -> nodes.Expr:558 if self.stream.current.test("name:not"):559 lineno = next(self.stream).lineno560 return nodes.Not(self.parse_not(), lineno=lineno)561 return self.parse_compare()562499 def parse_compare(self):563 def parse_compare(self) -> nodes.Expr:564 lineno = self.stream.current.lineno565 expr = self.parse_math1()566 ops = []503 while 1:567 while True:568 token_type = self.stream.current.type569 if token_type in _compare_operators:570 next(self.stream)571 ops.append(nodes.Operand(token_type, self.parse_math1()))
10 unmodified lines
582 if not ops:583 return expr584 return nodes.Compare(expr, ops, lineno=lineno)585522 def parse_math1(self):586 def parse_math1(self) -> nodes.Expr:587 lineno = self.stream.current.lineno588 left = self.parse_concat()589 while self.stream.current.type in ("add", "sub"):590 cls = _math_nodes[self.stream.current.type]
2 unmodified lines
593 left = cls(left, right, lineno=lineno)594 lineno = self.stream.current.lineno595 return left596533 def parse_concat(self):597 def parse_concat(self) -> nodes.Expr:598 lineno = self.stream.current.lineno599 args = [self.parse_math2()]600 while self.stream.current.type == "tilde":601 next(self.stream)
1 unmodified line
603 if len(args) == 1:604 return args[0]605 return nodes.Concat(args, lineno=lineno)606543 def parse_math2(self):607 def parse_math2(self) -> nodes.Expr:608 lineno = self.stream.current.lineno609 left = self.parse_pow()610 while self.stream.current.type in ("mul", "div", "floordiv", "mod"):611 cls = _math_nodes[self.stream.current.type]
2 unmodified lines
614 left = cls(left, right, lineno=lineno)615 lineno = self.stream.current.lineno616 return left617554 def parse_pow(self):618 def parse_pow(self) -> nodes.Expr:619 lineno = self.stream.current.lineno620 left = self.parse_unary()621 while self.stream.current.type == "pow":622 next(self.stream)
1 unmodified line
624 left = nodes.Pow(left, right, lineno=lineno)625 lineno = self.stream.current.lineno626 return left627564 def parse_unary(self, with_filter=True):628 def parse_unary(self, with_filter: bool = True) -> nodes.Expr:629 token_type = self.stream.current.type630 lineno = self.stream.current.lineno631 node: nodes.Expr632633 if token_type == "sub":634 next(self.stream)635 node = nodes.Neg(self.parse_unary(False), lineno=lineno)636 elif token_type == "add":
5 unmodified lines
642 if with_filter:643 node = self.parse_filter_expr(node)644 return node645580 def parse_primary(self):646 def parse_primary(self) -> nodes.Expr:647 token = self.stream.current648 node: nodes.Expr649 if token.type == "name":650 if token.value in ("true", "false", "True", "False"):651 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)652 elif token.value in ("none", "None"):
25 unmodified lines
678 return node679680 def parse_tuple(681 self,615 simplified=False,616 with_condexpr=True,617 extra_end_rules=None,618 explicit_parentheses=False,619 ):682 simplified: bool = False,683 with_condexpr: bool = True,684 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,685 explicit_parentheses: bool = False,686 ) -> t.Union[nodes.Tuple, nodes.Expr]:687 """Works like `parse_expression` but if multiple expressions are688 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.689 This method could also return a regular expression instead of a tuple690 if no commas where found.
17 unmodified lines
708 elif with_condexpr:709 parse = self.parse_expression710 else:711645 def parse():712 def parse() -> nodes.Expr:713 return self.parse_expression(with_condexpr=False)714648 args = []715 args: t.List[nodes.Expr] = []716 is_tuple = False717650 while 1:718 while True:719 if args:720 self.stream.expect("comma")721 if self.is_tuple_end(extra_end_rules):722 break
19 unmodified lines
742 )743744 return nodes.Tuple(args, "load", lineno=lineno)745678 def parse_list(self):746 def parse_list(self) -> nodes.List:747 token = self.stream.expect("lbracket")680 items = []748 items: t.List[nodes.Expr] = []749 while self.stream.current.type != "rbracket":750 if items:751 self.stream.expect("comma")752 if self.stream.current.type == "rbracket":
1 unmodified line
754 items.append(self.parse_expression())755 self.stream.expect("rbracket")756 return nodes.List(items, lineno=token.lineno)757690 def parse_dict(self):758 def parse_dict(self) -> nodes.Dict:759 token = self.stream.expect("lbrace")692 items = []760 items: t.List[nodes.Pair] = []761 while self.stream.current.type != "rbrace":762 if items:763 self.stream.expect("comma")764 if self.stream.current.type == "rbrace":
4 unmodified lines
769 items.append(nodes.Pair(key, value, lineno=key.lineno))770 self.stream.expect("rbrace")771 return nodes.Dict(items, lineno=token.lineno)772705 def parse_postfix(self, node):706 while 1:773 def parse_postfix(self, node: nodes.Expr) -> nodes.Expr:774 while True:775 token_type = self.stream.current.type776 if token_type == "dot" or token_type == "lbracket":777 node = self.parse_subscript(node)778 # calls are valid both after postfix expressions (getattr
3 unmodified lines
782 else:783 break784 return node785718 def parse_filter_expr(self, node):719 while 1:786 def parse_filter_expr(self, node: nodes.Expr) -> nodes.Expr:787 while True:788 token_type = self.stream.current.type789 if token_type == "pipe":722 node = self.parse_filter(node)790 node = self.parse_filter(node) # type: ignore791 elif token_type == "name" and self.stream.current.value == "is":792 node = self.parse_test(node)793 # calls are valid both after postfix expressions (getattr794 # and getitem) as well as filters and tests
2 unmodified lines
797 else:798 break799 return node800733 def parse_subscript(self, node):801 def parse_subscript(802 self, node: nodes.Expr803 ) -> t.Union[nodes.Getattr, nodes.Getitem]:804 token = next(self.stream)805 arg: nodes.Expr806807 if token.type == "dot":808 attr_token = self.stream.current809 next(self.stream)810 if attr_token.type == "name":
4 unmodified lines
815 self.fail("expected name or number", attr_token.lineno)816 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)817 return nodes.Getitem(node, arg, "load", lineno=token.lineno)818 if token.type == "lbracket":747 args = []819 args: t.List[nodes.Expr] = []820 while self.stream.current.type != "rbracket":821 if args:822 self.stream.expect("comma")823 args.append(self.parse_subscribed())
4 unmodified lines
828 arg = nodes.Tuple(args, "load", lineno=token.lineno)829 return nodes.Getitem(node, arg, "load", lineno=token.lineno)830 self.fail("expected subscript expression", token.lineno)831760 def parse_subscribed(self):832 def parse_subscribed(self) -> nodes.Expr:833 lineno = self.stream.current.lineno834 args: t.List[t.Optional[nodes.Expr]]835836 if self.stream.current.type == "colon":837 next(self.stream)838 args = [None]
21 unmodified lines
860 args.append(None)861862 return nodes.Slice(lineno=lineno, *args)863791 def parse_call(self, node):864 def parse_call_args(self) -> t.Tuple:865 token = self.stream.expect("lparen")866 args = []867 kwargs = []795 dyn_args = dyn_kwargs = None868 dyn_args = None869 dyn_kwargs = None870 require_comma = False871798 def ensure(expr):872 def ensure(expr: bool) -> None:873 if not expr:874 self.fail("invalid syntax for function call expression", token.lineno)875876 while self.stream.current.type != "rparen":877 if require_comma:878 self.stream.expect("comma")879880 # support for trailing comma881 if self.stream.current.type == "rparen":882 break883884 if self.stream.current.type == "mul":885 ensure(dyn_args is None and dyn_kwargs is None)886 next(self.stream)887 dyn_args = self.parse_expression()
17 unmodified lines
905 ensure(dyn_args is None and dyn_kwargs is None and not kwargs)906 args.append(self.parse_expression())907908 require_comma = True909910 self.stream.expect("rparen")911 return args, kwargs, dyn_args, dyn_kwargs912835 if node is None:836 return args, kwargs, dyn_args, dyn_kwargs913 def parse_call(self, node: nodes.Expr) -> nodes.Call:914 # The lparen will be expected in parse_call_args, but the lineno915 # needs to be recorded before the stream is advanced.916 token = self.stream.current917 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()918 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)919839 def parse_filter(self, node, start_inline=False):920 def parse_filter(921 self, node: t.Optional[nodes.Expr], start_inline: bool = False922 ) -> t.Optional[nodes.Expr]:923 while self.stream.current.type == "pipe" or start_inline:924 if not start_inline:925 next(self.stream)926 token = self.stream.expect("name")
1 unmodified line
928 while self.stream.current.type == "dot":929 next(self.stream)930 name += "." + self.stream.expect("name").value931 if self.stream.current.type == "lparen":849 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)932 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()933 else:934 args = []935 kwargs = []936 dyn_args = dyn_kwargs = None
2 unmodified lines
939 )940 start_inline = False941 return node942860 def parse_test(self, node):943 def parse_test(self, node: nodes.Expr) -> nodes.Expr:944 token = next(self.stream)945 if self.stream.current.test("name:not"):946 next(self.stream)947 negated = True
5 unmodified lines
953 name += "." + self.stream.expect("name").value954 dyn_args = dyn_kwargs = None955 kwargs = []956 if self.stream.current.type == "lparen":874 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)957 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()958 elif (959 self.stream.current.type960 in {961 "name",
19 unmodified lines
981 if negated:982 node = nodes.Not(node, lineno=token.lineno)983 return node984902 def subparse(self, end_tokens=None):903 body = []904 data_buffer = []985 def subparse(986 self, end_tokens: t.Optional[t.Tuple[str, ...]] = None987 ) -> t.List[nodes.Node]:988 body: t.List[nodes.Node] = []989 data_buffer: t.List[nodes.Node] = []990 add_data = data_buffer.append991992 if end_tokens is not None:993 self._end_token_stack.append(end_tokens)994910 def flush_data():995 def flush_data() -> None:996 if data_buffer:997 lineno = data_buffer[0].lineno998 body.append(nodes.Output(data_buffer[:], lineno=lineno))999 del data_buffer[:]
30 unmodified lines
1030 if end_tokens is not None:1031 self._end_token_stack.pop()1032 return body1033949 def parse(self):1034 def parse(self) -> nodes.Template:1035 """Parse the whole template into a `Template` node."""1036 result = nodes.Template(self.subparse(), lineno=1)1037 result.set_environment(self.environment)1038 return result
added:src/jinja2/py.typed
modified:src/jinja2/runtime.py+232 added-180 removed
1"""The runtime functions and state used by compiled templates."""2import functools3import sys4import typing as t5from collections import abc6from itertools import chain
15 unmodified lines
22from .utils import Namespace # noqa: F40123from .utils import object_type_repr24from .utils import pass_eval_context2526V = t.TypeVar("V")27F = t.TypeVar("F", bound=t.Callable[..., t.Any])2829if t.TYPE_CHECKING:30 import logging31 import typing_extensions as te32 from .environment import Environment3334 class LoopRenderFunc(te.Protocol):35 def __call__(36 self,37 reciter: t.Iterable[V],38 loop_render_func: "LoopRenderFunc",39 depth: int = 0,40 ) -> str:41 ...424344# these variables are exported to the template runtime45exported = [46 "LoopContext",47 "TemplateReference",
17 unmodified lines
65 "auto_await",66]676853def identity(x):69def identity(x: V) -> V:70 """Returns its argument. Useful for certain things in the71 environment.72 """73 return x747560def markup_join(seq):76def markup_join(seq: t.Iterable[t.Any]) -> str:77 """Concatenation that escapes if necessary and converts to string."""78 buf = []79 iterator = map(soft_str, seq)80 for arg in iterator:
2 unmodified lines
83 return Markup("").join(chain(buf, iterator))84 return concat(buf)858671def str_join(seq):87def str_join(seq: t.Iterable[t.Any]) -> str:88 """Simple args to string conversion and concatenation."""89 return concat(map(str, seq))909176def unicode_join(seq):92def unicode_join(seq: t.Iterable[t.Any]) -> str:93 import warnings9495 warnings.warn(96 "This template must be recompiled with at least Jinja 3.0, or"
4 unmodified lines
101 return str_join(seq)102103104def new_context(89 environment,90 template_name,91 blocks,92 vars=None,93 shared=None,94 globals=None,95 locals=None,96):105 environment: "Environment",106 template_name: t.Optional[str],107 blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],108 vars: t.Optional[t.Dict[str, t.Any]] = None,109 shared: bool = False,110 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,111 locals: t.Optional[t.Mapping[str, t.Any]] = None,112) -> "Context":113 """Internal helper for context creation."""114 if vars is None:115 vars = {}116 if shared:
15 unmodified lines
132133class TemplateReference:134 """The `self` in templates."""135120 def __init__(self, context):136 def __init__(self, context: "Context") -> None:137 self.__context = context138123 def __getitem__(self, name):139 def __getitem__(self, name: str) -> t.Any:140 blocks = self.__context.blocks[name]141 return BlockReference(name, self.__context, blocks, 0)142127 def __repr__(self):128 return f"<{self.__class__.__name__} {self.__context.name!r}>"143 def __repr__(self) -> str:144 return f"<{type(self).__name__} {self.__context.name!r}>"145146131class ContextMeta(type):132 def __new__(mcs, name, bases, d):133 rv = type.__new__(mcs, name, bases, d)147def _dict_method_all(dict_method: F) -> F:148 @functools.wraps(dict_method)149 def f_all(self: "Context") -> t.Any:150 return dict_method(self.get_all())151135 if not bases:136 return rv152 return t.cast(F, f_all)153138 if "resolve_or_missing" in d:139 # If the subclass overrides resolve_or_missing it opts in to140 # modern mode no matter what.141 rv._legacy_resolve_mode = False142 elif "resolve" in d or rv._legacy_resolve_mode:143 # If the subclass overrides resolve, or if its base is144 # already in legacy mode, warn about legacy behavior.145 import warnings154147 warnings.warn(148 "Overriding 'resolve' is deprecated and will not have"149 " the expected behavior in Jinja 3.1. Override"150 " 'resolve_or_missing' instead ",151 DeprecationWarning,152 stacklevel=2,153 )154 rv._legacy_resolve_mode = True155156 return rv157158155@abc.Mapping.register160class Context(metaclass=ContextMeta):156class Context:157 """The template context holds the variables of a template. It stores the158 values passed to the template and also the names the template exports.159 Creating instances is neither supported nor useful as it's created160 automatically at various stages of the template evaluation and should not
11 unmodified lines
172 method that doesn't fail with a `KeyError` but returns an173 :class:`Undefined` object for missing variables.174 """175180 _legacy_resolve_mode = False176 _legacy_resolve_mode: t.ClassVar[bool] = False177182 def __init__(self, environment, parent, name, blocks, globals=None):178 def __init_subclass__(cls) -> None:179 if "resolve_or_missing" in cls.__dict__:180 # If the subclass overrides resolve_or_missing it opts in to181 # modern mode no matter what.182 cls._legacy_resolve_mode = False183 elif "resolve" in cls.__dict__ or cls._legacy_resolve_mode:184 # If the subclass overrides resolve, or if its base is185 # already in legacy mode, warn about legacy behavior.186 import warnings187188 warnings.warn(189 "Overriding 'resolve' is deprecated and will not have"190 " the expected behavior in Jinja 3.1. Override"191 " 'resolve_or_missing' instead ",192 DeprecationWarning,193 stacklevel=2,194 )195 cls._legacy_resolve_mode = True196197 def __init__(198 self,199 environment: "Environment",200 parent: t.Dict[str, t.Any],201 name: t.Optional[str],202 blocks: t.Dict[str, t.Callable[["Context"], t.Iterator[str]]],203 globals: t.Optional[t.MutableMapping[str, t.Any]] = None,204 ):205 self.parent = parent184 self.vars = {}206 self.vars: t.Dict[str, t.Any] = {}207 self.environment: "Environment" = environment208 self.eval_ctx = EvalContext(self.environment, name)187 self.exported_vars = set()209 self.exported_vars: t.Set[str] = set()210 self.name = name211 self.globals_keys = set() if globals is None else set(globals)212213 # create the initial mapping of blocks. Whenever template inheritance214 # takes place the runtime will update this mapping with the new blocks215 # from the template.216 self.blocks = {k: [v] for k, v in blocks.items()}217196 def super(self, name, current):218 def super(219 self, name: str, current: t.Callable[["Context"], t.Iterator[str]]220 ) -> t.Union["BlockReference", "Undefined"]:221 """Render a parent block."""222 try:223 blocks = self.blocks[name]224 index = blocks.index(current) + 1
3 unmodified lines
228 f"there is no parent block called {name!r}.", name="super"229 )230 return BlockReference(name, self, blocks, index)231208 def get(self, key, default=None):232 def get(self, key: str, default: t.Any = None) -> t.Any:233 """Look up a variable by name, or return a default if the key is234 not found.235236 :param key: The variable name to look up.
3 unmodified lines
240 return self[key]241 except KeyError:242 return default243220 def resolve(self, key):244 def resolve(self, key: str) -> t.Union[t.Any, "Undefined"]:245 """Look up a variable by name, or return an :class:`Undefined`246 object if the key is not found.247248 If you need to add custom behavior, override
17 unmodified lines
266 return self.environment.undefined(name=key)267268 return rv269246 def resolve_or_missing(self, key):270 def resolve_or_missing(self, key: str) -> t.Any:271 """Look up a variable by name, or return a ``missing`` sentinel272 if the key is not found.273274 Override this method to add custom lookup behavior.
17 unmodified lines
292 return self.parent[key]293294 return missing295272 def get_exported(self):296 def get_exported(self) -> t.Dict[str, t.Any]:297 """Get a new dict with the exported variables."""298 return {k: self.vars[k] for k in self.exported_vars}299276 def get_all(self):300 def get_all(self) -> t.Dict[str, t.Any]:301 """Return the complete context as dict including the exported302 variables. For optimizations reasons this might not return an303 actual copy so be careful with using it.304 """
3 unmodified lines
308 return self.vars309 return dict(self.parent, **self.vars)310311 @internalcode288 def call(__self, __obj, *args, **kwargs): # noqa: B902312 def call(313 __self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902314 ) -> t.Union[t.Any, "Undefined"]:315 """Call the callable with the arguments and keyword arguments316 provided but inject the active context or environment as first317 argument if the callable has :func:`pass_context` or318 :func:`pass_environment`.
3 unmodified lines
322323 # Allow callable classes to take a context324 if (325 hasattr(__obj, "__call__") # noqa: B004300 and _PassArg.from_obj(__obj.__call__) is not None326 and _PassArg.from_obj(__obj.__call__) is not None # type: ignore327 ):302 __obj = __obj.__call__328 __obj = __obj.__call__ # type: ignore329304 if callable(__obj):305 pass_arg = _PassArg.from_obj(__obj)330 pass_arg = _PassArg.from_obj(__obj)331307 if pass_arg is _PassArg.context:308 # the active context should have access to variables set in309 # loops and blocks without mutating the context itself310 if kwargs.get("_loop_vars"):311 __self = __self.derived(kwargs["_loop_vars"])312 if kwargs.get("_block_vars"):313 __self = __self.derived(kwargs["_block_vars"])314 args = (__self,) + args315 elif pass_arg is _PassArg.eval_context:316 args = (__self.eval_ctx,) + args317 elif pass_arg is _PassArg.environment:318 args = (__self.environment,) + args332 if pass_arg is _PassArg.context:333 # the active context should have access to variables set in334 # loops and blocks without mutating the context itself335 if kwargs.get("_loop_vars"):336 __self = __self.derived(kwargs["_loop_vars"])337 if kwargs.get("_block_vars"):338 __self = __self.derived(kwargs["_block_vars"])339 args = (__self,) + args340 elif pass_arg is _PassArg.eval_context:341 args = (__self.eval_ctx,) + args342 elif pass_arg is _PassArg.environment:343 args = (__self.environment,) + args344345 kwargs.pop("_block_vars", None)346 kwargs.pop("_loop_vars", None)347348 try:349 return __obj(*args, **kwargs)350 except StopIteration:351 return __self.environment.undefined(352 "value was undefined because a callable raised a"353 " StopIteration exception"354 )355330 def derived(self, locals=None):356 def derived(self, locals: t.Optional[t.Dict[str, t.Any]] = None) -> "Context":357 """Internal helper function to create a derived context. This is358 used in situations where the system needs a new context in the same359 template that is independent.360 """
3 unmodified lines
364 context.eval_ctx = self.eval_ctx365 context.blocks.update((k, list(v)) for k, v in self.blocks.items())366 return context367342 # ignore: true343 def _all(meth): # noqa: B902344 def proxy(self):345 return getattr(self.get_all(), meth)()368 keys = _dict_method_all(dict.keys)369 values = _dict_method_all(dict.values)370 items = _dict_method_all(dict.items)371347 proxy.__doc__ = getattr(dict, meth).__doc__348 proxy.__name__ = meth349 return proxy350351 keys = _all("keys") # type:ignore352 values = _all("values") # type:ignore353 items = _all("items") # type:ignore354 del _all355356 def __contains__(self, name):372 def __contains__(self, name: str) -> bool:373 return name in self.vars or name in self.parent374359 def __getitem__(self, key):375 def __getitem__(self, key: str) -> t.Any:376 """Look up a variable by name with ``[]`` syntax, or raise a377 ``KeyError`` if the key is not found.378 """379 item = self.resolve_or_missing(key)
2 unmodified lines
382 raise KeyError(key)383384 return item385370 def __repr__(self):371 return f"<{self.__class__.__name__} {self.get_all()!r} of {self.name!r}>"386 def __repr__(self) -> str:387 return f"<{type(self).__name__} {self.get_all()!r} of {self.name!r}>"388389390class BlockReference:391 """One block on a template reference."""392377 def __init__(self, name, context, stack, depth):393 def __init__(394 self,395 name: str,396 context: "Context",397 stack: t.List[t.Callable[["Context"], t.Iterator[str]]],398 depth: int,399 ) -> None:400 self.name = name401 self._context = context402 self._stack = stack403 self._depth = depth404405 @property384 def super(self):406 def super(self) -> t.Union["BlockReference", "Undefined"]:407 """Super the block."""408 if self._depth + 1 >= len(self._stack):409 return self._context.environment.undefined(410 f"there is no parent block called {self.name!r}.", name="super"411 )412 return BlockReference(self.name, self._context, self._stack, self._depth + 1)413414 @internalcode393 async def _async_call(self):394 rv = concat([x async for x in self._stack[self._depth](self._context)])415 async def _async_call(self) -> str:416 rv = concat(417 [x async for x in self._stack[self._depth](self._context)] # type: ignore418 )419420 if self._context.eval_ctx.autoescape:421 return Markup(rv)422423 return rv424425 @internalcode402 def __call__(self):426 def __call__(self) -> str:427 if self._context.environment.is_async:404 return self._async_call()428 return self._async_call() # type: ignore429430 rv = concat(self._stack[self._depth](self._context))431432 if self._context.eval_ctx.autoescape:
10 unmodified lines
443 #: Current iteration of the loop, starting at 0.444 index0 = -1445446 _length: t.Optional[int] = None423 _after = missing424 _current = missing425 _before = missing426 _last_changed_value = missing447 _after: t.Any = missing448 _current: t.Any = missing449 _before: t.Any = missing450 _last_changed_value: t.Any = missing451428 def __init__(self, iterable, undefined, recurse=None, depth0=0):452 def __init__(453 self,454 iterable: t.Iterable[V],455 undefined: t.Type["Undefined"],456 recurse: t.Optional["LoopRenderFunc"] = None,457 depth0: int = 0,458 ) -> None:459 """460 :param iterable: Iterable to wrap.461 :param undefined: :class:`Undefined` class to use for next and462 previous items.
8 unmodified lines
471 #: How many levels deep a recursive loop currently is, starting at 0.472 self.depth0 = depth0473474 @staticmethod445 def _to_iterator(iterable):475 def _to_iterator(iterable: t.Iterable[V]) -> t.Iterator[V]:476 return iter(iterable)477478 @property449 def length(self):479 def length(self) -> int:480 """Length of the iterable.481482 If the iterable is a generator or otherwise does not have a483 size, it is eagerly evaluated to get a size.
1 unmodified line
485 if self._length is not None:486 return self._length487488 try:459 self._length = len(self._iterable)489 self._length = len(self._iterable) # type: ignore490 except TypeError:491 iterable = list(self._iterator)492 self._iterator = self._to_iterator(iterable)493 self._length = len(iterable) + self.index + (self._after is not missing)494495 return self._length496467 def __len__(self):497 def __len__(self) -> int:498 return self.length499500 @property471 def depth(self):501 def depth(self) -> int:502 """How many levels deep a recursive loop currently is, starting at 1."""503 return self.depth0 + 1504505 @property476 def index(self):506 def index(self) -> int:507 """Current iteration of the loop, starting at 1."""508 return self.index0 + 1509510 @property481 def revindex0(self):511 def revindex0(self) -> int:512 """Number of iterations from the end of the loop, ending at 0.513514 Requires calculating :attr:`length`.515 """516 return self.length - self.index517518 @property489 def revindex(self):519 def revindex(self) -> int:520 """Number of iterations from the end of the loop, ending at 1.521522 Requires calculating :attr:`length`.523 """524 return self.length - self.index0525526 @property497 def first(self):527 def first(self) -> bool:528 """Whether this is the first iteration of the loop."""529 return self.index0 == 0530501 def _peek_next(self):531 def _peek_next(self) -> t.Any:532 """Return the next element in the iterable, or :data:`missing`533 if the iterable is exhausted. Only peeks one item ahead, caching534 the result in :attr:`_last` for use in subsequent checks. The535 cache is reset when :meth:`__next__` is called.
4 unmodified lines
540 self._after = next(self._iterator, missing)541 return self._after542543 @property514 def last(self):544 def last(self) -> bool:545 """Whether this is the last iteration of the loop.546547 Causes the iterable to advance early. See548 :func:`itertools.groupby` for issues this can cause.
1 unmodified line
550 """551 return self._peek_next() is missing552553 @property524 def previtem(self):554 def previtem(self) -> t.Union[t.Any, "Undefined"]:555 """The item in the previous iteration. Undefined during the556 first iteration.557 """558 if self.first:
1 unmodified line
560561 return self._before562563 @property534 def nextitem(self):564 def nextitem(self) -> t.Union[t.Any, "Undefined"]:565 """The item in the next iteration. Undefined during the last566 iteration.567568 Causes the iterable to advance early. See569 :func:`itertools.groupby` for issues this can cause.540 The :func:`groupby` filter avoids that issue.570 The :func:`jinja-filters.groupby` filter avoids that issue.571 """572 rv = self._peek_next()573574 if rv is missing:575 return self._undefined("there is no next item")576577 return rv578549 def cycle(self, *args):579 def cycle(self, *args: V) -> V:580 """Return a value from the given args, cycling through based on581 the current :attr:`index0`.582583 :param args: One or more values to cycle through.
2 unmodified lines
586 raise TypeError("no items for cycling given")587588 return args[self.index0 % len(args)]589560 def changed(self, *value):590 def changed(self, *value: t.Any) -> bool:591 """Return ``True`` if previously called with a different value592 (including when called for the first time).593594 :param value: One or more values to compare to the last call.
3 unmodified lines
598 return True599600 return False601572 def __iter__(self):602 def __iter__(self) -> "LoopContext":603 return self604575 def __next__(self):605 def __next__(self) -> t.Tuple[t.Any, "LoopContext"]:606 if self._after is not missing:607 rv = self._after608 self._after = missing609 else:
4 unmodified lines
614 self._current = rv615 return rv, self616617 @internalcode588 def __call__(self, iterable):618 def __call__(self, iterable: t.Iterable[V]) -> str:619 """When iterating over nested data, render the body of the loop620 recursively with the given inner iterable data.621622 The loop must have the ``recursive`` marker for this to work.
4 unmodified lines
627 )628629 return self._recurse(iterable, self._recurse, depth=self.depth)630601 def __repr__(self):602 return f"<{self.__class__.__name__} {self.index}/{self.length}>"631 def __repr__(self) -> str:632 return f"<{type(self).__name__} {self.index}/{self.length}>"633634635class AsyncLoopContext(LoopContext):636 _iterator: t.AsyncIterator[t.Any] # type: ignore637638 @staticmethod607 def _to_iterator(iterable):639 def _to_iterator( # type: ignore640 iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]]641 ) -> t.AsyncIterator[V]:642 return auto_aiter(iterable)643644 @property611 async def length(self):645 async def length(self) -> int: # type: ignore646 if self._length is not None:647 return self._length648649 try:616 self._length = len(self._iterable)650 self._length = len(self._iterable) # type: ignore651 except TypeError:652 iterable = [x async for x in self._iterator]653 self._iterator = self._to_iterator(iterable)654 self._length = len(iterable) + self.index + (self._after is not missing)655656 return self._length657658 @property625 async def revindex0(self):659 async def revindex0(self) -> int: # type: ignore660 return await self.length - self.index661662 @property629 async def revindex(self):663 async def revindex(self) -> int: # type: ignore664 return await self.length - self.index0665632 async def _peek_next(self):666 async def _peek_next(self) -> t.Any:667 if self._after is not missing:668 return self._after669670 try:
3 unmodified lines
674675 return self._after676677 @property644 async def last(self):678 async def last(self) -> bool: # type: ignore679 return await self._peek_next() is missing680681 @property648 async def nextitem(self):682 async def nextitem(self) -> t.Union[t.Any, "Undefined"]:683 rv = await self._peek_next()684685 if rv is missing:686 return self._undefined("there is no next item")687688 return rv689656 def __aiter__(self):690 def __aiter__(self) -> "AsyncLoopContext":691 return self692659 async def __anext__(self):693 async def __anext__(self) -> t.Tuple[t.Any, "AsyncLoopContext"]:694 if self._after is not missing:695 rv = self._after696 self._after = missing697 else:
9 unmodified lines
707 """Wraps a macro function."""708709 def __init__(710 self,677 environment,678 func,679 name,680 arguments,681 catch_kwargs,682 catch_varargs,683 caller,684 default_autoescape=None,711 environment: "Environment",712 func: t.Callable[..., str],713 name: str,714 arguments: t.List[str],715 catch_kwargs: bool,716 catch_varargs: bool,717 caller: bool,718 default_autoescape: t.Optional[bool] = None,719 ):720 self._environment = environment721 self._func = func722 self._argument_count = len(arguments)
2 unmodified lines
725 self.catch_kwargs = catch_kwargs726 self.catch_varargs = catch_varargs727 self.caller = caller728 self.explicit_caller = "caller" in arguments729730 if default_autoescape is None:731 if callable(environment.autoescape):732 default_autoescape = environment.autoescape(None)733 else:696 default_autoescape = environment.autoescape734 default_autoescape = environment.autoescape735736 self._default_autoescape = default_autoescape737738 @internalcode739 @pass_eval_context701 def __call__(self, *args, **kwargs):740 def __call__(self, *args: t.Any, **kwargs: t.Any) -> str:741 # This requires a bit of explanation, In the past we used to742 # decide largely based on compile-time information if a macro is743 # safe or unsafe. While there was a volatile mode it was largely744 # unused for deciding on escaping. This turns out to be
67 unmodified lines
812 )813814 return self._invoke(arguments, autoescape)815777 async def _async_invoke(self, arguments, autoescape):778 rv = await self._func(*arguments)816 async def _async_invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:817 rv = await self._func(*arguments) # type: ignore818819 if autoescape:820 return Markup(rv)821783 return rv822 return rv # type: ignore823785 def _invoke(self, arguments, autoescape):824 def _invoke(self, arguments: t.List[t.Any], autoescape: bool) -> str:825 if self._environment.is_async:787 return self._async_invoke(arguments, autoescape)826 return self._async_invoke(arguments, autoescape) # type: ignore827828 rv = self._func(*arguments)829830 if autoescape:831 rv = Markup(rv)832833 return rv834796 def __repr__(self):835 def __repr__(self) -> str:836 name = "anonymous" if self.name is None else repr(self.name)798 return f"<{self.__class__.__name__} {name}>"837 return f"<{type(self).__name__} {name}>"838839840class Undefined:841 """The default undefined type. This undefined type can be printed and
16 unmodified lines
858 "_undefined_name",859 "_undefined_exception",860 )861823 def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):862 def __init__(863 self,864 hint: t.Optional[str] = None,865 obj: t.Any = missing,866 name: t.Optional[str] = None,867 exc: t.Type[TemplateRuntimeError] = UndefinedError,868 ) -> None:869 self._undefined_hint = hint870 self._undefined_obj = obj871 self._undefined_name = name872 self._undefined_exception = exc873874 @property830 def _undefined_message(self):875 def _undefined_message(self) -> str:876 """Build a message about the undefined value based on how it was877 accessed.878 """879 if self._undefined_hint:
13 unmodified lines
893 f" attribute {self._undefined_name!r}"894 )895896 @internalcode852 def _fail_with_undefined_error(self, *args, **kwargs):897 def _fail_with_undefined_error(self, *args: t.Any, **kwargs: t.Any) -> t.NoReturn:898 """Raise an :exc:`UndefinedError` when operations are performed899 on the undefined value.900 """901 raise self._undefined_exception(self._undefined_message)902903 @internalcode859 def __getattr__(self, name):904 def __getattr__(self, name: str) -> t.Any:905 if name[:2] == "__":906 raise AttributeError(name)907908 return self._fail_with_undefined_error()909910 __add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error911 __mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error
5 unmodified lines
917 __lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error918 __int__ = __float__ = __complex__ = _fail_with_undefined_error919 __pow__ = __rpow__ = _fail_with_undefined_error920875 def __eq__(self, other):921 def __eq__(self, other: t.Any) -> bool:922 return type(self) is type(other)923878 def __ne__(self, other):924 def __ne__(self, other: t.Any) -> bool:925 return not self.__eq__(other)926881 def __hash__(self):927 def __hash__(self) -> int:928 return id(type(self))929884 def __str__(self):930 def __str__(self) -> str:931 return ""932887 def __len__(self):933 def __len__(self) -> int:934 return 0935890 def __iter__(self):936 def __iter__(self) -> t.Iterator[t.Any]:937 yield from ()938893 async def __aiter__(self):939 async def __aiter__(self) -> t.AsyncIterator[t.Any]:940 for _ in ():941 yield942897 def __bool__(self):943 def __bool__(self) -> bool:944 return False945900 def __repr__(self):946 def __repr__(self) -> str:947 return "Undefined"948949904def make_logging_undefined(logger=None, base=None):950def make_logging_undefined(951 logger: t.Optional["logging.Logger"] = None, base: t.Type[Undefined] = Undefined952) -> t.Type[Undefined]:953 """Given a logger object this returns a new undefined class that will954 log certain failures. It will log iterations and printing. If no955 logger is given a default logger is created.956
16 unmodified lines
973 import logging974975 logger = logging.getLogger(__name__)976 logger.addHandler(logging.StreamHandler(sys.stderr))929 if base is None:930 base = Undefined977932 def _log_message(undef):933 logger.warning("Template variable warning: %s", undef._undefined_message)978 def _log_message(undef: Undefined) -> None:979 logger.warning( # type: ignore980 "Template variable warning: %s", undef._undefined_message981 )982935 class LoggingUndefined(base):936 def _fail_with_undefined_error(self, *args, **kwargs):983 class LoggingUndefined(base): # type: ignore984 __slots__ = ()985986 def _fail_with_undefined_error( # type: ignore987 self, *args: t.Any, **kwargs: t.Any988 ) -> t.NoReturn:989 try:938 return super()._fail_with_undefined_error(*args, **kwargs)990 super()._fail_with_undefined_error(*args, **kwargs)991 except self._undefined_exception as e:940 logger.error("Template variable error: %s", e)992 logger.error("Template variable error: %s", e) # type: ignore993 raise e994943 def __str__(self):995 def __str__(self) -> str:996 _log_message(self)945 return super().__str__()997 return super().__str__() # type: ignore998947 def __iter__(self):999 def __iter__(self) -> t.Iterator[t.Any]:1000 _log_message(self)949 return super().__iter__()1001 return super().__iter__() # type: ignore1002951 def __bool__(self):1003 def __bool__(self) -> bool:1004 _log_message(self)953 return super().__bool__()1005 return super().__bool__() # type: ignore10061007 return LoggingUndefined10081009
14 unmodified lines
1024 """10251026 __slots__ = ()1027976 def __html__(self):977 return self.__str__()1028 def __html__(self) -> str:1029 return str(self)1030979 def __getattr__(self, _):1031 def __getattr__(self, _: str) -> "ChainableUndefined":1032 return self1033982 __getitem__ = __getattr__1034 __getitem__ = __getattr__ # type: ignore103510361037class DebugUndefined(Undefined):1038 """An undefined that returns the debug info when printed.
10 unmodified lines
1049 """10501051 __slots__ = ()10521001 def __str__(self):1053 def __str__(self) -> str:1054 if self._undefined_hint:1055 message = f"undefined value printed: {self._undefined_hint}"10561057 elif self._undefined_obj is missing:1006 message = self._undefined_name1058 message = self._undefined_name # type: ignore10591060 else:1061 message = (1062 f"no such element: {object_type_repr(self._undefined_obj)}"
39 unmodified lines
modified:src/jinja2/sandbox.py+72 added-65 removed
1 unmodified line
2Useful when the template itself comes from an untrusted source.3"""4import operator5import types6import typing as t7from _string import formatter_field_name_split # type: ignore8from collections import abc9from collections import deque10from string import Formatter10from typing import FrozenSet11from typing import Set1112from markupsafe import EscapeFormatter13from markupsafe import Markup1415from .environment import Environment16from .exceptions import SecurityError17from .runtime import Context18from .runtime import Undefined1920F = t.TypeVar("F", bound=t.Callable[..., t.Any])2122#: maximum number of items a range may produce23MAX_RANGE = 1000002425#: Unsafe function attributes.23UNSAFE_FUNCTION_ATTRIBUTES: Set = set()26UNSAFE_FUNCTION_ATTRIBUTES: t.Set[str] = set()2728#: Unsafe method attributes. Function attributes are unsafe for methods too.26UNSAFE_METHOD_ATTRIBUTES: Set = set()29UNSAFE_METHOD_ATTRIBUTES: t.Set[str] = set()3031#: unsafe generator attributes.32UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}33
2 unmodified lines
3637#: unsafe attributes on async generators38UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}3937_mutable_spec = (40_mutable_spec: t.Tuple[t.Tuple[t.Type, t.FrozenSet[str]], ...] = (41 (42 abc.MutableSet,43 frozenset(44 [
34 unmodified lines
79 ),80)818280def inspect_format_method(callable):83def inspect_format_method(callable: t.Callable) -> t.Optional[str]:84 if not isinstance(85 callable, (types.MethodType, types.BuiltinMethodType)86 ) or callable.__name__ not in ("format", "format_map"):87 return None8889 obj = callable.__self__9091 if isinstance(obj, str):92 return obj9394 return None959690def safe_range(*args):97def safe_range(*args: int) -> range:98 """A range that can't generate ranges with a length of more than99 MAX_RANGE items.100 """101 rng = range(*args)
6 unmodified lines
108109 return rng110111105def unsafe(f):112def unsafe(f: F) -> F:113 """Marks a function or method as unsafe.114115 .. code-block: python116117 @unsafe118 def delete(self):119 pass120 """114 f.unsafe_callable = True121 f.unsafe_callable = True # type: ignore122 return f123124118def is_internal_attribute(obj, attr):125def is_internal_attribute(obj: t.Any, attr: str) -> bool:126 """Test if the attribute given is an internal python attribute. For127 example this function returns `True` for the `func_code` attribute of128 python objects. This is useful if the environment method129 :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.
28 unmodified lines
158 return True159 return attr.startswith("__")160161155def modifies_known_mutable(obj, attr):162def modifies_known_mutable(obj: t.Any, attr: str) -> bool:163 """This function checks if an attribute on a builtin mutable object164 (list, dict, set or deque) or the corresponding ABCs would modify it165 if called.166
32 unmodified lines
199200 #: default callback table for the binary operators. A copy of this is201 #: available on each instance of a sandboxed environment as202 #: :attr:`binop_table`196 default_binop_table = {203 default_binop_table: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {204 "+": operator.add,205 "-": operator.sub,206 "*": operator.mul,207 "/": operator.truediv,
4 unmodified lines
212213 #: default callback table for the unary operators. A copy of this is214 #: available on each instance of a sandboxed environment as215 #: :attr:`unop_table`209 default_unop_table = {"+": operator.pos, "-": operator.neg}216 default_unop_table: t.Dict[str, t.Callable[[t.Any], t.Any]] = {217 "+": operator.pos,218 "-": operator.neg,219 }220221 #: a set of binary operators that should be intercepted. Each operator222 #: that is added to this set (empty by default) is delegated to the223 #: :meth:`call_binop` method that will perform the operator. The default
7 unmodified lines
231 #: operator call, so make sure only to intercept the ones you are232 #: interested in.233 #:234 #: .. versionadded:: 2.6225 intercepted_binops: FrozenSet = frozenset()235 intercepted_binops: t.FrozenSet[str] = frozenset()236237 #: a set of unary operators that should be intercepted. Each operator238 #: that is added to this set (empty by default) is delegated to the239 #: :meth:`call_unop` method that will perform the operator. The default
6 unmodified lines
246 #: operator call, so make sure only to intercept the ones you are247 #: interested in.248 #:249 #: .. versionadded:: 2.6240 intercepted_unops: FrozenSet = frozenset()250 intercepted_unops: t.FrozenSet[str] = frozenset()251242 def intercept_unop(self, operator):243 """Called during template compilation with the name of a unary244 operator to check if it should be intercepted at runtime. If this245 method returns `True`, :meth:`call_unop` is executed for this unary246 operator. The default implementation of :meth:`call_unop` will use247 the :attr:`unop_table` dictionary to perform the operator with the248 same logic as the builtin one.249250 The following unary operators are interceptable: ``+`` and ``-``251252 Intercepted calls are always slower than the native operator call,253 so make sure only to intercept the ones you are interested in.254255 .. versionadded:: 2.6256 """257 return False258259 def __init__(self, *args, **kwargs):260 Environment.__init__(self, *args, **kwargs)252 def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:253 super().__init__(*args, **kwargs)254 self.globals["range"] = safe_range255 self.binop_table = self.default_binop_table.copy()256 self.unop_table = self.default_unop_table.copy()257265 def is_safe_attribute(self, obj, attr, value):258 def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:259 """The sandboxed environment will call this method to check if the260 attribute of an object is safe to access. Per default all attributes261 starting with an underscore are considered private as well as the262 special attributes of internal python objects as returned by the263 :func:`is_internal_attribute` function.264 """265 return not (attr.startswith("_") or is_internal_attribute(obj, attr))266274 def is_safe_callable(self, obj):275 """Check if an object is safely callable. Per default a function is276 considered safe unless the `unsafe_callable` attribute exists and is277 True. Override this method to alter the behavior, but this won't278 affect the `unsafe` decorator from this module.267 def is_safe_callable(self, obj: t.Any) -> bool:268 """Check if an object is safely callable. By default callables269 are considered safe unless decorated with :func:`unsafe`.270271 This also recognizes the Django convention of setting272 ``func.alters_data = True``.273 """274 return not (275 getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)276 )277284 def call_binop(self, context, operator, left, right):278 def call_binop(279 self, context: Context, operator: str, left: t.Any, right: t.Any280 ) -> t.Any:281 """For intercepted binary operator calls (:meth:`intercepted_binops`)282 this function is executed instead of the builtin operator. This can283 be used to fine tune the behavior of certain operators.284285 .. versionadded:: 2.6286 """287 return self.binop_table[operator](left, right)288293 def call_unop(self, context, operator, arg):289 def call_unop(self, context: Context, operator: str, arg: t.Any) -> t.Any:290 """For intercepted unary operator calls (:meth:`intercepted_unops`)291 this function is executed instead of the builtin operator. This can292 be used to fine tune the behavior of certain operators.293294 .. versionadded:: 2.6295 """296 return self.unop_table[operator](arg)297302 def getitem(self, obj, argument):298 def getitem(299 self, obj: t.Any, argument: t.Union[str, t.Any]300 ) -> t.Union[t.Any, Undefined]:301 """Subscribe an object from sandboxed code."""302 try:303 return obj[argument]304 except (TypeError, LookupError):
12 unmodified lines
317 return value318 return self.unsafe_undefined(obj, argument)319 return self.undefined(obj=obj, name=argument)320323 def getattr(self, obj, attribute):321 def getattr(self, obj: t.Any, attribute: str) -> t.Union[t.Any, Undefined]:322 """Subscribe an object from sandboxed code and prefer the323 attribute. The attribute passed *must* be a bytestring.324 """325 try:
8 unmodified lines
334 return value335 return self.unsafe_undefined(obj, attribute)336 return self.undefined(obj=obj, name=attribute)337340 def unsafe_undefined(self, obj, attribute):338 def unsafe_undefined(self, obj: t.Any, attribute: str) -> Undefined:339 """Return an undefined object for unsafe attributes."""340 return self.undefined(341 f"access to attribute {attribute!r} of"344 f" {obj.__class__.__name__!r} object is unsafe.",342 f" {type(obj).__name__!r} object is unsafe.",343 name=attribute,344 obj=obj,345 exc=SecurityError,346 )347350 def format_string(self, s, args, kwargs, format_func=None):348 def format_string(349 self,350 s: str,351 args: t.Tuple[t.Any, ...],352 kwargs: t.Dict[str, t.Any],353 format_func: t.Optional[t.Callable] = None,354 ) -> str:355 """If a format call is detected, then this is routed through this356 method so that our safety sandbox can be used for it.357 """358 formatter: SandboxedFormatter359 if isinstance(s, Markup):355 formatter = SandboxedEscapeFormatter(self, s.escape)360 formatter = SandboxedEscapeFormatter(self, escape=s.escape)361 else:362 formatter = SandboxedFormatter(self)363364 if format_func is not None and format_func.__name__ == "format_map":
3 unmodified lines
368 f" {len(args) + (kwargs is not None)} given"369 )370371 kwargs = args[0]367 args = None372 args = ()373374 rv = formatter.vformat(s, args, kwargs)375 return type(s)(rv)376372 def call(__self, __context, __obj, *args, **kwargs): # noqa: B902377 def call(378 __self, # noqa: B902379 __context: Context,380 __obj: t.Any,381 *args: t.Any,382 **kwargs: t.Any,383 ) -> t.Any:384 """Call an object from sandboxed code."""385 fmt = inspect_format_method(__obj)386 if fmt is not None:387 return __self.format_string(fmt, args, kwargs, __obj)
10 unmodified lines
398 permit modifications on the builtin mutable objects `list`, `set`, and399 `dict` by using the :func:`modifies_known_mutable` function.400 """401391 def is_safe_attribute(self, obj, attr, value):392 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):402 def is_safe_attribute(self, obj: t.Any, attr: str, value: t.Any) -> bool:403 if not super().is_safe_attribute(obj, attr, value):404 return False405406 return not modifies_known_mutable(obj, attr)407408397class SandboxedFormatterMixin:398 def __init__(self, env):409class SandboxedFormatter(Formatter):410 def __init__(self, env: Environment, **kwargs: t.Any) -> None:411 self._env = env412 super().__init__(**kwargs) # type: ignore413401 def get_field(self, field_name, args, kwargs):414 def get_field(415 self, field_name: str, args: t.Sequence[t.Any], kwargs: t.Mapping[str, t.Any]416 ) -> t.Tuple[t.Any, str]:417 first, rest = formatter_field_name_split(field_name)418 obj = self.get_value(first, args, kwargs)419 for is_attr, i in rest:420 if is_attr:
2 unmodified lines
423 obj = self._env.getitem(obj, i)424 return obj, first425426412class SandboxedFormatter(SandboxedFormatterMixin, Formatter):413 def __init__(self, env):414 SandboxedFormatterMixin.__init__(self, env)415 Formatter.__init__(self)416417418class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):419 def __init__(self, env, escape):420 SandboxedFormatterMixin.__init__(self, env)421 EscapeFormatter.__init__(self, escape)427class SandboxedEscapeFormatter(SandboxedFormatter, EscapeFormatter):428 pass
modified:src/jinja2/utils.py+88 added-90 removed
12 unmodified lines
13from urllib.parse import quote_from_bytes1415import markupsafe1617if t.TYPE_CHECKING:18 F = t.TypeVar("F", bound=t.Callable[..., t.Any])17F = t.TypeVar("F", bound=t.Callable[..., t.Any])1819# special singleton representing missing values for the runtime21missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()20missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()2122internal_code: t.MutableSet[CodeType] = set()2324concat = "".join252628def pass_context(f: "F") -> "F":27def pass_context(f: F) -> F:28 """Pass the :class:`~jinja2.runtime.Context` as the first argument29 to the decorated function when called while rendering a template.3031 Can be used on functions, filters, and tests.
8 unmodified lines
40 f.jinja_pass_arg = _PassArg.context # type: ignore41 return f424345def pass_eval_context(f: "F") -> "F":44def pass_eval_context(f: F) -> F:45 """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument46 to the decorated function when called while rendering a template.47 See :ref:`eval-context`.48
8 unmodified lines
57 f.jinja_pass_arg = _PassArg.eval_context # type: ignore58 return f596062def pass_environment(f: "F") -> "F":61def pass_environment(f: F) -> F:62 """Pass the :class:`~jinja2.Environment` as the first argument to63 the decorated function when called while rendering a template.6465 Can be used on functions, filters, and tests.
10 unmodified lines
76 eval_context = enum.auto()77 environment = enum.auto()7879 @classmethod81 def from_obj(cls, obj):80 def from_obj(cls, obj: F) -> t.Optional["_PassArg"]:81 if hasattr(obj, "jinja_pass_arg"):83 return obj.jinja_pass_arg82 return obj.jinja_pass_arg # type: ignore8384 for prefix in "context", "eval_context", "environment":85 squashed = prefix.replace("_", "")86
6 unmodified lines
93 stacklevel=2,94 )95 return cls[prefix]9697 return None989999def contextfunction(f):100def contextfunction(f: F) -> F:101 """Pass the context as the first argument to the decorated function.102103 .. deprecated:: 3.0104 Will be removed in Jinja 3.1. Use :func:`~jinja2.pass_context`
7 unmodified lines
112 )113 return pass_context(f)114115115def evalcontextfunction(f):116def evalcontextfunction(f: F) -> F:117 """Pass the eval context as the first argument to the decorated118 function.119120 .. deprecated:: 3.0
10 unmodified lines
131 )132 return pass_eval_context(f)133134134def environmentfunction(f):135def environmentfunction(f: F) -> F:136 """Pass the environment as the first argument to the decorated137 function.138139 .. deprecated:: 3.0
8 unmodified lines
148 )149 return pass_environment(f)150151151def internalcode(f):152def internalcode(f: F) -> F:153 """Marks the function as internally used"""154 internal_code.add(f.__code__)155 return f156157157def is_undefined(obj):158def is_undefined(obj: t.Any) -> bool:159 """Check if the object passed is undefined. This does nothing more than160 performing an instance check against :class:`Undefined` but looks nicer.161 This can be used for custom filters or tests that want to react to162 undefined variables. For example a custom default filter can look like
8 unmodified lines
171172 return isinstance(obj, Undefined)173174174def consume(iterable):175def consume(iterable: t.Iterable[t.Any]) -> None:176 """Consumes an iterable without doing anything with it."""177 for _ in iterable:178 pass179180180def clear_caches():181def clear_caches() -> None:182 """Jinja keeps internal caches for environments and lexers. These are183 used so that Jinja doesn't have to recreate environments and lexers all184 the time. Normally you don't have to care about that but if you are185 measuring memory consumption you may want to clean the caches.186 """186 from .environment import _spontaneous_environments187 from .environment import get_spontaneous_environment188 from .lexer import _lexer_cache189189 _spontaneous_environments.clear()190 get_spontaneous_environment.cache_clear()191 _lexer_cache.clear()192193193def import_string(import_name, silent=False):194def import_string(import_name: str, silent: bool = False) -> t.Any:195 """Imports an object based on a string. This is useful if you want to196 use import paths as endpoints or something similar. An import path can197 be specified either in dotted notation (``xml.sax.saxutils.escape``)198 or with a colon as object delimiter (``xml.sax.saxutils:escape``).
15 unmodified lines
214 if not silent:215 raise216217217def open_if_exists(filename, mode="rb"):218def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:219 """Returns a file descriptor for the filename if that file exists,220 otherwise ``None``.221 """222 if not os.path.isfile(filename):
1 unmodified line
224225 return open(filename, mode)226227227def object_type_repr(obj):228def object_type_repr(obj: t.Any) -> str:229 """Returns the name of the object's type. For some recognized230 singletons the name of the object is returned instead. (For231 example for `None` and `Ellipsis`).232 """
9 unmodified lines
242243 return f"{cls.__module__}.{cls.__name__} object"244245245def pformat(obj):246def pformat(obj: t.Any) -> str:247 """Format an object using :func:`pprint.pformat`."""247 from pprint import pformat248 from pprint import pformat # type: ignore249250 return pformat(obj)251252
67 unmodified lines
320 parentheses and brackets in more cases.321 """322 if trim_url_limit is not None:323323 def trim_url(x):324 if len(x) > trim_url_limit:324 def trim_url(x: str) -> str:325 if len(x) > trim_url_limit: # type: ignore326 return f"{x[:trim_url_limit]}..."327328 return x329330 else:331331 def trim_url(x):332 def trim_url(x: str) -> str:333 return x334335 words = re.split(r"(\s+)", str(markupsafe.escape(text)))336 rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else ""
64 unmodified lines
401402 return "".join(words)403404404def generate_lorem_ipsum(n=5, html=True, min=20, max=100):405def generate_lorem_ipsum(406 n: int = 5, html: bool = True, min: int = 20, max: int = 100407) -> str:408 """Generate some lorem ipsum for the template."""409 from .constants import LOREM_IPSUM_WORDS410411 words = LOREM_IPSUM_WORDS.split()
28 unmodified lines
440 next_capitalized = True441 p.append(word)442443 # ensure that the paragraph ends with a dot.441 p = " ".join(p)442 if p.endswith(","):443 p = p[:-1] + "."444 elif not p.endswith("."):445 p += "."446 result.append(p)444 p_str = " ".join(p)445446 if p_str.endswith(","):447 p_str = p_str[:-1] + "."448 elif not p_str.endswith("."):449 p_str += "."450451 result.append(p_str)452453 if not html:454 return "\n\n".join(result)455 return markupsafe.Markup(456 "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result)
22 unmodified lines
479480 return rv481482478def unicode_urlencode(obj, charset="utf-8", for_qs=False):483def unicode_urlencode(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str:484 import warnings485486 warnings.warn(487 "'unicode_urlencode' has been renamed to 'url_quote'. The old"
11 unmodified lines
499 # this is fast for small capacities (something below 1000) but doesn't500 # scale. But as long as it's only used as storage for templates this501 # won't do any harm.502498 def __init__(self, capacity):503 def __init__(self, capacity: int) -> None:504 self.capacity = capacity500 self._mapping = {}501 self._queue = deque()505 self._mapping: t.Dict[t.Any, t.Any] = {}506 self._queue: t.Deque[t.Any] = deque()507 self._postinit()508504 def _postinit(self):509 def _postinit(self) -> None:510 # alias all queue methods for faster lookup511 self._popleft = self._queue.popleft512 self._pop = self._queue.pop513 self._remove = self._queue.remove514 self._wlock = Lock()515 self._append = self._queue.append516512 def __getstate__(self):517 def __getstate__(self) -> t.Mapping[str, t.Any]:518 return {519 "capacity": self.capacity,520 "_mapping": self._mapping,521 "_queue": self._queue,522 }523519 def __setstate__(self, d):524 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:525 self.__dict__.update(d)526 self._postinit()527523 def __getnewargs__(self):528 def __getnewargs__(self) -> t.Tuple:529 return (self.capacity,)530526 def copy(self):531 def copy(self) -> "LRUCache":532 """Return a shallow copy of the instance."""533 rv = self.__class__(self.capacity)534 rv._mapping.update(self._mapping)535 rv._queue.extend(self._queue)536 return rv537533 def get(self, key, default=None):538 def get(self, key: t.Any, default: t.Any = None) -> t.Any:539 """Return an item from the cache dict or `default`"""540 try:541 return self[key]542 except KeyError:543 return default544540 def setdefault(self, key, default=None):545 def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any:546 """Set `default` if the key is not in the cache otherwise547 leave unchanged. Return the value of this key.548 """549 try:
1 unmodified line
551 except KeyError:552 self[key] = default553 return default554550 def clear(self):555 def clear(self) -> None:556 """Clear the cache."""552 self._wlock.acquire()553 try:557 with self._wlock:558 self._mapping.clear()559 self._queue.clear()556 finally:557 self._wlock.release()560559 def __contains__(self, key):561 def __contains__(self, key: t.Any) -> bool:562 """Check if a key exists in this cache."""563 return key in self._mapping564563 def __len__(self):565 def __len__(self) -> int:566 """Return the current size of the cache."""567 return len(self._mapping)568567 def __repr__(self):568 return f"<{self.__class__.__name__} {self._mapping!r}>"569 def __repr__(self) -> str:570 return f"<{type(self).__name__} {self._mapping!r}>"571570 def __getitem__(self, key):572 def __getitem__(self, key: t.Any) -> t.Any:573 """Get an item from the cache. Moves the item up so that it has the574 highest priority then.575576 Raise a `KeyError` if it does not exist.577 """576 self._wlock.acquire()577 try:578 with self._wlock:579 rv = self._mapping[key]580581 if self._queue[-1] != key:582 try:583 self._remove(key)584 except ValueError:585 # if something removed the key from the container586 # when we read, ignore the ValueError that we would587 # get otherwise.588 pass589590 self._append(key)591592 return rv589 finally:590 self._wlock.release()593592 def __setitem__(self, key, value):594 def __setitem__(self, key: t.Any, value: t.Any) -> None:595 """Sets the value for an item. Moves the item up so that it596 has the highest priority then.597 """596 self._wlock.acquire()597 try:598 with self._wlock:599 if key in self._mapping:600 self._remove(key)601 elif len(self._mapping) == self.capacity:602 del self._mapping[self._popleft()]603604 self._append(key)605 self._mapping[key] = value604 finally:605 self._wlock.release()606607 def __delitem__(self, key):607 def __delitem__(self, key: t.Any) -> None:608 """Remove an item from the cache dict.609 Raise a `KeyError` if it does not exist.610 """611 self._wlock.acquire()612 try:611 with self._wlock:612 del self._mapping[key]613614 try:615 self._remove(key)616 except ValueError:617 pass618 finally:619 self._wlock.release()618621 def items(self):619 def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]:620 """Return a list of items."""621 result = [(key, self._mapping[key]) for key in list(self._queue)]622 result.reverse()623 return result624627 def values(self):625 def values(self) -> t.Iterable[t.Any]:626 """Return a list of all values."""627 return [x[1] for x in self.items()]628631 def keys(self):629 def keys(self) -> t.Iterable[t.Any]:630 """Return a list of all keys ordered by most recent usage."""631 return list(self)632635 def __iter__(self):633 def __iter__(self) -> t.Iterator[t.Any]:634 return reversed(tuple(self._queue))635638 def __reversed__(self):636 def __reversed__(self) -> t.Iterator[t.Any]:637 """Iterate over the keys in the cache dict, oldest items638 coming first.639 """640 return iter(tuple(self._queue))
1 unmodified line
642 __copy__ = copy643644645def select_autoescape(648 enabled_extensions=("html", "htm", "xml"),649 disabled_extensions=(),650 default_for_string=True,651 default=False,652):646 enabled_extensions: t.Collection[str] = ("html", "htm", "xml"),647 disabled_extensions: t.Collection[str] = (),648 default_for_string: bool = True,649 default: bool = False,650) -> t.Callable[[t.Optional[str]], bool]:651 """Intelligently sets the initial value of autoescaping based on the652 filename of the template. This is the recommended way to configure653 autoescaping if you do not want to write a custom function yourself.654
29 unmodified lines
684 """685 enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)686 disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)687690 def autoescape(template_name):688 def autoescape(template_name: t.Optional[str]) -> bool:689 if template_name is None:690 return default_for_string691 template_name = template_name.lower()692 if template_name.endswith(enabled_patterns):
70 unmodified lines
763764 .. versionadded:: 2.1765 """766769 def __init__(self, *items):767 def __init__(self, *items: t.Any) -> None:768 if not items:769 raise RuntimeError("at least one item has to be provided")770 self.items = items771 self.pos = 0772775 def reset(self):773 def reset(self) -> None:774 """Resets the current item to the first item."""775 self.pos = 0776777 @property780 def current(self):778 def current(self) -> t.Any:779 """Return the current item. Equivalent to the item that will be780 returned next time :meth:`next` is called.781 """782 return self.items[self.pos]783786 def next(self):784 def next(self) -> t.Any:785 """Return the current item, then advance :attr:`current` to the786 next item.787 """788 rv = self.current
5 unmodified lines
794795class Joiner:796 """A joining helper for templates."""797800 def __init__(self, sep=", "):798 def __init__(self, sep: str = ", ") -> None:799 self.sep = sep800 self.used = False801804 def __call__(self):802 def __call__(self) -> str:803 if not self.used:804 self.used = True805 return ""806 return self.sep
2 unmodified lines
809class Namespace:810 """A namespace object that can hold arbitrary attributes. It may be811 initialized from a dictionary or with keyword arguments."""812815 def __init__(*args, **kwargs): # noqa: B902813 def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902814 self, args = args[0], args[1:]815 self.__attrs = dict(*args, **kwargs)816819 def __getattribute__(self, name):817 def __getattribute__(self, name: str) -> t.Any:818 # __class__ is needed for the awaitable check in async mode819 if name in {"_Namespace__attrs", "__class__"}:820 return object.__getattribute__(self, name)821 try:822 return self.__attrs[name]823 except KeyError:824 raise AttributeError(name)825828 def __setitem__(self, name, value):826 def __setitem__(self, name: str, value: t.Any) -> None:827 self.__attrs[name] = value828831 def __repr__(self):829 def __repr__(self) -> str:830 return f"<Namespace {self.__attrs!r}>"831832833class Markup(markupsafe.Markup):836 def __new__(cls, base, encoding=None, errors="strict"):834 def __new__(cls, base, encoding=None, errors="strict"): # type: ignore835 warnings.warn(836 "'jinja2.Markup' is deprecated and will be removed in Jinja"837 " 3.1. Import 'markupsafe.Markup' instead.",838 DeprecationWarning,
1 unmodified line
840 )841 return super().__new__(cls, base, encoding, errors)842843846def escape(s):844def escape(s: t.Any) -> str:845 warnings.warn(846 "'jinja2.escape' is deprecated and will be removed in Jinja"847 " 3.1. Import 'markupsafe.escape' instead.",848 DeprecationWarning,
3 unmodified lines
modified:src/jinja2/visitor.py+20 added-7 removed
1"""API for traversing the AST nodes. Implemented by the compiler and2meta introspection.3"""4import typing as t56from .nodes import Node78if t.TYPE_CHECKING:9 import typing_extensions as te1011 class VisitCallable(te.Protocol):12 def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:13 ...141516class NodeVisitor:17 """Walks the abstract syntax tree and call visitor functions for every18 node found. The visitor functions may return values which will be19 forwarded by the `visit` method.
4 unmodified lines
24 the `get_visitor` function. If no visitor function exists for a node25 (return value `None`) the `generic_visit` visitor is used instead.26 """2719 def get_visitor(self, node):28 def get_visitor(self, node: Node) -> "t.Optional[VisitCallable]":29 """Return the visitor function for this node or `None` if no visitor30 exists for this node. In that case the generic visit function is31 used instead.32 """24 return getattr(self, f"visit_{node.__class__.__name__}", None)33 return getattr(self, f"visit_{type(node).__name__}", None) # type: ignore3426 def visit(self, node, *args, **kwargs):35 def visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:36 """Visit a node."""37 f = self.get_visitor(node)3839 if f is not None:40 return f(node, *args, **kwargs)4142 return self.generic_visit(node, *args, **kwargs)4333 def generic_visit(self, node, *args, **kwargs):44 def generic_visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:45 """Called if no explicit visitor function exists for a node."""46 for node in node.iter_child_nodes():47 self.visit(node, *args, **kwargs)48
8 unmodified lines
57 value. The return value may be the original node in which case no58 replacement takes place.59 """6050 def generic_visit(self, node, *args, **kwargs):61 def generic_visit(self, node: Node, *args: t.Any, **kwargs: t.Any) -> Node:62 for field, old_value in node.iter_fields():63 if isinstance(old_value, list):64 new_values = []65 for value in old_value:
13 unmodified lines
79 else:80 setattr(node, field, new_node)81 return node8272 def visit_list(self, node, *args, **kwargs):83 def visit_list(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.List[Node]:84 """As transformers may return lists in some places this method85 can be used to enforce a list as return value.86 """87 rv = self.visit(node, *args, **kwargs)8889 if not isinstance(rv, list):78 rv = [rv]90 return [rv]9192 return rv
modified:tests/test_ext.py+1 added-1 removed
191 unmodified lines
192 def interpolate(self, token):193 pos = 0194 end = len(token.value)195 lineno = token.lineno196 while 1:196 while True:197 match = _gettext_re.search(token.value, pos)198 if match is None:199 break200 value = token.value[pos : match.start()]
514 unmodified lines
modified:CHANGES.rst+1 added
7 unmodified lines
8- Drop support for Python 2.7 and 3.5.9- Bump MarkupSafe dependency to >=1.1.10- Bump Babel optional dependency to >=2.1.11- Remove code that was marked deprecated.12- Add type hinting. :pr:`1412`13- Use :pep:`451` API to load templates with14 :class:`~loaders.PackageLoader`. :issue:`1168`15- Fix a bug that caused imported macros to not have access to the16 current template's globals. :issue:`688`
846 unmodified lines
modified:MANIFEST.in+1 added
4 unmodified lines
5graft docs6prune docs/_build7graft examples8graft tests9include src/click/py.typed10global-exclude *.pyc
modified:setup.cfg+9 added-3 removed
84 unmodified lines
85[mypy]86files = src/jinja287python_version = 3.688disallow_subclassing_any = True89# disallow_untyped_calls = True90# disallow_untyped_defs = True89disallow_untyped_calls = True90disallow_untyped_defs = True91disallow_incomplete_defs = True92no_implicit_optional = True93local_partial_types = True94# no_implicit_reexport = True94no_implicit_reexport = True95strict_equality = True96warn_redundant_casts = True97warn_unused_configs = True98warn_unused_ignores = True99warn_return_any = True100warn_unreachable = True101102[mypy-jinja2.defaults]103no_implicit_reexport = False104105[mypy-markupsafe]106no_implicit_reexport = False