nodes.py 28 KB

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