nodes.py 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  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. __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