nodes.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 types
  13. import operator
  14. from collections import deque
  15. from jinja2.utils import Markup
  16. from jinja2._compat import izip, with_metaclass, text_type
  17. #: the types we support for context functions
  18. _context_function_types = (types.FunctionType, types.MethodType)
  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 AssignBlock(Stmt):
  277. """Assigns a block to a target."""
  278. fields = ('target', 'body')
  279. class Expr(Node):
  280. """Baseclass for all expressions."""
  281. abstract = True
  282. def as_const(self, eval_ctx=None):
  283. """Return the value of the expression as constant or raise
  284. :exc:`Impossible` if this was not possible.
  285. An :class:`EvalContext` can be provided, if none is given
  286. a default context is created which requires the nodes to have
  287. an attached environment.
  288. .. versionchanged:: 2.4
  289. the `eval_ctx` parameter was added.
  290. """
  291. raise Impossible()
  292. def can_assign(self):
  293. """Check if it's possible to assign something to this node."""
  294. return False
  295. class BinExpr(Expr):
  296. """Baseclass for all binary expressions."""
  297. fields = ('left', 'right')
  298. operator = None
  299. abstract = True
  300. def as_const(self, eval_ctx=None):
  301. eval_ctx = get_eval_context(self, eval_ctx)
  302. # intercepted operators cannot be folded at compile time
  303. if self.environment.sandboxed and \
  304. self.operator in self.environment.intercepted_binops:
  305. raise Impossible()
  306. f = _binop_to_func[self.operator]
  307. try:
  308. return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
  309. except Exception:
  310. raise Impossible()
  311. class UnaryExpr(Expr):
  312. """Baseclass for all unary expressions."""
  313. fields = ('node',)
  314. operator = None
  315. abstract = True
  316. def as_const(self, eval_ctx=None):
  317. eval_ctx = get_eval_context(self, eval_ctx)
  318. # intercepted operators cannot be folded at compile time
  319. if self.environment.sandboxed and \
  320. self.operator in self.environment.intercepted_unops:
  321. raise Impossible()
  322. f = _uaop_to_func[self.operator]
  323. try:
  324. return f(self.node.as_const(eval_ctx))
  325. except Exception:
  326. raise Impossible()
  327. class Name(Expr):
  328. """Looks up a name or stores a value in a name.
  329. The `ctx` of the node can be one of the following values:
  330. - `store`: store a value in the name
  331. - `load`: load that name
  332. - `param`: like `store` but if the name was defined as function parameter.
  333. """
  334. fields = ('name', 'ctx')
  335. def can_assign(self):
  336. return self.name not in ('true', 'false', 'none',
  337. 'True', 'False', 'None')
  338. class Literal(Expr):
  339. """Baseclass for literals."""
  340. abstract = True
  341. class Const(Literal):
  342. """All constant values. The parser will return this node for simple
  343. constants such as ``42`` or ``"foo"`` but it can be used to store more
  344. complex values such as lists too. Only constants with a safe
  345. representation (objects where ``eval(repr(x)) == x`` is true).
  346. """
  347. fields = ('value',)
  348. def as_const(self, eval_ctx=None):
  349. return self.value
  350. @classmethod
  351. def from_untrusted(cls, value, lineno=None, environment=None):
  352. """Return a const object if the value is representable as
  353. constant value in the generated code, otherwise it will raise
  354. an `Impossible` exception.
  355. """
  356. from .compiler import has_safe_repr
  357. if not has_safe_repr(value):
  358. raise Impossible()
  359. return cls(value, lineno=lineno, environment=environment)
  360. class TemplateData(Literal):
  361. """A constant template string."""
  362. fields = ('data',)
  363. def as_const(self, eval_ctx=None):
  364. eval_ctx = get_eval_context(self, eval_ctx)
  365. if eval_ctx.volatile:
  366. raise Impossible()
  367. if eval_ctx.autoescape:
  368. return Markup(self.data)
  369. return self.data
  370. class Tuple(Literal):
  371. """For loop unpacking and some other things like multiple arguments
  372. for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
  373. is used for loading the names or storing.
  374. """
  375. fields = ('items', 'ctx')
  376. def as_const(self, eval_ctx=None):
  377. eval_ctx = get_eval_context(self, eval_ctx)
  378. return tuple(x.as_const(eval_ctx) for x in self.items)
  379. def can_assign(self):
  380. for item in self.items:
  381. if not item.can_assign():
  382. return False
  383. return True
  384. class List(Literal):
  385. """Any list literal such as ``[1, 2, 3]``"""
  386. fields = ('items',)
  387. def as_const(self, eval_ctx=None):
  388. eval_ctx = get_eval_context(self, eval_ctx)
  389. return [x.as_const(eval_ctx) for x in self.items]
  390. class Dict(Literal):
  391. """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
  392. :class:`Pair` nodes.
  393. """
  394. fields = ('items',)
  395. def as_const(self, eval_ctx=None):
  396. eval_ctx = get_eval_context(self, eval_ctx)
  397. return dict(x.as_const(eval_ctx) for x in self.items)
  398. class Pair(Helper):
  399. """A key, value pair for dicts."""
  400. fields = ('key', 'value')
  401. def as_const(self, eval_ctx=None):
  402. eval_ctx = get_eval_context(self, eval_ctx)
  403. return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
  404. class Keyword(Helper):
  405. """A key, value pair for keyword arguments where key is a string."""
  406. fields = ('key', 'value')
  407. def as_const(self, eval_ctx=None):
  408. eval_ctx = get_eval_context(self, eval_ctx)
  409. return self.key, self.value.as_const(eval_ctx)
  410. class CondExpr(Expr):
  411. """A conditional expression (inline if expression). (``{{
  412. foo if bar else baz }}``)
  413. """
  414. fields = ('test', 'expr1', 'expr2')
  415. def as_const(self, eval_ctx=None):
  416. eval_ctx = get_eval_context(self, eval_ctx)
  417. if self.test.as_const(eval_ctx):
  418. return self.expr1.as_const(eval_ctx)
  419. # if we evaluate to an undefined object, we better do that at runtime
  420. if self.expr2 is None:
  421. raise Impossible()
  422. return self.expr2.as_const(eval_ctx)
  423. class Filter(Expr):
  424. """This node applies a filter on an expression. `name` is the name of
  425. the filter, the rest of the fields are the same as for :class:`Call`.
  426. If the `node` of a filter is `None` the contents of the last buffer are
  427. filtered. Buffers are created by macros and filter blocks.
  428. """
  429. fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
  430. def as_const(self, eval_ctx=None):
  431. eval_ctx = get_eval_context(self, eval_ctx)
  432. if eval_ctx.volatile or self.node is None:
  433. raise Impossible()
  434. # we have to be careful here because we call filter_ below.
  435. # if this variable would be called filter, 2to3 would wrap the
  436. # call in a list beause it is assuming we are talking about the
  437. # builtin filter function here which no longer returns a list in
  438. # python 3. because of that, do not rename filter_ to filter!
  439. filter_ = self.environment.filters.get(self.name)
  440. if filter_ is None or getattr(filter_, 'contextfilter', False):
  441. raise Impossible()
  442. obj = self.node.as_const(eval_ctx)
  443. args = [x.as_const(eval_ctx) for x in self.args]
  444. if getattr(filter_, 'evalcontextfilter', False):
  445. args.insert(0, eval_ctx)
  446. elif getattr(filter_, 'environmentfilter', False):
  447. args.insert(0, self.environment)
  448. kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
  449. if self.dyn_args is not None:
  450. try:
  451. args.extend(self.dyn_args.as_const(eval_ctx))
  452. except Exception:
  453. raise Impossible()
  454. if self.dyn_kwargs is not None:
  455. try:
  456. kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
  457. except Exception:
  458. raise Impossible()
  459. try:
  460. return filter_(obj, *args, **kwargs)
  461. except Exception:
  462. raise Impossible()
  463. class Test(Expr):
  464. """Applies a test on an expression. `name` is the name of the test, the
  465. rest of the fields are the same as for :class:`Call`.
  466. """
  467. fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
  468. class Call(Expr):
  469. """Calls an expression. `args` is a list of arguments, `kwargs` a list
  470. of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
  471. and `dyn_kwargs` has to be either `None` or a node that is used as
  472. node for dynamic positional (``*args``) or keyword (``**kwargs``)
  473. arguments.
  474. """
  475. fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
  476. def as_const(self, eval_ctx=None):
  477. eval_ctx = get_eval_context(self, eval_ctx)
  478. if eval_ctx.volatile:
  479. raise Impossible()
  480. obj = self.node.as_const(eval_ctx)
  481. # don't evaluate context functions
  482. args = [x.as_const(eval_ctx) for x in self.args]
  483. if isinstance(obj, _context_function_types):
  484. if getattr(obj, 'contextfunction', False):
  485. raise Impossible()
  486. elif getattr(obj, 'evalcontextfunction', False):
  487. args.insert(0, eval_ctx)
  488. elif getattr(obj, 'environmentfunction', False):
  489. args.insert(0, self.environment)
  490. kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
  491. if self.dyn_args is not None:
  492. try:
  493. args.extend(self.dyn_args.as_const(eval_ctx))
  494. except Exception:
  495. raise Impossible()
  496. if self.dyn_kwargs is not None:
  497. try:
  498. kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
  499. except Exception:
  500. raise Impossible()
  501. try:
  502. return obj(*args, **kwargs)
  503. except Exception:
  504. raise Impossible()
  505. class Getitem(Expr):
  506. """Get an attribute or item from an expression and prefer the item."""
  507. fields = ('node', 'arg', 'ctx')
  508. def as_const(self, eval_ctx=None):
  509. eval_ctx = get_eval_context(self, eval_ctx)
  510. if self.ctx != 'load':
  511. raise Impossible()
  512. try:
  513. return self.environment.getitem(self.node.as_const(eval_ctx),
  514. self.arg.as_const(eval_ctx))
  515. except Exception:
  516. raise Impossible()
  517. def can_assign(self):
  518. return False
  519. class Getattr(Expr):
  520. """Get an attribute or item from an expression that is a ascii-only
  521. bytestring and prefer the attribute.
  522. """
  523. fields = ('node', 'attr', 'ctx')
  524. def as_const(self, eval_ctx=None):
  525. if self.ctx != 'load':
  526. raise Impossible()
  527. try:
  528. eval_ctx = get_eval_context(self, eval_ctx)
  529. return self.environment.getattr(self.node.as_const(eval_ctx),
  530. self.attr)
  531. except Exception:
  532. raise Impossible()
  533. def can_assign(self):
  534. return False
  535. class Slice(Expr):
  536. """Represents a slice object. This must only be used as argument for
  537. :class:`Subscript`.
  538. """
  539. fields = ('start', 'stop', 'step')
  540. def as_const(self, eval_ctx=None):
  541. eval_ctx = get_eval_context(self, eval_ctx)
  542. def const(obj):
  543. if obj is None:
  544. return None
  545. return obj.as_const(eval_ctx)
  546. return slice(const(self.start), const(self.stop), const(self.step))
  547. class Concat(Expr):
  548. """Concatenates the list of expressions provided after converting them to
  549. unicode.
  550. """
  551. fields = ('nodes',)
  552. def as_const(self, eval_ctx=None):
  553. eval_ctx = get_eval_context(self, eval_ctx)
  554. return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)
  555. class Compare(Expr):
  556. """Compares an expression with some other expressions. `ops` must be a
  557. list of :class:`Operand`\s.
  558. """
  559. fields = ('expr', 'ops')
  560. def as_const(self, eval_ctx=None):
  561. eval_ctx = get_eval_context(self, eval_ctx)
  562. result = value = self.expr.as_const(eval_ctx)
  563. try:
  564. for op in self.ops:
  565. new_value = op.expr.as_const(eval_ctx)
  566. result = _cmpop_to_func[op.op](value, new_value)
  567. value = new_value
  568. except Exception:
  569. raise Impossible()
  570. return result
  571. class Operand(Helper):
  572. """Holds an operator and an expression."""
  573. fields = ('op', 'expr')
  574. if __debug__:
  575. Operand.__doc__ += '\nThe following operators are available: ' + \
  576. ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
  577. set(_uaop_to_func) | set(_cmpop_to_func)))
  578. class Mul(BinExpr):
  579. """Multiplies the left with the right node."""
  580. operator = '*'
  581. class Div(BinExpr):
  582. """Divides the left by the right node."""
  583. operator = '/'
  584. class FloorDiv(BinExpr):
  585. """Divides the left by the right node and truncates conver the
  586. result into an integer by truncating.
  587. """
  588. operator = '//'
  589. class Add(BinExpr):
  590. """Add the left to the right node."""
  591. operator = '+'
  592. class Sub(BinExpr):
  593. """Subtract the right from the left node."""
  594. operator = '-'
  595. class Mod(BinExpr):
  596. """Left modulo right."""
  597. operator = '%'
  598. class Pow(BinExpr):
  599. """Left to the power of right."""
  600. operator = '**'
  601. class And(BinExpr):
  602. """Short circuited AND."""
  603. operator = 'and'
  604. def as_const(self, eval_ctx=None):
  605. eval_ctx = get_eval_context(self, eval_ctx)
  606. return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
  607. class Or(BinExpr):
  608. """Short circuited OR."""
  609. operator = 'or'
  610. def as_const(self, eval_ctx=None):
  611. eval_ctx = get_eval_context(self, eval_ctx)
  612. return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
  613. class Not(UnaryExpr):
  614. """Negate the expression."""
  615. operator = 'not'
  616. class Neg(UnaryExpr):
  617. """Make the expression negative."""
  618. operator = '-'
  619. class Pos(UnaryExpr):
  620. """Make the expression positive (noop for most expressions)"""
  621. operator = '+'
  622. # Helpers for extensions
  623. class EnvironmentAttribute(Expr):
  624. """Loads an attribute from the environment object. This is useful for
  625. extensions that want to call a callback stored on the environment.
  626. """
  627. fields = ('name',)
  628. class ExtensionAttribute(Expr):
  629. """Returns the attribute of an extension bound to the environment.
  630. The identifier is the identifier of the :class:`Extension`.
  631. This node is usually constructed by calling the
  632. :meth:`~jinja2.ext.Extension.attr` method on an extension.
  633. """
  634. fields = ('identifier', 'name')
  635. class ImportedName(Expr):
  636. """If created with an import name the import name is returned on node
  637. access. For example ``ImportedName('cgi.escape')`` returns the `escape`
  638. function from the cgi module on evaluation. Imports are optimized by the
  639. compiler so there is no need to assign them to local variables.
  640. """
  641. fields = ('importname',)
  642. class InternalName(Expr):
  643. """An internal name in the compiler. You cannot create these nodes
  644. yourself but the parser provides a
  645. :meth:`~jinja2.parser.Parser.free_identifier` method that creates
  646. a new identifier for you. This identifier is not available from the
  647. template and is not threated specially by the compiler.
  648. """
  649. fields = ('name',)
  650. def __init__(self):
  651. raise TypeError('Can\'t create internal names. Use the '
  652. '`free_identifier` method on a parser.')
  653. class MarkSafe(Expr):
  654. """Mark the wrapped expression as safe (wrap it as `Markup`)."""
  655. fields = ('expr',)
  656. def as_const(self, eval_ctx=None):
  657. eval_ctx = get_eval_context(self, eval_ctx)
  658. return Markup(self.expr.as_const(eval_ctx))
  659. class MarkSafeIfAutoescape(Expr):
  660. """Mark the wrapped expression as safe (wrap it as `Markup`) but
  661. only if autoescaping is active.
  662. .. versionadded:: 2.5
  663. """
  664. fields = ('expr',)
  665. def as_const(self, eval_ctx=None):
  666. eval_ctx = get_eval_context(self, eval_ctx)
  667. if eval_ctx.volatile:
  668. raise Impossible()
  669. expr = self.expr.as_const(eval_ctx)
  670. if eval_ctx.autoescape:
  671. return Markup(expr)
  672. return expr
  673. class ContextReference(Expr):
  674. """Returns the current template context. It can be used like a
  675. :class:`Name` node, with a ``'load'`` ctx and will return the
  676. current :class:`~jinja2.runtime.Context` object.
  677. Here an example that assigns the current template name to a
  678. variable named `foo`::
  679. Assign(Name('foo', ctx='store'),
  680. Getattr(ContextReference(), 'name'))
  681. """
  682. class Continue(Stmt):
  683. """Continue a loop."""
  684. class Break(Stmt):
  685. """Break a loop."""
  686. class Scope(Stmt):
  687. """An artificial scope."""
  688. fields = ('body',)
  689. class EvalContextModifier(Stmt):
  690. """Modifies the eval context. For each option that should be modified,
  691. a :class:`Keyword` has to be added to the :attr:`options` list.
  692. Example to change the `autoescape` setting::
  693. EvalContextModifier(options=[Keyword('autoescape', Const(True))])
  694. """
  695. fields = ('options',)
  696. class ScopedEvalContextModifier(EvalContextModifier):
  697. """Modifies the eval context and reverts it later. Works exactly like
  698. :class:`EvalContextModifier` but will only modify the
  699. :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
  700. """
  701. fields = ('body',)
  702. # make sure nobody creates custom nodes
  703. def _failing_new(*args, **kwargs):
  704. raise TypeError('can\'t create custom node types')
  705. NodeType.__new__ = staticmethod(_failing_new); del _failing_new