You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1206 lines
34KB

  1. """AST nodes generated by the parser for the compiler. Also provides
  2. some node tree helper functions used by the parser and compiler in order
  3. to normalize nodes.
  4. """
  5. import inspect
  6. import operator
  7. import typing as t
  8. from collections import deque
  9. from markupsafe import Markup
  10. from .utils import _PassArg
  11. if t.TYPE_CHECKING:
  12. import typing_extensions as te
  13. from .environment import Environment
  14. _NodeBound = t.TypeVar("_NodeBound", bound="Node")
  15. _binop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
  16. "*": operator.mul,
  17. "/": operator.truediv,
  18. "//": operator.floordiv,
  19. "**": operator.pow,
  20. "%": operator.mod,
  21. "+": operator.add,
  22. "-": operator.sub,
  23. }
  24. _uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] = {
  25. "not": operator.not_,
  26. "+": operator.pos,
  27. "-": operator.neg,
  28. }
  29. _cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = {
  30. "eq": operator.eq,
  31. "ne": operator.ne,
  32. "gt": operator.gt,
  33. "gteq": operator.ge,
  34. "lt": operator.lt,
  35. "lteq": operator.le,
  36. "in": lambda a, b: a in b,
  37. "notin": lambda a, b: a not in b,
  38. }
  39. class Impossible(Exception):
  40. """Raised if the node could not perform a requested action."""
  41. class NodeType(type):
  42. """A metaclass for nodes that handles the field and attribute
  43. inheritance. fields and attributes from the parent class are
  44. automatically forwarded to the child."""
  45. def __new__(mcs, name, bases, d): # type: ignore
  46. for attr in "fields", "attributes":
  47. storage = []
  48. storage.extend(getattr(bases[0] if bases else object, attr, ()))
  49. storage.extend(d.get(attr, ()))
  50. assert len(bases) <= 1, "multiple inheritance not allowed"
  51. assert len(storage) == len(set(storage)), "layout conflict"
  52. d[attr] = tuple(storage)
  53. d.setdefault("abstract", False)
  54. return type.__new__(mcs, name, bases, d)
  55. class EvalContext:
  56. """Holds evaluation time information. Custom attributes can be attached
  57. to it in extensions.
  58. """
  59. def __init__(
  60. self, environment: "Environment", template_name: t.Optional[str] = None
  61. ) -> None:
  62. self.environment = environment
  63. if callable(environment.autoescape):
  64. self.autoescape = environment.autoescape(template_name)
  65. else:
  66. self.autoescape = environment.autoescape
  67. self.volatile = False
  68. def save(self) -> t.Mapping[str, t.Any]:
  69. return self.__dict__.copy()
  70. def revert(self, old: t.Mapping[str, t.Any]) -> None:
  71. self.__dict__.clear()
  72. self.__dict__.update(old)
  73. def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext:
  74. if ctx is None:
  75. if node.environment is None:
  76. raise RuntimeError(
  77. "if no eval context is passed, the node must have an"
  78. " attached environment."
  79. )
  80. return EvalContext(node.environment)
  81. return ctx
  82. class Node(metaclass=NodeType):
  83. """Baseclass for all Jinja nodes. There are a number of nodes available
  84. of different types. There are four major types:
  85. - :class:`Stmt`: statements
  86. - :class:`Expr`: expressions
  87. - :class:`Helper`: helper nodes
  88. - :class:`Template`: the outermost wrapper node
  89. All nodes have fields and attributes. Fields may be other nodes, lists,
  90. or arbitrary values. Fields are passed to the constructor as regular
  91. positional arguments, attributes as keyword arguments. Each node has
  92. two attributes: `lineno` (the line number of the node) and `environment`.
  93. The `environment` attribute is set at the end of the parsing process for
  94. all nodes automatically.
  95. """
  96. fields: t.Tuple[str, ...] = ()
  97. attributes: t.Tuple[str, ...] = ("lineno", "environment")
  98. abstract = True
  99. lineno: int
  100. environment: t.Optional["Environment"]
  101. def __init__(self, *fields: t.Any, **attributes: t.Any) -> None:
  102. if self.abstract:
  103. raise TypeError("abstract nodes are not instantiable")
  104. if fields:
  105. if len(fields) != len(self.fields):
  106. if not self.fields:
  107. raise TypeError(f"{type(self).__name__!r} takes 0 arguments")
  108. raise TypeError(
  109. f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
  110. f" argument{'s' if len(self.fields) != 1 else ''}"
  111. )
  112. for name, arg in zip(self.fields, fields):
  113. setattr(self, name, arg)
  114. for attr in self.attributes:
  115. setattr(self, attr, attributes.pop(attr, None))
  116. if attributes:
  117. raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
  118. def iter_fields(
  119. self,
  120. exclude: t.Optional[t.Container[str]] = None,
  121. only: t.Optional[t.Container[str]] = None,
  122. ) -> t.Iterator[t.Tuple[str, t.Any]]:
  123. """This method iterates over all fields that are defined and yields
  124. ``(key, value)`` tuples. Per default all fields are returned, but
  125. it's possible to limit that to some fields by providing the `only`
  126. parameter or to exclude some using the `exclude` parameter. Both
  127. should be sets or tuples of field names.
  128. """
  129. for name in self.fields:
  130. if (
  131. (exclude is None and only is None)
  132. or (exclude is not None and name not in exclude)
  133. or (only is not None and name in only)
  134. ):
  135. try:
  136. yield name, getattr(self, name)
  137. except AttributeError:
  138. pass
  139. def iter_child_nodes(
  140. self,
  141. exclude: t.Optional[t.Container[str]] = None,
  142. only: t.Optional[t.Container[str]] = None,
  143. ) -> t.Iterator["Node"]:
  144. """Iterates over all direct child nodes of the node. This iterates
  145. over all fields and yields the values of they are nodes. If the value
  146. of a field is a list all the nodes in that list are returned.
  147. """
  148. for _, item in self.iter_fields(exclude, only):
  149. if isinstance(item, list):
  150. for n in item:
  151. if isinstance(n, Node):
  152. yield n
  153. elif isinstance(item, Node):
  154. yield item
  155. def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
  156. """Find the first node of a given type. If no such node exists the
  157. return value is `None`.
  158. """
  159. for result in self.find_all(node_type):
  160. return result
  161. return None
  162. def find_all(
  163. self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
  164. ) -> t.Iterator[_NodeBound]:
  165. """Find all the nodes of a given type. If the type is a tuple,
  166. the check is performed for any of the tuple items.
  167. """
  168. for child in self.iter_child_nodes():
  169. if isinstance(child, node_type):
  170. yield child # type: ignore
  171. yield from child.find_all(node_type)
  172. def set_ctx(self, ctx: str) -> "Node":
  173. """Reset the context of a node and all child nodes. Per default the
  174. parser will all generate nodes that have a 'load' context as it's the
  175. most common one. This method is used in the parser to set assignment
  176. targets and other nodes to a store context.
  177. """
  178. todo = deque([self])
  179. while todo:
  180. node = todo.popleft()
  181. if "ctx" in node.fields:
  182. node.ctx = ctx # type: ignore
  183. todo.extend(node.iter_child_nodes())
  184. return self
  185. def set_lineno(self, lineno: int, override: bool = False) -> "Node":
  186. """Set the line numbers of the node and children."""
  187. todo = deque([self])
  188. while todo:
  189. node = todo.popleft()
  190. if "lineno" in node.attributes:
  191. if node.lineno is None or override:
  192. node.lineno = lineno
  193. todo.extend(node.iter_child_nodes())
  194. return self
  195. def set_environment(self, environment: "Environment") -> "Node":
  196. """Set the environment for all nodes."""
  197. todo = deque([self])
  198. while todo:
  199. node = todo.popleft()
  200. node.environment = environment
  201. todo.extend(node.iter_child_nodes())
  202. return self
  203. def __eq__(self, other: t.Any) -> bool:
  204. if type(self) is not type(other):
  205. return NotImplemented
  206. return tuple(self.iter_fields()) == tuple(other.iter_fields())
  207. def __hash__(self) -> int:
  208. return hash(tuple(self.iter_fields()))
  209. def __repr__(self) -> str:
  210. args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
  211. return f"{type(self).__name__}({args_str})"
  212. def dump(self) -> str:
  213. def _dump(node: t.Union[Node, t.Any]) -> None:
  214. if not isinstance(node, Node):
  215. buf.append(repr(node))
  216. return
  217. buf.append(f"nodes.{type(node).__name__}(")
  218. if not node.fields:
  219. buf.append(")")
  220. return
  221. for idx, field in enumerate(node.fields):
  222. if idx:
  223. buf.append(", ")
  224. value = getattr(node, field)
  225. if isinstance(value, list):
  226. buf.append("[")
  227. for idx, item in enumerate(value):
  228. if idx:
  229. buf.append(", ")
  230. _dump(item)
  231. buf.append("]")
  232. else:
  233. _dump(value)
  234. buf.append(")")
  235. buf: t.List[str] = []
  236. _dump(self)
  237. return "".join(buf)
  238. class Stmt(Node):
  239. """Base node for all statements."""
  240. abstract = True
  241. class Helper(Node):
  242. """Nodes that exist in a specific context only."""
  243. abstract = True
  244. class Template(Node):
  245. """Node that represents a template. This must be the outermost node that
  246. is passed to the compiler.
  247. """
  248. fields = ("body",)
  249. body: t.List[Node]
  250. class Output(Stmt):
  251. """A node that holds multiple expressions which are then printed out.
  252. This is used both for the `print` statement and the regular template data.
  253. """
  254. fields = ("nodes",)
  255. nodes: t.List["Expr"]
  256. class Extends(Stmt):
  257. """Represents an extends statement."""
  258. fields = ("template",)
  259. template: "Expr"
  260. class For(Stmt):
  261. """The for loop. `target` is the target for the iteration (usually a
  262. :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
  263. of nodes that are used as loop-body, and `else_` a list of nodes for the
  264. `else` block. If no else node exists it has to be an empty list.
  265. For filtered nodes an expression can be stored as `test`, otherwise `None`.
  266. """
  267. fields = ("target", "iter", "body", "else_", "test", "recursive")
  268. target: Node
  269. iter: Node
  270. body: t.List[Node]
  271. else_: t.List[Node]
  272. test: t.Optional[Node]
  273. recursive: bool
  274. class If(Stmt):
  275. """If `test` is true, `body` is rendered, else `else_`."""
  276. fields = ("test", "body", "elif_", "else_")
  277. test: Node
  278. body: t.List[Node]
  279. elif_: t.List["If"]
  280. else_: t.List[Node]
  281. class Macro(Stmt):
  282. """A macro definition. `name` is the name of the macro, `args` a list of
  283. arguments and `defaults` a list of defaults if there are any. `body` is
  284. a list of nodes for the macro body.
  285. """
  286. fields = ("name", "args", "defaults", "body")
  287. name: str
  288. args: t.List["Name"]
  289. defaults: t.List["Expr"]
  290. body: t.List[Node]
  291. class CallBlock(Stmt):
  292. """Like a macro without a name but a call instead. `call` is called with
  293. the unnamed macro as `caller` argument this node holds.
  294. """
  295. fields = ("call", "args", "defaults", "body")
  296. call: "Call"
  297. args: t.List["Name"]
  298. defaults: t.List["Expr"]
  299. body: t.List[Node]
  300. class FilterBlock(Stmt):
  301. """Node for filter sections."""
  302. fields = ("body", "filter")
  303. body: t.List[Node]
  304. filter: "Filter"
  305. class With(Stmt):
  306. """Specific node for with statements. In older versions of Jinja the
  307. with statement was implemented on the base of the `Scope` node instead.
  308. .. versionadded:: 2.9.3
  309. """
  310. fields = ("targets", "values", "body")
  311. targets: t.List["Expr"]
  312. values: t.List["Expr"]
  313. body: t.List[Node]
  314. class Block(Stmt):
  315. """A node that represents a block.
  316. .. versionchanged:: 3.0.0
  317. the `required` field was added.
  318. """
  319. fields = ("name", "body", "scoped", "required")
  320. name: str
  321. body: t.List[Node]
  322. scoped: bool
  323. required: bool
  324. class Include(Stmt):
  325. """A node that represents the include tag."""
  326. fields = ("template", "with_context", "ignore_missing")
  327. template: "Expr"
  328. with_context: bool
  329. ignore_missing: bool
  330. class Import(Stmt):
  331. """A node that represents the import tag."""
  332. fields = ("template", "target", "with_context")
  333. template: "Expr"
  334. target: str
  335. with_context: bool
  336. class FromImport(Stmt):
  337. """A node that represents the from import tag. It's important to not
  338. pass unsafe names to the name attribute. The compiler translates the
  339. attribute lookups directly into getattr calls and does *not* use the
  340. subscript callback of the interface. As exported variables may not
  341. start with double underscores (which the parser asserts) this is not a
  342. problem for regular Jinja code, but if this node is used in an extension
  343. extra care must be taken.
  344. The list of names may contain tuples if aliases are wanted.
  345. """
  346. fields = ("template", "names", "with_context")
  347. template: "Expr"
  348. names: t.List[t.Union[str, t.Tuple[str, str]]]
  349. with_context: bool
  350. class ExprStmt(Stmt):
  351. """A statement that evaluates an expression and discards the result."""
  352. fields = ("node",)
  353. node: Node
  354. class Assign(Stmt):
  355. """Assigns an expression to a target."""
  356. fields = ("target", "node")
  357. target: "Expr"
  358. node: Node
  359. class AssignBlock(Stmt):
  360. """Assigns a block to a target."""
  361. fields = ("target", "filter", "body")
  362. target: "Expr"
  363. filter: t.Optional["Filter"]
  364. body: t.List[Node]
  365. class Expr(Node):
  366. """Baseclass for all expressions."""
  367. abstract = True
  368. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  369. """Return the value of the expression as constant or raise
  370. :exc:`Impossible` if this was not possible.
  371. An :class:`EvalContext` can be provided, if none is given
  372. a default context is created which requires the nodes to have
  373. an attached environment.
  374. .. versionchanged:: 2.4
  375. the `eval_ctx` parameter was added.
  376. """
  377. raise Impossible()
  378. def can_assign(self) -> bool:
  379. """Check if it's possible to assign something to this node."""
  380. return False
  381. class BinExpr(Expr):
  382. """Baseclass for all binary expressions."""
  383. fields = ("left", "right")
  384. left: Expr
  385. right: Expr
  386. operator: str
  387. abstract = True
  388. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  389. eval_ctx = get_eval_context(self, eval_ctx)
  390. # intercepted operators cannot be folded at compile time
  391. if (
  392. eval_ctx.environment.sandboxed
  393. and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
  394. ):
  395. raise Impossible()
  396. f = _binop_to_func[self.operator]
  397. try:
  398. return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
  399. except Exception:
  400. raise Impossible()
  401. class UnaryExpr(Expr):
  402. """Baseclass for all unary expressions."""
  403. fields = ("node",)
  404. node: Expr
  405. operator: str
  406. abstract = True
  407. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  408. eval_ctx = get_eval_context(self, eval_ctx)
  409. # intercepted operators cannot be folded at compile time
  410. if (
  411. eval_ctx.environment.sandboxed
  412. and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
  413. ):
  414. raise Impossible()
  415. f = _uaop_to_func[self.operator]
  416. try:
  417. return f(self.node.as_const(eval_ctx))
  418. except Exception:
  419. raise Impossible()
  420. class Name(Expr):
  421. """Looks up a name or stores a value in a name.
  422. The `ctx` of the node can be one of the following values:
  423. - `store`: store a value in the name
  424. - `load`: load that name
  425. - `param`: like `store` but if the name was defined as function parameter.
  426. """
  427. fields = ("name", "ctx")
  428. name: str
  429. ctx: str
  430. def can_assign(self) -> bool:
  431. return self.name not in {"true", "false", "none", "True", "False", "None"}
  432. class NSRef(Expr):
  433. """Reference to a namespace value assignment"""
  434. fields = ("name", "attr")
  435. name: str
  436. attr: str
  437. def can_assign(self) -> bool:
  438. # We don't need any special checks here; NSRef assignments have a
  439. # runtime check to ensure the target is a namespace object which will
  440. # have been checked already as it is created using a normal assignment
  441. # which goes through a `Name` node.
  442. return True
  443. class Literal(Expr):
  444. """Baseclass for literals."""
  445. abstract = True
  446. class Const(Literal):
  447. """All constant values. The parser will return this node for simple
  448. constants such as ``42`` or ``"foo"`` but it can be used to store more
  449. complex values such as lists too. Only constants with a safe
  450. representation (objects where ``eval(repr(x)) == x`` is true).
  451. """
  452. fields = ("value",)
  453. value: t.Any
  454. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  455. return self.value
  456. @classmethod
  457. def from_untrusted(
  458. cls,
  459. value: t.Any,
  460. lineno: t.Optional[int] = None,
  461. environment: "t.Optional[Environment]" = None,
  462. ) -> "Const":
  463. """Return a const object if the value is representable as
  464. constant value in the generated code, otherwise it will raise
  465. an `Impossible` exception.
  466. """
  467. from .compiler import has_safe_repr
  468. if not has_safe_repr(value):
  469. raise Impossible()
  470. return cls(value, lineno=lineno, environment=environment)
  471. class TemplateData(Literal):
  472. """A constant template string."""
  473. fields = ("data",)
  474. data: str
  475. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
  476. eval_ctx = get_eval_context(self, eval_ctx)
  477. if eval_ctx.volatile:
  478. raise Impossible()
  479. if eval_ctx.autoescape:
  480. return Markup(self.data)
  481. return self.data
  482. class Tuple(Literal):
  483. """For loop unpacking and some other things like multiple arguments
  484. for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
  485. is used for loading the names or storing.
  486. """
  487. fields = ("items", "ctx")
  488. items: t.List[Expr]
  489. ctx: str
  490. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:
  491. eval_ctx = get_eval_context(self, eval_ctx)
  492. return tuple(x.as_const(eval_ctx) for x in self.items)
  493. def can_assign(self) -> bool:
  494. for item in self.items:
  495. if not item.can_assign():
  496. return False
  497. return True
  498. class List(Literal):
  499. """Any list literal such as ``[1, 2, 3]``"""
  500. fields = ("items",)
  501. items: t.List[Expr]
  502. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:
  503. eval_ctx = get_eval_context(self, eval_ctx)
  504. return [x.as_const(eval_ctx) for x in self.items]
  505. class Dict(Literal):
  506. """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
  507. :class:`Pair` nodes.
  508. """
  509. fields = ("items",)
  510. items: t.List["Pair"]
  511. def as_const(
  512. self, eval_ctx: t.Optional[EvalContext] = None
  513. ) -> t.Dict[t.Any, t.Any]:
  514. eval_ctx = get_eval_context(self, eval_ctx)
  515. return dict(x.as_const(eval_ctx) for x in self.items)
  516. class Pair(Helper):
  517. """A key, value pair for dicts."""
  518. fields = ("key", "value")
  519. key: Expr
  520. value: Expr
  521. def as_const(
  522. self, eval_ctx: t.Optional[EvalContext] = None
  523. ) -> t.Tuple[t.Any, t.Any]:
  524. eval_ctx = get_eval_context(self, eval_ctx)
  525. return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
  526. class Keyword(Helper):
  527. """A key, value pair for keyword arguments where key is a string."""
  528. fields = ("key", "value")
  529. key: str
  530. value: Expr
  531. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
  532. eval_ctx = get_eval_context(self, eval_ctx)
  533. return self.key, self.value.as_const(eval_ctx)
  534. class CondExpr(Expr):
  535. """A conditional expression (inline if expression). (``{{
  536. foo if bar else baz }}``)
  537. """
  538. fields = ("test", "expr1", "expr2")
  539. test: Expr
  540. expr1: Expr
  541. expr2: t.Optional[Expr]
  542. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  543. eval_ctx = get_eval_context(self, eval_ctx)
  544. if self.test.as_const(eval_ctx):
  545. return self.expr1.as_const(eval_ctx)
  546. # if we evaluate to an undefined object, we better do that at runtime
  547. if self.expr2 is None:
  548. raise Impossible()
  549. return self.expr2.as_const(eval_ctx)
  550. def args_as_const(
  551. node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
  552. ) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
  553. args = [x.as_const(eval_ctx) for x in node.args]
  554. kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
  555. if node.dyn_args is not None:
  556. try:
  557. args.extend(node.dyn_args.as_const(eval_ctx))
  558. except Exception:
  559. raise Impossible()
  560. if node.dyn_kwargs is not None:
  561. try:
  562. kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
  563. except Exception:
  564. raise Impossible()
  565. return args, kwargs
  566. class _FilterTestCommon(Expr):
  567. fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
  568. node: Expr
  569. name: str
  570. args: t.List[Expr]
  571. kwargs: t.List[Pair]
  572. dyn_args: t.Optional[Expr]
  573. dyn_kwargs: t.Optional[Expr]
  574. abstract = True
  575. _is_filter = True
  576. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  577. eval_ctx = get_eval_context(self, eval_ctx)
  578. if eval_ctx.volatile:
  579. raise Impossible()
  580. if self._is_filter:
  581. env_map = eval_ctx.environment.filters
  582. else:
  583. env_map = eval_ctx.environment.tests
  584. func = env_map.get(self.name)
  585. pass_arg = _PassArg.from_obj(func) # type: ignore
  586. if func is None or pass_arg is _PassArg.context:
  587. raise Impossible()
  588. if eval_ctx.environment.is_async and (
  589. getattr(func, "jinja_async_variant", False) is True
  590. or inspect.iscoroutinefunction(func)
  591. ):
  592. raise Impossible()
  593. args, kwargs = args_as_const(self, eval_ctx)
  594. args.insert(0, self.node.as_const(eval_ctx))
  595. if pass_arg is _PassArg.eval_context:
  596. args.insert(0, eval_ctx)
  597. elif pass_arg is _PassArg.environment:
  598. args.insert(0, eval_ctx.environment)
  599. try:
  600. return func(*args, **kwargs)
  601. except Exception:
  602. raise Impossible()
  603. class Filter(_FilterTestCommon):
  604. """Apply a filter to an expression. ``name`` is the name of the
  605. filter, the other fields are the same as :class:`Call`.
  606. If ``node`` is ``None``, the filter is being used in a filter block
  607. and is applied to the content of the block.
  608. """
  609. node: t.Optional[Expr] # type: ignore
  610. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  611. if self.node is None:
  612. raise Impossible()
  613. return super().as_const(eval_ctx=eval_ctx)
  614. class Test(_FilterTestCommon):
  615. """Apply a test to an expression. ``name`` is the name of the test,
  616. the other field are the same as :class:`Call`.
  617. .. versionchanged:: 3.0
  618. ``as_const`` shares the same logic for filters and tests. Tests
  619. check for volatile, async, and ``@pass_context`` etc.
  620. decorators.
  621. """
  622. _is_filter = False
  623. class Call(Expr):
  624. """Calls an expression. `args` is a list of arguments, `kwargs` a list
  625. of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
  626. and `dyn_kwargs` has to be either `None` or a node that is used as
  627. node for dynamic positional (``*args``) or keyword (``**kwargs``)
  628. arguments.
  629. """
  630. fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")
  631. node: Expr
  632. args: t.List[Expr]
  633. kwargs: t.List[Keyword]
  634. dyn_args: t.Optional[Expr]
  635. dyn_kwargs: t.Optional[Expr]
  636. class Getitem(Expr):
  637. """Get an attribute or item from an expression and prefer the item."""
  638. fields = ("node", "arg", "ctx")
  639. node: Expr
  640. arg: Expr
  641. ctx: str
  642. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  643. if self.ctx != "load":
  644. raise Impossible()
  645. eval_ctx = get_eval_context(self, eval_ctx)
  646. try:
  647. return eval_ctx.environment.getitem(
  648. self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
  649. )
  650. except Exception:
  651. raise Impossible()
  652. class Getattr(Expr):
  653. """Get an attribute or item from an expression that is a ascii-only
  654. bytestring and prefer the attribute.
  655. """
  656. fields = ("node", "attr", "ctx")
  657. node: Expr
  658. attr: str
  659. ctx: str
  660. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  661. if self.ctx != "load":
  662. raise Impossible()
  663. eval_ctx = get_eval_context(self, eval_ctx)
  664. try:
  665. return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
  666. except Exception:
  667. raise Impossible()
  668. class Slice(Expr):
  669. """Represents a slice object. This must only be used as argument for
  670. :class:`Subscript`.
  671. """
  672. fields = ("start", "stop", "step")
  673. start: t.Optional[Expr]
  674. stop: t.Optional[Expr]
  675. step: t.Optional[Expr]
  676. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
  677. eval_ctx = get_eval_context(self, eval_ctx)
  678. def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
  679. if obj is None:
  680. return None
  681. return obj.as_const(eval_ctx)
  682. return slice(const(self.start), const(self.stop), const(self.step))
  683. class Concat(Expr):
  684. """Concatenates the list of expressions provided after converting
  685. them to strings.
  686. """
  687. fields = ("nodes",)
  688. nodes: t.List[Expr]
  689. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
  690. eval_ctx = get_eval_context(self, eval_ctx)
  691. return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
  692. class Compare(Expr):
  693. """Compares an expression with some other expressions. `ops` must be a
  694. list of :class:`Operand`\\s.
  695. """
  696. fields = ("expr", "ops")
  697. expr: Expr
  698. ops: t.List["Operand"]
  699. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  700. eval_ctx = get_eval_context(self, eval_ctx)
  701. result = value = self.expr.as_const(eval_ctx)
  702. try:
  703. for op in self.ops:
  704. new_value = op.expr.as_const(eval_ctx)
  705. result = _cmpop_to_func[op.op](value, new_value)
  706. if not result:
  707. return False
  708. value = new_value
  709. except Exception:
  710. raise Impossible()
  711. return result
  712. class Operand(Helper):
  713. """Holds an operator and an expression."""
  714. fields = ("op", "expr")
  715. op: str
  716. expr: Expr
  717. class Mul(BinExpr):
  718. """Multiplies the left with the right node."""
  719. operator = "*"
  720. class Div(BinExpr):
  721. """Divides the left by the right node."""
  722. operator = "/"
  723. class FloorDiv(BinExpr):
  724. """Divides the left by the right node and truncates conver the
  725. result into an integer by truncating.
  726. """
  727. operator = "//"
  728. class Add(BinExpr):
  729. """Add the left to the right node."""
  730. operator = "+"
  731. class Sub(BinExpr):
  732. """Subtract the right from the left node."""
  733. operator = "-"
  734. class Mod(BinExpr):
  735. """Left modulo right."""
  736. operator = "%"
  737. class Pow(BinExpr):
  738. """Left to the power of right."""
  739. operator = "**"
  740. class And(BinExpr):
  741. """Short circuited AND."""
  742. operator = "and"
  743. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  744. eval_ctx = get_eval_context(self, eval_ctx)
  745. return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
  746. class Or(BinExpr):
  747. """Short circuited OR."""
  748. operator = "or"
  749. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  750. eval_ctx = get_eval_context(self, eval_ctx)
  751. return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
  752. class Not(UnaryExpr):
  753. """Negate the expression."""
  754. operator = "not"
  755. class Neg(UnaryExpr):
  756. """Make the expression negative."""
  757. operator = "-"
  758. class Pos(UnaryExpr):
  759. """Make the expression positive (noop for most expressions)"""
  760. operator = "+"
  761. # Helpers for extensions
  762. class EnvironmentAttribute(Expr):
  763. """Loads an attribute from the environment object. This is useful for
  764. extensions that want to call a callback stored on the environment.
  765. """
  766. fields = ("name",)
  767. name: str
  768. class ExtensionAttribute(Expr):
  769. """Returns the attribute of an extension bound to the environment.
  770. The identifier is the identifier of the :class:`Extension`.
  771. This node is usually constructed by calling the
  772. :meth:`~jinja2.ext.Extension.attr` method on an extension.
  773. """
  774. fields = ("identifier", "name")
  775. identifier: str
  776. name: str
  777. class ImportedName(Expr):
  778. """If created with an import name the import name is returned on node
  779. access. For example ``ImportedName('cgi.escape')`` returns the `escape`
  780. function from the cgi module on evaluation. Imports are optimized by the
  781. compiler so there is no need to assign them to local variables.
  782. """
  783. fields = ("importname",)
  784. importname: str
  785. class InternalName(Expr):
  786. """An internal name in the compiler. You cannot create these nodes
  787. yourself but the parser provides a
  788. :meth:`~jinja2.parser.Parser.free_identifier` method that creates
  789. a new identifier for you. This identifier is not available from the
  790. template and is not treated specially by the compiler.
  791. """
  792. fields = ("name",)
  793. name: str
  794. def __init__(self) -> None:
  795. raise TypeError(
  796. "Can't create internal names. Use the "
  797. "`free_identifier` method on a parser."
  798. )
  799. class MarkSafe(Expr):
  800. """Mark the wrapped expression as safe (wrap it as `Markup`)."""
  801. fields = ("expr",)
  802. expr: Expr
  803. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
  804. eval_ctx = get_eval_context(self, eval_ctx)
  805. return Markup(self.expr.as_const(eval_ctx))
  806. class MarkSafeIfAutoescape(Expr):
  807. """Mark the wrapped expression as safe (wrap it as `Markup`) but
  808. only if autoescaping is active.
  809. .. versionadded:: 2.5
  810. """
  811. fields = ("expr",)
  812. expr: Expr
  813. def as_const(
  814. self, eval_ctx: t.Optional[EvalContext] = None
  815. ) -> t.Union[Markup, t.Any]:
  816. eval_ctx = get_eval_context(self, eval_ctx)
  817. if eval_ctx.volatile:
  818. raise Impossible()
  819. expr = self.expr.as_const(eval_ctx)
  820. if eval_ctx.autoescape:
  821. return Markup(expr)
  822. return expr
  823. class ContextReference(Expr):
  824. """Returns the current template context. It can be used like a
  825. :class:`Name` node, with a ``'load'`` ctx and will return the
  826. current :class:`~jinja2.runtime.Context` object.
  827. Here an example that assigns the current template name to a
  828. variable named `foo`::
  829. Assign(Name('foo', ctx='store'),
  830. Getattr(ContextReference(), 'name'))
  831. This is basically equivalent to using the
  832. :func:`~jinja2.pass_context` decorator when using the high-level
  833. API, which causes a reference to the context to be passed as the
  834. first argument to a function.
  835. """
  836. class DerivedContextReference(Expr):
  837. """Return the current template context including locals. Behaves
  838. exactly like :class:`ContextReference`, but includes local
  839. variables, such as from a ``for`` loop.
  840. .. versionadded:: 2.11
  841. """
  842. class Continue(Stmt):
  843. """Continue a loop."""
  844. class Break(Stmt):
  845. """Break a loop."""
  846. class Scope(Stmt):
  847. """An artificial scope."""
  848. fields = ("body",)
  849. body: t.List[Node]
  850. class OverlayScope(Stmt):
  851. """An overlay scope for extensions. This is a largely unoptimized scope
  852. that however can be used to introduce completely arbitrary variables into
  853. a sub scope from a dictionary or dictionary like object. The `context`
  854. field has to evaluate to a dictionary object.
  855. Example usage::
  856. OverlayScope(context=self.call_method('get_context'),
  857. body=[...])
  858. .. versionadded:: 2.10
  859. """
  860. fields = ("context", "body")
  861. context: Expr
  862. body: t.List[Node]
  863. class EvalContextModifier(Stmt):
  864. """Modifies the eval context. For each option that should be modified,
  865. a :class:`Keyword` has to be added to the :attr:`options` list.
  866. Example to change the `autoescape` setting::
  867. EvalContextModifier(options=[Keyword('autoescape', Const(True))])
  868. """
  869. fields = ("options",)
  870. options: t.List[Keyword]
  871. class ScopedEvalContextModifier(EvalContextModifier):
  872. """Modifies the eval context and reverts it later. Works exactly like
  873. :class:`EvalContextModifier` but will only modify the
  874. :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
  875. """
  876. fields = ("body",)
  877. body: t.List[Node]
  878. # make sure nobody creates custom nodes
  879. def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
  880. raise TypeError("can't create custom node types")
  881. NodeType.__new__ = staticmethod(_failing_new) # type: ignore
  882. del _failing_new