Skip to content
Myr

added first working pieces of compiler

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 82b3f3d · Browse files · 9 files+761 added−106 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+761 added−106 removed

  • other:+761 added−106 removed

9 files+761 added−106 removed

added:jinja2/compiler.py+380 added
1# -*- coding: utf-8 -*-2"""3 jinja2.compiler4 ~~~~~~~~~~~~~~~56 Compiles nodes into python code.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11from random import randrange12from operator import xor13from cStringIO import StringIO14from jinja2 import nodes15from jinja2.visitor import NodeVisitor, NodeTransformer16from jinja2.exceptions import TemplateAssertionError171819operators = {20 'eq': '==',21 'ne': '!=',22 'gt': '>',23 'gteq': '>=',24 'lt': '<',25 'lteq': '<=',26 'in': 'in',27 'notin': 'not in'28}293031def generate(node, filename, stream=None):32 is_child = node.find(nodes.Extends) is not None33 generator = CodeGenerator(is_child, filename, stream)34 generator.visit(node)35 if stream is None:36 return generator.stream.getvalue()373839class Identifiers(object):40 """Tracks the status of identifiers in frames."""4142 def __init__(self):43 # variables that are known to be declared (probably from outer44 # frames or because they are special for the frame)45 self.declared = set()4647 # names that are accessed without being explicitly declared by48 # this one or any of the outer scopes. Names can appear both in49 # declared and undeclared.50 self.undeclared = set()5152 # names that are declared locally53 self.declared_locally = set()5455 # names that are declared by parameters56 self.declared_parameter = set()5758 def add_special(self, name):59 """Register a special name like `loop`."""60 self.undeclared.discard(name)61 self.declared.add(name)6263 def is_declared(self, name):64 """Check if a name is declared in this or an outer scope."""65 return name in self.declared or name in self.declared_locally or \66 name in self.declared_parameter6768 def find_shadowed(self):69 """Find all the shadowed names."""70 return self.declared & (self.declared_locally | self.declared_parameter)717273class Frame(object):7475 def __init__(self, parent=None):76 self.identifiers = Identifiers()77 self.parent = parent78 if parent is not None:79 self.identifiers.declared.update(80 parent.identifiers.declared |81 parent.identifiers.undeclared |82 parent.identifiers.declared_locally |83 parent.identifiers.declared_parameter84 )8586 def inspect(self, nodes):87 """Walk the node and check for identifiers."""88 visitor = FrameIdentifierVisitor(self.identifiers)89 for node in nodes:90 visitor.visit(node)9192 def inner(self):93 """Return an inner frame."""94 return Frame(self)959697class FrameIdentifierVisitor(NodeVisitor):98 """A visitor for `Frame.inspect`."""99100 def __init__(self, identifiers):101 self.identifiers = identifiers102103 def visit_Name(self, node):104 """All assignments to names go through this function."""105 if node.ctx in ('store', 'param'):106 self.identifiers.declared_locally.add(node.name)107 elif node.ctx == 'load':108 if not self.identifiers.is_declared(node.name):109 self.identifiers.undeclared.add(node.name)110111 def visit_Macro(self, node):112 """Macros set local."""113 self.identifiers.declared_locally.add(node.name)114115 # stop traversing at instructions that have their own scope.116 visit_Block = visit_Call = visit_FilterBlock = \117 visit_For = lambda s, n: None118119120class CodeGenerator(NodeVisitor):121122 def __init__(self, is_child, filename, stream=None):123 if stream is None:124 stream = StringIO()125 self.is_child = is_child126 self.filename = filename127 self.stream = stream128 self.blocks = {}129 self.indentation = 0130 self.new_lines = 0131 self.last_identifier = 0132 self._last_line = 0133 self._first_write = True134135 def temporary_identifier(self):136 self.last_identifier += 1137 return 't%d' % self.last_identifier138139 def indent(self):140 self.indentation += 1141142 def outdent(self):143 self.indentation -= 1144145 def blockvisit(self, nodes, frame, force_generator=False):146 self.indent()147 if force_generator:148 self.writeline('if 0: yield None')149 for node in nodes:150 self.visit(node, frame)151 self.outdent()152153 def write(self, x):154 if self.new_lines:155 if not self._first_write:156 self.stream.write('\n' * self.new_lines)157 self._first_write = False158 self.stream.write(' ' * self.indentation)159 self.new_lines = 0160 self.stream.write(x)161162 def writeline(self, x, node=None, extra=0):163 self.newline(node, extra)164 self.write(x)165166 def newline(self, node=None, extra=0):167 self.new_lines = max(self.new_lines, 1 + extra)168 if node is not None and node.lineno != self._last_line:169 self.write('# line: %s' % node.lineno)170 self.new_lines = 1171 self._last_line = node.lineno172173 def pull_locals(self, frame, no_indent=False):174 if not no_indent:175 self.indent()176 for name in frame.identifiers.undeclared:177 self.writeline('l_%s = context[%r]' % (name, name))178 if not no_indent:179 self.outdent()180181 # -- Visitors182183 def visit_Template(self, node, frame=None):184 assert frame is None, 'no root frame allowed'185 self.writeline('from jinja2.runtime import *')186 self.writeline('filename = %r' % self.filename)187 self.writeline('context = TemplateContext(global_context, '188 'make_undefined, filename)')189190 # generate the body render function.191 self.writeline('def body(context=context):', extra=1)192 frame = Frame()193 frame.inspect(node.body)194 self.pull_locals(frame)195 self.blockvisit(node.body, frame, True)196197 # top level changes to locals are pushed back to the198 # context of *this* template for include.199 self.indent()200 self.writeline('context.from_locals(locals())')201 self.outdent()202203 # at this point we now have the blocks collected and can visit them too.204 for name, block in self.blocks.iteritems():205 block_frame = Frame()206 block_frame.inspect(block.body)207 self.writeline('def block_%s(context=context):' % name, block, 1)208 self.pull_locals(block_frame)209 self.blockvisit(block.body, block_frame, True)210211 def visit_Block(self, node, frame):212 """Call a block and register it for the template."""213 if node.name in self.blocks:214 raise TemplateAssertionError("the block '%s' was already defined" %215 node.name, node.lineno,216 self.filename)217 self.blocks[node.name] = node218 self.writeline('for event in block_%s():' % node.name)219 self.indent()220 self.writeline('yield event')221 self.outdent()222223 def visit_Extends(self, node, frame):224 """Calls the extender."""225 self.writeline('extends(', node, 1)226 self.visit(node.template)227 self.write(', globals())')228229 def visit_For(self, node, frame):230 loop_frame = frame.inner()231 loop_frame.inspect(node.iter_child_nodes())232 loop_frame.identifiers.add_special('loop')233 extended_loop = bool(node.else_) or \234 'loop' in loop_frame.identifiers.undeclared235236 # make sure we "backup" overridden, local identifiers237 # TODO: we should probably optimize this and check if the238 # identifier is in use afterwards.239 aliases = {}240 for name in loop_frame.identifiers.find_shadowed():241 aliases[name] = ident = self.temporary_identifier()242 self.writeline('%s = l_%s' % (ident, name))243244 self.pull_locals(loop_frame, True)245246 self.newline(node)247 if node.else_:248 self.writeline('l_loop = None')249 self.write('for ')250 self.visit(node.target, loop_frame)251 self.write(extended_loop and ', l_loop in looper(' or ' in ')252 self.visit(node.iter, loop_frame)253 self.write(extended_loop and '):' or ':')254 self.blockvisit(node.body, loop_frame)255256 if node.else_:257 self.writeline('if l_loop is None:')258 self.blockvisit(node.else_, loop_frame)259260 # reset the aliases and clean them up261 for name, alias in aliases.iteritems():262 self.writeline('l_%s = %s; del %s' % (name, alias, alias))263264 def visit_If(self, node, frame):265 self.writeline('if ', node)266 self.visit(node.test, frame)267 self.write(':')268 self.blockvisit(node.body, frame)269 if node.else_:270 self.writeline('else:')271 self.blockvisit(node.else_, frame)272273 def visit_ExprStmt(self, node, frame):274 self.newline(node)275 self.visit(node, frame)276277 def visit_Output(self, node, frame):278 self.newline(node)279280 # try to evaluate as many chunks as possible into a static281 # string at compile time.282 body = []283 for child in node.nodes:284 try:285 const = unicode(child.as_const())286 except:287 body.append(child)288 continue289 if body and isinstance(body[-1], list):290 body[-1].append(const)291 else:292 body.append([const])293294 # if we have less than 3 nodes we just yield them295 if len(body) < 3:296 for item in body:297 if isinstance(item, list):298 self.writeline('yield %s' % repr(u''.join(item)))299 else:300 self.newline(item)301 self.write('yield unicode(')302 self.visit(item, frame)303 self.write(')')304305 # otherwise we create a format string as this is faster in that case306 else:307 format = []308 arguments = []309 for item in body:310 if isinstance(item, list):311 format.append(u''.join(item).replace('%', '%%'))312 else:313 format.append('%s')314 arguments.append(item)315 self.writeline('yield %r %% (' % u''.join(format))316 idx = -1317 for idx, argument in enumerate(arguments):318 if idx:319 self.write(', ')320 self.visit(argument, frame)321 self.write(idx == 0 and ',)' or ')')322323 def visit_Name(self, node, frame):324 # at this point we should only have locals left as the325 # blocks, macros and template body ensure that they are set.326 self.write('l_' + node.name)327328 def visit_Const(self, node, frame):329 val = node.value330 if isinstance(val, float):331 # XXX: add checks for infinity and nan332 self.write(str(val))333 else:334 self.write(repr(val))335336 def binop(operator):337 def visitor(self, node, frame):338 self.write('(')339 self.visit(node.left, frame)340 self.write(' %s ' % operator)341 self.visit(node.right, frame)342 self.write(')')343 return visitor344345 def uaop(operator):346 def visitor(self, node, frame):347 self.write('(' + operator)348 self.visit(node.node)349 self.write(')')350 return visitor351352 visit_Add = binop('+')353 visit_Sub = binop('-')354 visit_Mul = binop('*')355 visit_Div = binop('/')356 visit_FloorDiv = binop('//')357 visit_Pow = binop('**')358 visit_Mod = binop('%')359 visit_And = binop('and')360 visit_Or = binop('or')361 visit_Pos = uaop('+')362 visit_Neg = uaop('-')363 visit_Not = uaop('not ')364 del binop, uaop365366 def visit_Compare(self, node, frame):367 self.visit(node.expr, frame)368 for op in node.ops:369 self.visit(op, frame)370371 def visit_Operand(self, node, frame):372 self.write(' %s ' % operators[node.op])373 self.visit(node.expr, frame)374375 def visit_Subscript(self, node, frame):376 self.write('subscript(')377 self.visit(node.node, frame)378 self.write(', ')379 self.visit(node.arg, frame)380 self.write(')')
modified:jinja2/datastructure.py+15 added-10 removed
57 unmodified lines
58 token = self._stream.current59 if token.type == 'eof':60 self._stream.close()61 raise StopIteration()62 self._stream.next()62 self._stream.next(False)63 return token646566class TokenStream(object):
39 unmodified lines
106 """Got n tokens ahead."""107 for x in xrange(n):108 self.next()109110 def next(self, skip_eol=True):111 """Go one token ahead and return the old one"""110 def next(self):111 """Go one token ahead."""112 if self._pushed:113 self.current = self._pushed.popleft()114 elif self.current.type != 'eof':115 try:116 self.current = self._next()117 except StopIteration:118 self.close()112 rv = self.current113 while 1:114 if self._pushed:115 self.current = self._pushed.popleft()116 elif self.current.type is not 'eof':117 try:118 self.current = self._next()119 except StopIteration:120 self.close()121 if not skip_eol or self.current.type is not 'eol':122 break123 return rv124125 def close(self):126 """Close the stream."""127 self.current = Token(self.current.lineno, 'eof', '')
19 unmodified lines
modified:jinja2/exceptions.py+10 added-2 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""111213class TemplateError(RuntimeError):13class TemplateError(Exception):14 pass151617class TemplateNotFound(IOError, LookupError, TemplateError):
11 unmodified lines
29 Raised to tell the user that there is a problem with the template.30 """3132 def __init__(self, message, lineno, filename):33 SyntaxError.__init__(self, message)33 SyntaxError.__init__(self, '%s (line %s)' % (message, lineno))34 self.message = message35 self.lineno = lineno36 self.filename = filename373839class TemplateAssertionError(AssertionError, TemplateSyntaxError):4041 def __init__(self, message, lineno, filename):42 AssertionError.__init__(self, message)43 TemplateSyntaxError.__init__(self, message, lineno, filename)444546class TemplateRuntimeError(TemplateError):47 """48 Raised by the template engine if a tag encountered an error when49 rendering.
1 unmodified line
modified:jinja2/lexer.py+8 added-7 removed
32 unmodified lines
33whitespace_re = re.compile(r'\s+(?um)')34string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"35 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')36integer_re = re.compile(r'\d+')37name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')37name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')38float_re = re.compile(r'\d+\.\d+')39eol_re = re.compile(r'(\s*$\s*)+(?m)')404142# set of used keywords42keywords = set(['and', 'block', 'elif', 'else', 'endblock',43keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',44 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',45 'endtrans', 'extends', 'filter', 'for', 'if', 'in',46 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',46 'recursive', 'set', 'trans', 'call', 'endcall',47 'true', 'false', 'none'])47 'recursive', 'set', 'trans', 'call', 'endcall'])4849# bind operators to token types50operators = {51 '+': 'add',
25 unmodified lines
77}7879reverse_operators = dict([(v, k) for k, v in operators.iteritems()])80assert len(operators) == len(reverse_operators), 'operators dropped'81operator_re = re.compile('(%s)' % '|'.join([re.escape(x) for x in82 sorted(operators, key=lambda x: -len(x))]))81operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in82 sorted(operators, key=lambda x: -len(x))))8384simple_escapes = {85 'a': '\a',86 'n': '\n',
141 unmodified lines
228 e = re.escape229230 # lexing rules for tags231 tag_rules = [232 (eol_re, 'eol', None),233 (whitespace_re, None, None),234 (float_re, 'float', None),235 (integer_re, 'integer', None),235 (c('%s' % '|'.join(sorted(keywords, key=lambda x: -len(x)))),236 (c(r'\b(?:%s)\b' % '|'.join(sorted(keywords, key=lambda x: -len(x)))),237 'keyword', None),238 (name_re, 'name', None),239 (string_re, 'string', None),240 (operator_re, 'operator', None)
264 unmodified lines
modified:jinja2/nodes.py+91 added-60 removed
33 unmodified lines
34 '-': operator.neg35}363738def set_ctx(node, ctx):39 """40 Reset the context of a node and all child nodes. Per default the parser41 will all generate nodes that have a 'load' context as it's the most common42 one. This method is used in the parser to set assignment targets and43 other nodes to a store context.44 """45 todo = deque([node])46 while todo:47 node = todo.popleft()48 if 'ctx' in node._fields:49 node.ctx = ctx50 todo.extend(node.iter_child_nodes())383940class Impossible(Exception):41 """
3 unmodified lines
4546class NodeType(type):4748 def __new__(cls, name, bases, d):62 for attr in '_fields', '_attributes':49 for attr in 'fields', 'attributes':50 storage = []51 for base in bases:52 storage.extend(getattr(base, attr, ()))53 storage.extend(d.get(attr, ()))
3 unmodified lines
575859class Node(object):60 """74 Base jinja node.61 Baseclass for all Jinja nodes.62 """63 __metaclass__ = NodeType77 _fields = ()78 _attributes = ('lineno',)64 fields = ()65 attributes = ('lineno',)6667 def __init__(self, *args, **kw):68 if args:82 if len(args) != len(self._fields):83 if not self._fields:69 if len(args) != len(self.fields):70 if not self.fields:71 raise TypeError('%r takes 0 arguments' %72 self.__class__.__name__)73 raise TypeError('%r takes 0 or %d argument%s' % (74 self.__class__.__name__,88 len(self._fields),89 len(self._fields) != 1 and 's' or ''75 len(self.fields),76 len(self.fields) != 1 and 's' or ''77 ))91 for name, arg in izip(self._fields, args):78 for name, arg in izip(self.fields, args):79 setattr(self, name, arg)93 for attr in self._attributes:80 for attr in self.attributes:81 setattr(self, attr, kw.pop(attr, None))82 if kw:83 raise TypeError('unknown keyword argument %r' %84 iter(kw).next())8586 def iter_fields(self):87 """Iterate over all fields."""100 for name in self._fields:88 for name in self.fields:89 try:90 yield name, getattr(self, name)91 except AttributeError:92 pass9394 def iter_child_nodes(self):95 """Iterate over all child nodes."""96 for field, item in self.iter_fields():97 if isinstance(item, list):98 for n in item:99 if isinstance(n, Node):100 yield n101 elif isinstance(item, Node):102 yield item103104 def find(self, node_type):105 """Find the first node of a given type."""106 for result in self.find_all(node_type):107 return result108109 def find_all(self, node_type):110 """Find all the nodes of a given type."""111 for child in self.iter_child_nodes():112 if isinstance(child, node_type):113 yield child114 for result in child.find_all(node_type):115 yield result116117 def set_ctx(self, ctx):118 """119 Reset the context of a node and all child nodes. Per default the parser120 will all generate nodes that have a 'load' context as it's the most common121 one. This method is used in the parser to set assignment targets and122 other nodes to a store context.123 """124 todo = deque([self])125 while todo:126 node = todo.popleft()127 if 'ctx' in node.fields:128 node.ctx = ctx129 todo.extend(node.iter_child_nodes())130131 def __repr__(self):132 return '%s(%s)' % (133 self.__class__.__name__,134 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for119 arg in self._fields)135 arg in self.fields)136 )137138139class Stmt(Node):
11 unmodified lines
151class Template(Node):152 """153 Node that represents a template.154 """139 _fields = ('body',)155 fields = ('body',)156157158class Output(Stmt):159 """160 A node that holds multiple expressions which are then printed out. This161 is used both for the `print` statement and the regular template data.162 """147 _fields = ('nodes',)163 fields = ('nodes',)164165 def optimized_nodes(self):166 """Try to optimize the nodes."""167 buffer = []168 for node in self.nodes:169 try:170 const = unicode(node.as_const())171 except:172 buffer.append(node)173 else:174 if buffer and isinstance(buffer[-1], unicode):175 buffer[-1] += const176 else:177 buffer.append(const)178 return buffer179180181class Extends(Stmt):182 """183 Represents an extends statement.184 """154 _fields = ('extends',)185 fields = ('template',)186187188class For(Stmt):189 """190 A node that represents a for loop191 """161 _fields = ('target', 'iter', 'body', 'else_', 'recursive')192 fields = ('target', 'iter', 'body', 'else_', 'recursive')193194195class If(Stmt):196 """197 A node that represents an if condition.198 """168 _fields = ('test', 'body', 'else_')199 fields = ('test', 'body', 'else_')200201202class Macro(Stmt):203 """204 A node that represents a macro.205 """175 _fields = ('name', 'arguments', 'body')206 fields = ('name', 'args', 'defaults', 'dyn_args', 'dyn_kwargs', 'body')207208209class CallBlock(Stmt):210 """211 A node that represents am extended macro call.212 """182 _fields = ('expr', 'body')213 fields = ('call', 'body')214215216class Set(Stmt):217 """218 Allows defining own variables.219 """189 _fields = ('name', 'expr')220 fields = ('name', 'expr')221222223class FilterBlock(Stmt):224 """225 Node for filter sections.226 """196 _fields = ('body', 'filters')227 fields = ('body', 'filters')228229230class Block(Stmt):231 """232 A node that represents a block.233 """203 _fields = ('name', 'body')234 fields = ('name', 'body')235236237class Include(Stmt):238 """239 A node that represents the include tag.240 """210 _fields = ('template',)241 fields = ('template', 'target')242243244class Trans(Stmt):245 """246 A node for translatable sections.247 """217 _fields = ('singular', 'plural', 'indicator', 'replacements')248 fields = ('singular', 'plural', 'indicator', 'replacements')249250251class ExprStmt(Stmt):252 """253 A statement that evaluates an expression to None.254 """224 _fields = ('node',)255 fields = ('node',)256257258class Assign(Stmt):259 """260 Assigns an expression to a target.261 """231 _fields = ('target', 'node')262 fields = ('target', 'node')263264265class Expr(Node):266 """
17 unmodified lines
284class BinExpr(Expr):285 """286 Baseclass for all binary expressions.287 """257 _fields = ('left', 'right')288 fields = ('left', 'right')289 operator = None290291 def as_const(self):292 f = _binop_to_func[self.operator]
7 unmodified lines
300class UnaryExpr(Expr):301 """302 Baseclass for all unary expressions.303 """273 _fields = ('node',)304 fields = ('node',)305 operator = None306307 def as_const(self):308 f = _uaop_to_func[self.operator]
6 unmodified lines
315class Name(Expr):316 """317 any name such as {{ foo }}318 """288 _fields = ('name', 'ctx')319 fields = ('name', 'ctx')320321 def can_assign(self):291 return True322 return self.name not in ('true', 'false', 'none')323324325class Literal(Expr):326 """
4 unmodified lines
331class Const(Literal):332 """333 any constat such as {{ "foo" }}334 """304 _fields = ('value',)335 fields = ('value',)336337 def as_const(self):338 return self.value339
2 unmodified lines
342 """343 For loop unpacking and some other things like multiple arguments344 for subscripts.345 """315 _fields = ('items', 'ctx')346 fields = ('items', 'ctx')347348 def as_const(self):349 return tuple(x.as_const() for x in self.items)350
7 unmodified lines
358class List(Literal):359 """360 any list literal such as {{ [1, 2, 3] }}361 """331 _fields = ('items',)362 fields = ('items',)363364 def as_const(self):365 return [x.as_const() for x in self.items]366
1 unmodified line
368class Dict(Literal):369 """370 any dict literal such as {{ {1: 2, 3: 4} }}371 """341 _fields = ('items',)372 fields = ('items',)373374 def as_const(self):375 return dict(x.as_const() for x in self.items)376
1 unmodified line
378class Pair(Helper):379 """380 A key, value pair for dicts.381 """351 _fields = ('key', 'value')382 fields = ('key', 'value')383384 def as_const(self):385 return self.key.as_const(), self.value.as_const()386
1 unmodified line
388class CondExpr(Expr):389 """390 {{ foo if bar else baz }}391 """361 _fields = ('test', 'expr1', 'expr2')392 fields = ('test', 'expr1', 'expr2')393394 def as_const(self):395 if self.test.as_const():396 return self.expr1.as_const()
3 unmodified lines
400class Filter(Expr):401 """402 {{ foo|bar|baz }}403 """373 _fields = ('node', 'filters')404 fields = ('node', 'filters')405406407class FilterCall(Expr):408 """409 {{ |bar() }}410 """380 _fields = ('name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')411 fields = ('name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')412413414class Test(Expr):415 """416 {{ foo is lower }}417 """387 _fields = ('name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')418 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')419420421class Call(Expr):422 """423 {{ foo(bar) }}424 """394 _fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')425 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')426427428class Subscript(Expr):429 """430 {{ foo.bar }} and {{ foo['bar'] }} etc.431 """401 _fields = ('node', 'arg', 'ctx')432 fields = ('node', 'arg', 'ctx')433434 def as_const(self):435 try:436 return self.node.as_const()[self.node.as_const()]
7 unmodified lines
444class Slice(Expr):445 """446 1:2:3 etc.447 """417 _fields = ('start', 'stop', 'step')448 fields = ('start', 'stop', 'step')449450451class Concat(Expr):452 """453 For {{ foo ~ bar }}. Concatenates strings.454 """424 _fields = ('nodes',)455 fields = ('nodes',)456457 def as_const(self):458 return ''.join(unicode(x.as_const()) for x in self.nodes)459
1 unmodified line
461class Compare(Expr):462 """463 {{ foo == bar }}, {{ foo >= bar }} etc.464 """434 _fields = ('expr', 'ops')465 fields = ('expr', 'ops')466467468class Operand(Helper):469 """470 Operator + expression.471 """441 _fields = ('op', 'expr')472 fields = ('op', 'expr')473474475class Mul(BinExpr):476 """
70 unmodified lines
547 """548 operator = 'not'549550520class NegExpr(UnaryExpr):551class Neg(UnaryExpr):552 """553 {{ -foo }}554 """555 operator = '-'556557527class PosExpr(UnaryExpr):558class Pos(UnaryExpr):559 """560 {{ +foo }}561 """562 operator = '+'
modified:jinja2/parser.py+113 added-27 removed
12 unmodified lines
131415__all__ = ['Parser']1617_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'include'])17_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',18 'macro', 'include'])19_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])19_tuple_edge_tokens = set(['rparen', 'block_end', 'variable_end', 'in',20 'semicolon', 'recursive'])20_statement_end_tokens = set(['elif', 'else', 'endblock', 'endfilter',22 'endfor', 'endif', 'endmacro',23 'endcall', 'block_end'])21 'endfor', 'endif', 'endmacro', 'variable_end',22 'in', 'recursive', 'endcall', 'block_end'])232425class Parser(object):26 """
10 unmodified lines
37 filename = filename.encode('utf-8')38 self.source = source39 self.filename = filename40 self.closed = False42 self.blocks = set()41 self.no_variable_block = self.environment.lexer.no_variable_block42 self.stream = environment.lexer.tokenize(source, filename)4344 def end_statement(self):
12 unmodified lines
57 return getattr(self, 'parse_' + token_type)()58 elif token_type is 'call':59 self.stream.next()60 return self.parse_call_block()63 lineno = self.stream.current.lineno61 lineno = self.stream.current62 expr = self.parse_expression()63 if self.stream.current.type == 'assign':66 return self.parse_assign(expr)64 result = self.parse_assign(expr)65 else:66 result = nodes.ExprStmt(expr, lineno=lineno)67 self.end_statement()68 return nodes.ExprStmt(expr, lineno=lineno)68 return result6970 def parse_assign(self, target):71 """Parse an assign statement."""72 lineno = self.stream.expect('assign').lineno
2 unmodified lines
75 target, target.lineno,76 self.filename)77 expr = self.parse_tuple()78 self.end_statement()79 nodes.set_ctx(target, 'store')79 target.set_ctx('store')80 return nodes.Assign(target, expr, lineno=lineno)8182 def parse_statements(self, end_tokens, drop_needle=False):83 """
10 unmodified lines
94 result = self.subparse(end_tokens)95 else:96 result = []97 while self.stream.current.type not in end_tokens:98 if self.stream.current.type is 'block_end':99 self.stream.next()100 result.extend(self.subparse(end_tokens))101 break102 result.append(self.parse_statement())103 if drop_needle:104 self.stream.next()105 return result
1 unmodified line
107 def parse_for(self):108 """Parse a for loop."""109 lineno = self.stream.expect('for').lineno110 target = self.parse_tuple(simplified=True)107 nodes.set_ctx(target, 'store')111 if not target.can_assign():112 raise TemplateSyntaxError("can't assign to '%s'" %113 target, target.lineno,114 self.filename)115 target.set_ctx('store')116 self.stream.expect('in')117 iter = self.parse_tuple()118 if self.stream.current.type is 'recursive':119 self.stream.next()120 recursive = True121 else:122 recursive = False123 body = self.parse_statements(('endfor', 'else'))116 token_type = self.stream.current.type117 self.stream.next()118 if token_type is 'endfor':124 if self.stream.next().type is 'endfor':125 else_ = []126 else:127 else_ = self.parse_statements(('endfor',), drop_needle=True)128 return nodes.For(target, iter, body, else_, False, lineno=lineno)129130 def parse_if(self):125 pass131 """Parse an if construct."""132 node = result = nodes.If(lineno=self.stream.expect('if').lineno)133 while 1:134 # TODO: exclude conditional expressions here135 node.test = self.parse_tuple()136 node.body = self.parse_statements(('elif', 'else', 'endif'))137 token_type = self.stream.next().type138 if token_type is 'elif':139 new_node = nodes.If(lineno=self.stream.current.lineno)140 node.else_ = [new_node]141 node = new_node142 continue143 elif token_type is 'else':144 node.else_ = self.parse_statements(('endif',),145 drop_needle=True)146 else:147 node.else_ = []148 break149 return result150151 def parse_block(self):128 pass152 node = nodes.Block(lineno=self.stream.expect('block').lineno)153 node.name = self.stream.expect('name').value154 node.body = self.parse_statements(('endblock',), drop_needle=True)155 return node156157 def parse_extends(self):131 pass158 node = nodes.Extends(lineno=self.stream.expect('extends').lineno)159 node.template = self.parse_expression()160 self.end_statement()161 return node162163 def parse_include(self):134 pass164 node = nodes.Include(lineno=self.stream.expect('include').lineno)165 expr = self.parse_expression()166 if self.stream.current.type is 'assign':167 self.stream.next()168 if not expr.can_assign():169 raise TemplateSyntaxError('can\'t assign imported template '170 'to this expression.', expr.lineno,171 self.filename)172 expr.set_ctx('store')173 node.target = expr174 node.template = self.parse_expression()175 else:176 node.target = None177 node.template = expr178 self.end_statement()179 return node180181 def parse_call_block(self):137 pass182 node = nodes.CallBlock(lineno=self.stream.expect('call').lineno)183 node.call = self.parse_call()184 node.body = self.parse_statements(('endcall',), drop_needle=True)185 return node186187 def parse_macro(self):188 node = nodes.Macro(lineno=self.stream.expect('macro').lineno)189 node.name = self.stream.expect('name').value190 self.stream.expect('lparen')191 node.args = args = []192 node.defaults = defaults = []193 while self.stream.current.type is not 'rparen':194 if args:195 self.stream.expect('comma')196 token = self.stream.expect('name')197 arg = nodes.Name(token.value, 'param', lineno=token.lineno)198 if not arg.can_assign():199 raise TemplateSyntaxError("can't assign to '%s'" %200 arg.name, arg.lineno,201 self.filename)202 if self.stream.current.type is 'assign':203 self.stream.next()204 defaults.append(self.parse_expression())205 self.stream.expect('rparen')206 node.body = self.parse_statements(('endmacro',), drop_needle=True)207 return node208209 def parse_print(self):210 node = nodes.Output(lineno=self.stream.expect('print').lineno)211 node.nodes = []212 while self.stream.current.type not in _statement_end_tokens:213 if node.nodes:214 self.stream.expect('comma')215 node.nodes.append(self.parse_expression())216 self.end_statement()217 return node218219 def parse_expression(self):220 """Parse an expression."""221 return self.parse_condexpr()222
93 unmodified lines
316 left = self.parse_floordiv()317 while self.stream.current.type is 'div':318 self.stream.next()319 right = self.parse_floordiv()240 left = nodes.Floor(left, right, lineno=lineno)320 left = nodes.Div(left, right, lineno=lineno)321 lineno = self.stream.current.lineno322 return left323324 def parse_floordiv(self):
31 unmodified lines
356 lineno = self.stream.current.lineno357 if token_type is 'not':358 self.stream.next()359 node = self.parse_unary()280 return nodes.Neg(node, lineno=lineno)360 return nodes.Not(node, lineno=lineno)361 if token_type is 'sub':362 self.stream.next()363 node = self.parse_unary()284 return nodes.Sub(node, lineno=lineno)364 return nodes.Neg(node, lineno=lineno)365 if token_type is 'add':366 self.stream.next()367 node = self.parse_unary()368 return nodes.Pos(node, lineno=lineno)
40 unmodified lines
409 is_tuple = False410 while 1:411 if args:412 self.stream.expect('comma')333 if self.stream.current.type in _tuple_edge_tokens:413 if self.stream.current.type in _statement_end_tokens:414 break415 args.append(parse())416 if self.stream.current.type is not 'comma':417 break
50 unmodified lines
468469 def parse_subscript(self, node):470 token = self.stream.next()471 if token.type is 'dot':472 attr_token = self.stream.current392 if token.type not in ('name', 'integer'):473 if attr_token.type not in ('name', 'integer'):474 raise TemplateSyntaxError('expected name or number',394 token.lineno, self.filename)395 arg = nodes.Const(token.value, lineno=token.lineno)475 attr_token.lineno, self.filename)476 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)477 self.stream.next()478 elif token.type is 'lbracket':479 args = []480 while self.stream.current.type is not 'rbracket':
146 unmodified lines
627 add_data(nodes.Const(token.value, lineno=token.lineno))628 self.stream.next()629 elif token.type is 'variable_begin':630 self.stream.next()631 want_comma = False632 while not self.stream.current.type in _statement_end_tokens:633 if want_comma:634 self.stream.expect('comma')550 add_data(self.parse_tuple())635 add_data(self.parse_expression())636 want_comma = True637 self.stream.expect('variable_end')638 elif token.type is 'block_begin':639 flush_data()640 self.stream.next()
15 unmodified lines
added:jinja2/runtime.py+47 added
1# -*- coding: utf-8 -*-2"""3 jinja2.runtime4 ~~~~~~~~~~~~~~56 Runtime helpers.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11try:12 from collections import defaultdict13except ImportError:14 defaultdict = None151617__all__ = ['extends', 'TemplateContext']181920def extends(template, namespace):21 """22 This loads a template (and evaluates it) and replaces the blocks.23 """242526class TemplateContext(dict):2728 def __init__(self, globals, undefined_factory, filename):29 dict.__init__(self, globals)30 self.undefined_factory = undefined_factory31 self.filename = filename3233 # if there is a default dict, dict has a __missing__ method we can use.34 if defaultdict is None:35 def __getitem__(self, name):36 if name in self:37 return self[name]38 return self.undefined_factory(name)39 else:40 def __missing__(self, key):41 return self.undefined_factory(key)4243 def from_locals(self, mapping):44 """Update the template context from locals."""45 for key, value in mapping.iteritems():46 if key[:2] == 'l_':47 self[key[:-2]] = value
added:jinja2/visitor.py+81 added
1# -*- coding: utf-8 -*-2"""3 jinja2.visitor4 ~~~~~~~~~~~~~~56 This module implements a visitor for the nodes.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11from jinja2.nodes import Node121314class NodeVisitor(object):15 """16 Walks the abstract syntax tree and call visitor functions for every node17 found. The visitor functions may return values which will be forwarded18 by the `visit` method.1920 Per default the visitor functions for the nodes are ``'visit_'`` +21 class name of the node. So a `TryFinally` node visit function would22 be `visit_TryFinally`. This behavior can be changed by overriding23 the `get_visitor` function. If no visitor function exists for a node24 (return value `None`) the `generic_visit` visitor is used instead.25 """2627 def get_visitor(self, node):28 """29 Return the visitor function for this node or `None` if no visitor30 exists for this node. In that case the generic visit function is31 used instead.32 """33 method = 'visit_' + node.__class__.__name__34 return getattr(self, method, None)3536 def visit(self, node, *args, **kwargs):37 """Visit a node."""38 f = self.get_visitor(node)39 if f is not None:40 return f(node, *args, **kwargs)41 return self.generic_visit(node, *args, **kwargs)4243 def generic_visit(self, node, *args, **kwargs):44 """Called if no explicit visitor function exists for a node."""45 for node in node.iter_child_nodes():46 self.visit(node, *args, **kwargs)474849class NodeTransformer(NodeVisitor):50 """51 Walks the abstract syntax tree and allows modifications of nodes.5253 The `NodeTransformer` will walk the AST and use the return value of the54 visitor functions to replace or remove the old node. If the return55 value of the visitor function is `None` the node will be removed56 from the previous location otherwise it's replaced with the return57 value. The return value may be the original node in which case no58 replacement takes place.59 """6061 def generic_visit(self, node, *args, **kwargs):62 for field, old_value in node.iter_fields():63 if isinstance(old_value, list):64 new_values = []65 for value in old_value:66 if isinstance(value, Node):67 value = self.visit(value, *args, **kwargs)68 if value is None:69 continue70 elif not isinstance(value, Node):71 new_values.extend(value)72 continue73 new_values.append(value)74 old_value[:] = new_values75 elif isinstance(old_value, Node):76 new_node = self.visit(old_value, *args, **kwargs)77 if new_node is None:78 delattr(node, field)79 else:80 setattr(node, field, new_node)81 return node
added:test.py+16 added
1from jinja2 import Environment2from jinja2.compiler import generate345env = Environment()6ast = env.parse("""7Hello {{ name }}!. How is it {{ "going" }}. {{ [1, 2, 3] }}?8{% for name in user_names %}9 {{ loop.index }}: {{ name }}10 {% if loop.index % 2 == 0 %}...{% endif %}11{% endfor %}12Name again: {{ name }}!13""")14print ast15print16print generate(ast, "foo.html")