PageRenderTime 76ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Doc/jinja2/nodes.py

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