nodes.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  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: t.List[t.Tuple[str, ...]] = []
  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. __hash__ = object.__hash__
  208. def __repr__(self) -> str:
  209. args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)
  210. return f"{type(self).__name__}({args_str})"
  211. def dump(self) -> str:
  212. def _dump(node: t.Union[Node, t.Any]) -> None:
  213. if not isinstance(node, Node):
  214. buf.append(repr(node))
  215. return
  216. buf.append(f"nodes.{type(node).__name__}(")
  217. if not node.fields:
  218. buf.append(")")
  219. return
  220. for idx, field in enumerate(node.fields):
  221. if idx:
  222. buf.append(", ")
  223. value = getattr(node, field)
  224. if isinstance(value, list):
  225. buf.append("[")
  226. for idx, item in enumerate(value):
  227. if idx:
  228. buf.append(", ")
  229. _dump(item)
  230. buf.append("]")
  231. else:
  232. _dump(value)
  233. buf.append(")")
  234. buf: t.List[str] = []
  235. _dump(self)
  236. return "".join(buf)
  237. class Stmt(Node):
  238. """Base node for all statements."""
  239. abstract = True
  240. class Helper(Node):
  241. """Nodes that exist in a specific context only."""
  242. abstract = True
  243. class Template(Node):
  244. """Node that represents a template. This must be the outermost node that
  245. is passed to the compiler.
  246. """
  247. fields = ("body",)
  248. body: t.List[Node]
  249. class Output(Stmt):
  250. """A node that holds multiple expressions which are then printed out.
  251. This is used both for the `print` statement and the regular template data.
  252. """
  253. fields = ("nodes",)
  254. nodes: t.List["Expr"]
  255. class Extends(Stmt):
  256. """Represents an extends statement."""
  257. fields = ("template",)
  258. template: "Expr"
  259. class For(Stmt):
  260. """The for loop. `target` is the target for the iteration (usually a
  261. :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
  262. of nodes that are used as loop-body, and `else_` a list of nodes for the
  263. `else` block. If no else node exists it has to be an empty list.
  264. For filtered nodes an expression can be stored as `test`, otherwise `None`.
  265. """
  266. fields = ("target", "iter", "body", "else_", "test", "recursive")
  267. target: Node
  268. iter: Node
  269. body: t.List[Node]
  270. else_: t.List[Node]
  271. test: t.Optional[Node]
  272. recursive: bool
  273. class If(Stmt):
  274. """If `test` is true, `body` is rendered, else `else_`."""
  275. fields = ("test", "body", "elif_", "else_")
  276. test: Node
  277. body: t.List[Node]
  278. elif_: t.List["If"]
  279. else_: t.List[Node]
  280. class Macro(Stmt):
  281. """A macro definition. `name` is the name of the macro, `args` a list of
  282. arguments and `defaults` a list of defaults if there are any. `body` is
  283. a list of nodes for the macro body.
  284. """
  285. fields = ("name", "args", "defaults", "body")
  286. name: str
  287. args: t.List["Name"]
  288. defaults: t.List["Expr"]
  289. body: t.List[Node]
  290. class CallBlock(Stmt):
  291. """Like a macro without a name but a call instead. `call` is called with
  292. the unnamed macro as `caller` argument this node holds.
  293. """
  294. fields = ("call", "args", "defaults", "body")
  295. call: "Call"
  296. args: t.List["Name"]
  297. defaults: t.List["Expr"]
  298. body: t.List[Node]
  299. class FilterBlock(Stmt):
  300. """Node for filter sections."""
  301. fields = ("body", "filter")
  302. body: t.List[Node]
  303. filter: "Filter"
  304. class With(Stmt):
  305. """Specific node for with statements. In older versions of Jinja the
  306. with statement was implemented on the base of the `Scope` node instead.
  307. .. versionadded:: 2.9.3
  308. """
  309. fields = ("targets", "values", "body")
  310. targets: t.List["Expr"]
  311. values: t.List["Expr"]
  312. body: t.List[Node]
  313. class Block(Stmt):
  314. """A node that represents a block.
  315. .. versionchanged:: 3.0.0
  316. the `required` field was added.
  317. """
  318. fields = ("name", "body", "scoped", "required")
  319. name: str
  320. body: t.List[Node]
  321. scoped: bool
  322. required: bool
  323. class Include(Stmt):
  324. """A node that represents the include tag."""
  325. fields = ("template", "with_context", "ignore_missing")
  326. template: "Expr"
  327. with_context: bool
  328. ignore_missing: bool
  329. class Import(Stmt):
  330. """A node that represents the import tag."""
  331. fields = ("template", "target", "with_context")
  332. template: "Expr"
  333. target: str
  334. with_context: bool
  335. class FromImport(Stmt):
  336. """A node that represents the from import tag. It's important to not
  337. pass unsafe names to the name attribute. The compiler translates the
  338. attribute lookups directly into getattr calls and does *not* use the
  339. subscript callback of the interface. As exported variables may not
  340. start with double underscores (which the parser asserts) this is not a
  341. problem for regular Jinja code, but if this node is used in an extension
  342. extra care must be taken.
  343. The list of names may contain tuples if aliases are wanted.
  344. """
  345. fields = ("template", "names", "with_context")
  346. template: "Expr"
  347. names: t.List[t.Union[str, t.Tuple[str, str]]]
  348. with_context: bool
  349. class ExprStmt(Stmt):
  350. """A statement that evaluates an expression and discards the result."""
  351. fields = ("node",)
  352. node: Node
  353. class Assign(Stmt):
  354. """Assigns an expression to a target."""
  355. fields = ("target", "node")
  356. target: "Expr"
  357. node: Node
  358. class AssignBlock(Stmt):
  359. """Assigns a block to a target."""
  360. fields = ("target", "filter", "body")
  361. target: "Expr"
  362. filter: t.Optional["Filter"]
  363. body: t.List[Node]
  364. class Expr(Node):
  365. """Baseclass for all expressions."""
  366. abstract = True
  367. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  368. """Return the value of the expression as constant or raise
  369. :exc:`Impossible` if this was not possible.
  370. An :class:`EvalContext` can be provided, if none is given
  371. a default context is created which requires the nodes to have
  372. an attached environment.
  373. .. versionchanged:: 2.4
  374. the `eval_ctx` parameter was added.
  375. """
  376. raise Impossible()
  377. def can_assign(self) -> bool:
  378. """Check if it's possible to assign something to this node."""
  379. return False
  380. class BinExpr(Expr):
  381. """Baseclass for all binary expressions."""
  382. fields = ("left", "right")
  383. left: Expr
  384. right: Expr
  385. operator: str
  386. abstract = True
  387. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  388. eval_ctx = get_eval_context(self, eval_ctx)
  389. # intercepted operators cannot be folded at compile time
  390. if (
  391. eval_ctx.environment.sandboxed
  392. and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
  393. ):
  394. raise Impossible()
  395. f = _binop_to_func[self.operator]
  396. try:
  397. return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
  398. except Exception as e:
  399. raise Impossible() from e
  400. class UnaryExpr(Expr):
  401. """Baseclass for all unary expressions."""
  402. fields = ("node",)
  403. node: Expr
  404. operator: str
  405. abstract = True
  406. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  407. eval_ctx = get_eval_context(self, eval_ctx)
  408. # intercepted operators cannot be folded at compile time
  409. if (
  410. eval_ctx.environment.sandboxed
  411. and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
  412. ):
  413. raise Impossible()
  414. f = _uaop_to_func[self.operator]
  415. try:
  416. return f(self.node.as_const(eval_ctx))
  417. except Exception as e:
  418. raise Impossible() from e
  419. class Name(Expr):
  420. """Looks up a name or stores a value in a name.
  421. The `ctx` of the node can be one of the following values:
  422. - `store`: store a value in the name
  423. - `load`: load that name
  424. - `param`: like `store` but if the name was defined as function parameter.
  425. """
  426. fields = ("name", "ctx")
  427. name: str
  428. ctx: str
  429. def can_assign(self) -> bool:
  430. return self.name not in {"true", "false", "none", "True", "False", "None"}
  431. class NSRef(Expr):
  432. """Reference to a namespace value assignment"""
  433. fields = ("name", "attr")
  434. name: str
  435. attr: str
  436. def can_assign(self) -> bool:
  437. # We don't need any special checks here; NSRef assignments have a
  438. # runtime check to ensure the target is a namespace object which will
  439. # have been checked already as it is created using a normal assignment
  440. # which goes through a `Name` node.
  441. return True
  442. class Literal(Expr):
  443. """Baseclass for literals."""
  444. abstract = True
  445. class Const(Literal):
  446. """All constant values. The parser will return this node for simple
  447. constants such as ``42`` or ``"foo"`` but it can be used to store more
  448. complex values such as lists too. Only constants with a safe
  449. representation (objects where ``eval(repr(x)) == x`` is true).
  450. """
  451. fields = ("value",)
  452. value: t.Any
  453. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  454. return self.value
  455. @classmethod
  456. def from_untrusted(
  457. cls,
  458. value: t.Any,
  459. lineno: t.Optional[int] = None,
  460. environment: "t.Optional[Environment]" = None,
  461. ) -> "Const":
  462. """Return a const object if the value is representable as
  463. constant value in the generated code, otherwise it will raise
  464. an `Impossible` exception.
  465. """
  466. from .compiler import has_safe_repr
  467. if not has_safe_repr(value):
  468. raise Impossible()
  469. return cls(value, lineno=lineno, environment=environment)
  470. class TemplateData(Literal):
  471. """A constant template string."""
  472. fields = ("data",)
  473. data: str
  474. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
  475. eval_ctx = get_eval_context(self, eval_ctx)
  476. if eval_ctx.volatile:
  477. raise Impossible()
  478. if eval_ctx.autoescape:
  479. return Markup(self.data)
  480. return self.data
  481. class Tuple(Literal):
  482. """For loop unpacking and some other things like multiple arguments
  483. for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
  484. is used for loading the names or storing.
  485. """
  486. fields = ("items", "ctx")
  487. items: t.List[Expr]
  488. ctx: str
  489. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[t.Any, ...]:
  490. eval_ctx = get_eval_context(self, eval_ctx)
  491. return tuple(x.as_const(eval_ctx) for x in self.items)
  492. def can_assign(self) -> bool:
  493. for item in self.items:
  494. if not item.can_assign():
  495. return False
  496. return True
  497. class List(Literal):
  498. """Any list literal such as ``[1, 2, 3]``"""
  499. fields = ("items",)
  500. items: t.List[Expr]
  501. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.List[t.Any]:
  502. eval_ctx = get_eval_context(self, eval_ctx)
  503. return [x.as_const(eval_ctx) for x in self.items]
  504. class Dict(Literal):
  505. """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
  506. :class:`Pair` nodes.
  507. """
  508. fields = ("items",)
  509. items: t.List["Pair"]
  510. def as_const(
  511. self, eval_ctx: t.Optional[EvalContext] = None
  512. ) -> t.Dict[t.Any, t.Any]:
  513. eval_ctx = get_eval_context(self, eval_ctx)
  514. return dict(x.as_const(eval_ctx) for x in self.items)
  515. class Pair(Helper):
  516. """A key, value pair for dicts."""
  517. fields = ("key", "value")
  518. key: Expr
  519. value: Expr
  520. def as_const(
  521. self, eval_ctx: t.Optional[EvalContext] = None
  522. ) -> t.Tuple[t.Any, t.Any]:
  523. eval_ctx = get_eval_context(self, eval_ctx)
  524. return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
  525. class Keyword(Helper):
  526. """A key, value pair for keyword arguments where key is a string."""
  527. fields = ("key", "value")
  528. key: str
  529. value: Expr
  530. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Tuple[str, t.Any]:
  531. eval_ctx = get_eval_context(self, eval_ctx)
  532. return self.key, self.value.as_const(eval_ctx)
  533. class CondExpr(Expr):
  534. """A conditional expression (inline if expression). (``{{
  535. foo if bar else baz }}``)
  536. """
  537. fields = ("test", "expr1", "expr2")
  538. test: Expr
  539. expr1: Expr
  540. expr2: t.Optional[Expr]
  541. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  542. eval_ctx = get_eval_context(self, eval_ctx)
  543. if self.test.as_const(eval_ctx):
  544. return self.expr1.as_const(eval_ctx)
  545. # if we evaluate to an undefined object, we better do that at runtime
  546. if self.expr2 is None:
  547. raise Impossible()
  548. return self.expr2.as_const(eval_ctx)
  549. def args_as_const(
  550. node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
  551. ) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
  552. args = [x.as_const(eval_ctx) for x in node.args]
  553. kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
  554. if node.dyn_args is not None:
  555. try:
  556. args.extend(node.dyn_args.as_const(eval_ctx))
  557. except Exception as e:
  558. raise Impossible() from e
  559. if node.dyn_kwargs is not None:
  560. try:
  561. kwargs.update(node.dyn_kwargs.as_const(eval_ctx))
  562. except Exception as e:
  563. raise Impossible() from e
  564. return args, kwargs
  565. class _FilterTestCommon(Expr):
  566. fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
  567. node: Expr
  568. name: str
  569. args: t.List[Expr]
  570. kwargs: t.List[Pair]
  571. dyn_args: t.Optional[Expr]
  572. dyn_kwargs: t.Optional[Expr]
  573. abstract = True
  574. _is_filter = True
  575. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  576. eval_ctx = get_eval_context(self, eval_ctx)
  577. if eval_ctx.volatile:
  578. raise Impossible()
  579. if self._is_filter:
  580. env_map = eval_ctx.environment.filters
  581. else:
  582. env_map = eval_ctx.environment.tests
  583. func = env_map.get(self.name)
  584. pass_arg = _PassArg.from_obj(func) # type: ignore
  585. if func is None or pass_arg is _PassArg.context:
  586. raise Impossible()
  587. if eval_ctx.environment.is_async and (
  588. getattr(func, "jinja_async_variant", False) is True
  589. or inspect.iscoroutinefunction(func)
  590. ):
  591. raise Impossible()
  592. args, kwargs = args_as_const(self, eval_ctx)
  593. args.insert(0, self.node.as_const(eval_ctx))
  594. if pass_arg is _PassArg.eval_context:
  595. args.insert(0, eval_ctx)
  596. elif pass_arg is _PassArg.environment:
  597. args.insert(0, eval_ctx.environment)
  598. try:
  599. return func(*args, **kwargs)
  600. except Exception as e:
  601. raise Impossible() from e
  602. class Filter(_FilterTestCommon):
  603. """Apply a filter to an expression. ``name`` is the name of the
  604. filter, the other fields are the same as :class:`Call`.
  605. If ``node`` is ``None``, the filter is being used in a filter block
  606. and is applied to the content of the block.
  607. """
  608. node: t.Optional[Expr] # type: ignore
  609. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  610. if self.node is None:
  611. raise Impossible()
  612. return super().as_const(eval_ctx=eval_ctx)
  613. class Test(_FilterTestCommon):
  614. """Apply a test to an expression. ``name`` is the name of the test,
  615. the other field are the same as :class:`Call`.
  616. .. versionchanged:: 3.0
  617. ``as_const`` shares the same logic for filters and tests. Tests
  618. check for volatile, async, and ``@pass_context`` etc.
  619. decorators.
  620. """
  621. _is_filter = False
  622. class Call(Expr):
  623. """Calls an expression. `args` is a list of arguments, `kwargs` a list
  624. of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
  625. and `dyn_kwargs` has to be either `None` or a node that is used as
  626. node for dynamic positional (``*args``) or keyword (``**kwargs``)
  627. arguments.
  628. """
  629. fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")
  630. node: Expr
  631. args: t.List[Expr]
  632. kwargs: t.List[Keyword]
  633. dyn_args: t.Optional[Expr]
  634. dyn_kwargs: t.Optional[Expr]
  635. class Getitem(Expr):
  636. """Get an attribute or item from an expression and prefer the item."""
  637. fields = ("node", "arg", "ctx")
  638. node: Expr
  639. arg: Expr
  640. ctx: str
  641. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  642. if self.ctx != "load":
  643. raise Impossible()
  644. eval_ctx = get_eval_context(self, eval_ctx)
  645. try:
  646. return eval_ctx.environment.getitem(
  647. self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
  648. )
  649. except Exception as e:
  650. raise Impossible() from e
  651. class Getattr(Expr):
  652. """Get an attribute or item from an expression that is a ascii-only
  653. bytestring and prefer the attribute.
  654. """
  655. fields = ("node", "attr", "ctx")
  656. node: Expr
  657. attr: str
  658. ctx: str
  659. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  660. if self.ctx != "load":
  661. raise Impossible()
  662. eval_ctx = get_eval_context(self, eval_ctx)
  663. try:
  664. return eval_ctx.environment.getattr(self.node.as_const(eval_ctx), self.attr)
  665. except Exception as e:
  666. raise Impossible() from e
  667. class Slice(Expr):
  668. """Represents a slice object. This must only be used as argument for
  669. :class:`Subscript`.
  670. """
  671. fields = ("start", "stop", "step")
  672. start: t.Optional[Expr]
  673. stop: t.Optional[Expr]
  674. step: t.Optional[Expr]
  675. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> slice:
  676. eval_ctx = get_eval_context(self, eval_ctx)
  677. def const(obj: t.Optional[Expr]) -> t.Optional[t.Any]:
  678. if obj is None:
  679. return None
  680. return obj.as_const(eval_ctx)
  681. return slice(const(self.start), const(self.stop), const(self.step))
  682. class Concat(Expr):
  683. """Concatenates the list of expressions provided after converting
  684. them to strings.
  685. """
  686. fields = ("nodes",)
  687. nodes: t.List[Expr]
  688. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
  689. eval_ctx = get_eval_context(self, eval_ctx)
  690. return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)
  691. class Compare(Expr):
  692. """Compares an expression with some other expressions. `ops` must be a
  693. list of :class:`Operand`\\s.
  694. """
  695. fields = ("expr", "ops")
  696. expr: Expr
  697. ops: t.List["Operand"]
  698. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  699. eval_ctx = get_eval_context(self, eval_ctx)
  700. result = value = self.expr.as_const(eval_ctx)
  701. try:
  702. for op in self.ops:
  703. new_value = op.expr.as_const(eval_ctx)
  704. result = _cmpop_to_func[op.op](value, new_value)
  705. if not result:
  706. return False
  707. value = new_value
  708. except Exception as e:
  709. raise Impossible() from e
  710. return result
  711. class Operand(Helper):
  712. """Holds an operator and an expression."""
  713. fields = ("op", "expr")
  714. op: str
  715. expr: Expr
  716. class Mul(BinExpr):
  717. """Multiplies the left with the right node."""
  718. operator = "*"
  719. class Div(BinExpr):
  720. """Divides the left by the right node."""
  721. operator = "/"
  722. class FloorDiv(BinExpr):
  723. """Divides the left by the right node and converts the
  724. result into an integer by truncating.
  725. """
  726. operator = "//"
  727. class Add(BinExpr):
  728. """Add the left to the right node."""
  729. operator = "+"
  730. class Sub(BinExpr):
  731. """Subtract the right from the left node."""
  732. operator = "-"
  733. class Mod(BinExpr):
  734. """Left modulo right."""
  735. operator = "%"
  736. class Pow(BinExpr):
  737. """Left to the power of right."""
  738. operator = "**"
  739. class And(BinExpr):
  740. """Short circuited AND."""
  741. operator = "and"
  742. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  743. eval_ctx = get_eval_context(self, eval_ctx)
  744. return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
  745. class Or(BinExpr):
  746. """Short circuited OR."""
  747. operator = "or"
  748. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
  749. eval_ctx = get_eval_context(self, eval_ctx)
  750. return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
  751. class Not(UnaryExpr):
  752. """Negate the expression."""
  753. operator = "not"
  754. class Neg(UnaryExpr):
  755. """Make the expression negative."""
  756. operator = "-"
  757. class Pos(UnaryExpr):
  758. """Make the expression positive (noop for most expressions)"""
  759. operator = "+"
  760. # Helpers for extensions
  761. class EnvironmentAttribute(Expr):
  762. """Loads an attribute from the environment object. This is useful for
  763. extensions that want to call a callback stored on the environment.
  764. """
  765. fields = ("name",)
  766. name: str
  767. class ExtensionAttribute(Expr):
  768. """Returns the attribute of an extension bound to the environment.
  769. The identifier is the identifier of the :class:`Extension`.
  770. This node is usually constructed by calling the
  771. :meth:`~jinja2.ext.Extension.attr` method on an extension.
  772. """
  773. fields = ("identifier", "name")
  774. identifier: str
  775. name: str
  776. class ImportedName(Expr):
  777. """If created with an import name the import name is returned on node
  778. access. For example ``ImportedName('cgi.escape')`` returns the `escape`
  779. function from the cgi module on evaluation. Imports are optimized by the
  780. compiler so there is no need to assign them to local variables.
  781. """
  782. fields = ("importname",)
  783. importname: str
  784. class InternalName(Expr):
  785. """An internal name in the compiler. You cannot create these nodes
  786. yourself but the parser provides a
  787. :meth:`~jinja2.parser.Parser.free_identifier` method that creates
  788. a new identifier for you. This identifier is not available from the
  789. template and is not treated specially by the compiler.
  790. """
  791. fields = ("name",)
  792. name: str
  793. def __init__(self) -> None:
  794. raise TypeError(
  795. "Can't create internal names. Use the "
  796. "`free_identifier` method on a parser."
  797. )
  798. class MarkSafe(Expr):
  799. """Mark the wrapped expression as safe (wrap it as `Markup`)."""
  800. fields = ("expr",)
  801. expr: Expr
  802. def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> Markup:
  803. eval_ctx = get_eval_context(self, eval_ctx)
  804. return Markup(self.expr.as_const(eval_ctx))
  805. class MarkSafeIfAutoescape(Expr):
  806. """Mark the wrapped expression as safe (wrap it as `Markup`) but
  807. only if autoescaping is active.
  808. .. versionadded:: 2.5
  809. """
  810. fields = ("expr",)
  811. expr: Expr
  812. def as_const(
  813. self, eval_ctx: t.Optional[EvalContext] = None
  814. ) -> t.Union[Markup, t.Any]:
  815. eval_ctx = get_eval_context(self, eval_ctx)
  816. if eval_ctx.volatile:
  817. raise Impossible()
  818. expr = self.expr.as_const(eval_ctx)
  819. if eval_ctx.autoescape:
  820. return Markup(expr)
  821. return expr
  822. class ContextReference(Expr):
  823. """Returns the current template context. It can be used like a
  824. :class:`Name` node, with a ``'load'`` ctx and will return the
  825. current :class:`~jinja2.runtime.Context` object.
  826. Here an example that assigns the current template name to a
  827. variable named `foo`::
  828. Assign(Name('foo', ctx='store'),
  829. Getattr(ContextReference(), 'name'))
  830. This is basically equivalent to using the
  831. :func:`~jinja2.pass_context` decorator when using the high-level
  832. API, which causes a reference to the context to be passed as the
  833. first argument to a function.
  834. """
  835. class DerivedContextReference(Expr):
  836. """Return the current template context including locals. Behaves
  837. exactly like :class:`ContextReference`, but includes local
  838. variables, such as from a ``for`` loop.
  839. .. versionadded:: 2.11
  840. """
  841. class Continue(Stmt):
  842. """Continue a loop."""
  843. class Break(Stmt):
  844. """Break a loop."""
  845. class Scope(Stmt):
  846. """An artificial scope."""
  847. fields = ("body",)
  848. body: t.List[Node]
  849. class OverlayScope(Stmt):
  850. """An overlay scope for extensions. This is a largely unoptimized scope
  851. that however can be used to introduce completely arbitrary variables into
  852. a sub scope from a dictionary or dictionary like object. The `context`
  853. field has to evaluate to a dictionary object.
  854. Example usage::
  855. OverlayScope(context=self.call_method('get_context'),
  856. body=[...])
  857. .. versionadded:: 2.10
  858. """
  859. fields = ("context", "body")
  860. context: Expr
  861. body: t.List[Node]
  862. class EvalContextModifier(Stmt):
  863. """Modifies the eval context. For each option that should be modified,
  864. a :class:`Keyword` has to be added to the :attr:`options` list.
  865. Example to change the `autoescape` setting::
  866. EvalContextModifier(options=[Keyword('autoescape', Const(True))])
  867. """
  868. fields = ("options",)
  869. options: t.List[Keyword]
  870. class ScopedEvalContextModifier(EvalContextModifier):
  871. """Modifies the eval context and reverts it later. Works exactly like
  872. :class:`EvalContextModifier` but will only modify the
  873. :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
  874. """
  875. fields = ("body",)
  876. body: t.List[Node]
  877. # make sure nobody creates custom nodes
  878. def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":
  879. raise TypeError("can't create custom node types")
  880. NodeType.__new__ = staticmethod(_failing_new) # type: ignore
  881. del _failing_new