nodes.py 30 KB

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