more compiler stuff
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 00d87ce · Browse files · 6 files·+287 added−211 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+287 added−211 removed
- other:+287 added−211 removed
Provenance
- Commit
8efc522- Tree
0dfcfc9- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
00d87ce
6 files changed+287 added−211 removed
modified:jinja2/compiler.py+181 added-21 removed
6 unmodified lines7 8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11+from copy import copy12 from random import randrange13 from operator import xor14 from cStringIO import StringIO15 from jinja2 import nodes58 unmodified lines74 class Frame(object):75 76 def __init__(self, parent=None):77 self.identifiers = Identifiers()78+ self.toplevel = False79 self.parent = parent80+ self.block = parent and parent.block or None81 if parent is not None:82 self.identifiers.declared.update(83 parent.identifiers.declared |84 parent.identifiers.undeclared |85 parent.identifiers.declared_locally |86 parent.identifiers.declared_parameter87 )88 89+ def copy(self):90+ """Create a copy of the current one."""91+ rv = copy(self)92+ rv.identifiers = copy(self)93+ return rv94+95 def inspect(self, nodes):96 """Walk the node and check for identifiers."""97 visitor = FrameIdentifierVisitor(self.identifiers)98 for node in nodes:22 unmodified lines121 """Macros set local."""122 self.identifiers.declared_locally.add(node.name)123 124 # stop traversing at instructions that have their own scope.116- visit_Block = visit_Call = visit_FilterBlock = \125+ visit_Block = visit_CallBlock = visit_FilterBlock = \126 visit_For = lambda s, n: None127 128 129 class CodeGenerator(NodeVisitor):17 unmodified lines147 148 def indent(self):149 self.indentation += 1150 142- def outdent(self):143- self.indentation -= 1151+ def outdent(self, step=1):152+ self.indentation -= step153 154 def blockvisit(self, nodes, frame, force_generator=False):155 self.indent()156 if force_generator:21 unmodified lines178 self.write('# line: %s' % node.lineno)179 self.new_lines = 1180 self._last_line = node.lineno181 182+ def signature(self, node, frame, have_comma=True):183+ have_comma = have_comma and [True] or []184+ def touch_comma():185+ if have_comma:186+ self.write(', ')187+ else:188+ have_comma.append(True)189+190+ for arg in node.args:191+ touch_comma()192+ self.visit(arg, frame)193+ for kwarg in node.kwargs:194+ touch_comma()195+ self.visit(kwarg, frame)196+ if node.dyn_args:197+ touch_comma()198+ self.visit(node.dyn_args, frame)199+ if node.dyn_kwargs:200+ touch_comma()201+ self.visit(node.dyn_kwargs, frame)202+203 def pull_locals(self, frame, no_indent=False):204 if not no_indent:205 self.indent()206 for name in frame.identifiers.undeclared:6 unmodified lines213 def visit_Template(self, node, frame=None):214 assert frame is None, 'no root frame allowed'215 self.writeline('from jinja2.runtime import *')216 self.writeline('filename = %r' % self.filename)187- self.writeline('context = TemplateContext(global_context, '217+ self.writeline('template_context = TemplateContext(global_context, '218 'make_undefined, filename)')219 190- # generate the body render function.191- self.writeline('def body(context=context):', extra=1)220+ # generate the root render function.221+ self.writeline('def root(context=template_context):', extra=1)222+ self.indent()223+ self.writeline('parent_root = None')224+ self.outdent()225 frame = Frame()226 frame.inspect(node.body)227+ frame.toplevel = True228 self.pull_locals(frame)229 self.blockvisit(node.body, frame, True)230 197- # top level changes to locals are pushed back to the198- # context of *this* template for include.231+ # make sure that the parent root is called.232 self.indent()200- self.writeline('context.from_locals(locals())')201- self.outdent()233+ self.writeline('if parent_root is not None:')234+ self.indent()235+ self.writeline('for event in parent_root(context):')236+ self.indent()237+ self.writeline('yield event')238+ self.outdent(3)239 240 # at this point we now have the blocks collected and can visit them too.241 for name, block in self.blocks.iteritems():242 block_frame = Frame()243 block_frame.inspect(block.body)244+ block_frame.block = name207- self.writeline('def block_%s(context=context):' % name, block, 1)245+ self.writeline('def block_%s(context):' % name, block, 1)246 self.pull_locals(block_frame)247 self.blockvisit(block.body, block_frame, True)248 249 def visit_Block(self, node, frame):2 unmodified lines252 raise TemplateAssertionError("the block '%s' was already defined" %253 node.name, node.lineno,254 self.filename)255 self.blocks[node.name] = node218- self.writeline('for event in block_%s():' % node.name)256+ self.writeline('for event in block_%s(context):' % node.name)257 self.indent()258 self.writeline('yield event')259 self.outdent()260 261 def visit_Extends(self, node, frame):262 """Calls the extender."""263+ if not frame.toplevel:264+ raise TemplateAssertionError('cannot use extend from a non '265+ 'top-level scope', node.lineno,266+ self.filename)267+ self.writeline('if parent_root is not None:')268+ self.indent()269+ self.writeline('raise TemplateRuntimeError(%r)' %270+ 'extended multiple times')271+ self.outdent()225- self.writeline('extends(', node, 1)226- self.visit(node.template)272+ self.writeline('parent_root = extends(', node, 1)273+ self.visit(node.template, frame)274 self.write(', globals())')275 276 def visit_For(self, node, frame):277 loop_frame = frame.inner()278 loop_frame.inspect(node.iter_child_nodes())232- loop_frame.identifiers.add_special('loop')279 extended_loop = bool(node.else_) or \280 'loop' in loop_frame.identifiers.undeclared281+ loop_frame.identifiers.add_special('loop')282 283 # make sure we "backup" overridden, local identifiers284 # TODO: we should probably optimize this and check if the285 # identifier is in use afterwards.17 unmodified lines303 if node.else_:304 self.writeline('if l_loop is None:')305 self.blockvisit(node.else_, loop_frame)306 260- # reset the aliases and clean them up307+ # reset the aliases and clean up308+ delete = set('l_' + x for x in loop_frame.identifiers.declared_locally309+ | loop_frame.identifiers.declared_parameter)310+ if extended_loop:311+ delete.add('l_loop')312 for name, alias in aliases.iteritems():262- self.writeline('l_%s = %s; del %s' % (name, alias, alias))313+ self.writeline('l_%s = %s' % (name, alias))314+ delete.add(alias)315+ delete.discard('l_' + name)316+ self.writeline('del %s' % ', '.join(delete))317 318 def visit_If(self, node, frame):319 self.writeline('if ', node)320 self.visit(node.test, frame)2 unmodified lines323 if node.else_:324 self.writeline('else:')325 self.blockvisit(node.else_, frame)326 327+ def visit_Macro(self, node, frame):328+ macro_frame = frame.inner()329+ macro_frame.inspect(node.body)330+ args = ['l_' + x.name for x in node.args]331+ if 'arguments' in macro_frame.identifiers.undeclared:332+ accesses_arguments = True333+ args.append('l_arguments')334+ else:335+ accesses_arguments = False336+ self.writeline('def macro(%s):' % ', '.join(args), node)337+ self.indent()338+ self.writeline('if 0: yield None')339+ self.outdent()340+ self.blockvisit(node.body, frame)341+ self.newline()342+ if frame.toplevel:343+ self.write('context[%r] = ' % node.name)344+ arg_tuple = ', '.join(repr(x.name) for x in node.args)345+ if len(node.args) == 1:346+ arg_tuple += ','347+ self.write('l_%s = Macro(macro, %r, (%s), %s)' % (348+ node.name, node.name,349+ arg_tuple, accesses_arguments350+ ))351+352 def visit_ExprStmt(self, node, frame):353 self.newline(node)354 self.visit(node, frame)355 42 unmodified lines398 self.write(', ')399 self.visit(argument, frame)400 self.write(idx == 0 and ',)' or ')')401 402+ def visit_Assign(self, node, frame):403+ self.newline(node)404+ # toplevel assignments however go into the local namespace and405+ # the current template's context. We create a copy of the frame406+ # here and add a set so that the Name visitor can add the assigned407+ # names here.408+ if frame.toplevel:409+ assignment_frame = frame.copy()410+ assignment_frame.assigned_names = set()411+ else:412+ assignment_frame = frame413+ self.visit(node.target, assignment_frame)414+ self.write(' = ')415+ self.visit(node.node, frame)416+ if frame.toplevel:417+ for name in assignment_frame.assigned_names:418+ self.writeline('context[%r] = l_%s' % (name, name))419+420 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.421+ if frame.toplevel and node.ctx == 'store':422+ frame.assigned_names.add(node.name)423 self.write('l_' + node.name)424 425 def visit_Const(self, node, frame):426 val = node.value2 unmodified lines429 self.write(str(val))430 else:431 self.write(repr(val))432 433+ def visit_Tuple(self, node, frame):434+ self.write('(')435+ idx = -1436+ for idx, item in enumerate(node.items):437+ if idx:438+ self.write(', ')439+ self.visit(item, frame)440+ self.write(idx == 0 and ',)' or ')')441+442 def binop(operator):443 def visitor(self, node, frame):444 self.write('(')445 self.visit(node.left, frame)32 unmodified lines478 self.write(' %s ' % operators[node.op])479 self.visit(node.expr, frame)480 481 def visit_Subscript(self, node, frame):482+ if isinstance(node.arg, nodes.Slice):483+ self.visit(node.node, frame)484+ self.write('[')485+ self.visit(node.arg, frame)486+ self.write(']')487+ return488+ try:489+ const = node.arg.as_const()490+ have_const = True491+ except nodes.Impossible:492+ have_const = False493+ if have_const:494+ if isinstance(const, (int, long, float)):495+ self.visit(node.node, frame)496+ self.write('[%s]' % const)497+ return376- self.write('subscript(')498+ self.write('subscribe(')499 self.visit(node.node, frame)500 self.write(', ')501+ if have_const:502+ self.write(repr(const))503+ else:379- self.visit(node.arg, frame)504+ self.visit(node.arg, frame)505+ self.write(', make_undefined)')506+507+ def visit_Slice(self, node, frame):508+ if node.start is not None:509+ self.visit(node.start, frame)510+ self.write(':')511+ if node.stop is not None:512+ self.visit(node.stop, frame)513+ if node.step is not None:514+ self.write(':')515+ self.visit(node.step, frame)516+517+ def visit_Filter(self, node, frame):518+ for filter in node.filters:519+ self.write('context.filters[%r](' % filter.name)520+ self.visit(node.node, frame)521+ for filter in reversed(node.filters):522+ self.signature(filter, frame)523+ self.write(')')524+525+ def visit_Test(self, node, frame):526+ self.write('context.tests[%r](')527+ self.visit(node.node, frame)528+ self.signature(node, frame)529 self.write(')')530+531+ def visit_Call(self, node, frame):532+ self.visit(node.node, frame)533+ self.write('(')534+ self.signature(node, frame, False)535+ self.write(')')536+537+ def visit_Keyword(self, node, frame):538+ self.visit(node.key, frame)539+ self.write('=')540+ self.visit(node.value, frame)modified:jinja2/datastructure.py+5 added-5 removed
94 unmodified lines95 self._pushed.append(token)96 97 def look(self):98 """Look at the next token."""99- old_token = self.current100- next = self.next()101- self.push(old_token)102- self.push(next)103- return next99+ old_token = self.next()100+ result = self.current101+ self.push(result)102+ self.current = old_token103+ return result104 105 def skip(self, n):106 """Got n tokens ahead."""107 for x in xrange(n):39 unmodified linesmodified:jinja2/nodes.py+67 added-164 removed
33 unmodified lines34 '-': operator.neg35 }36 37 38-39-38 class Impossible(Exception):41- """42- Raised if the node could not perform a requested action.43- """39+ """Raised if the node could not perform a requested action."""40 41 42 class NodeType(type):43+ """A metaclass for nodes that handles the field and attribute44+ inheritance. fields and attributes from the parent class are45+ automatically forwarded to the child."""46 47 def __new__(cls, name, bases, d):48 for attr in 'fields', 'attributes':49 storage = []5 unmodified lines55 return type.__new__(cls, name, bases, d)56 57 58 class Node(object):60- """61- Baseclass for all Jinja nodes.62- """59+ """Baseclass for all Jinja nodes."""60 __metaclass__ = NodeType61 fields = ()62 attributes = ('lineno',)63 47 unmodified lines111 for result in child.find_all(node_type):112 yield result113 114 def set_ctx(self, ctx):115+ """Reset the context of a node and all child nodes. Per default the116+ parser will all generate nodes that have a 'load' context as it's the117+ most common one. This method is used in the parser to set assignment118+ targets and other nodes to a store context.119 """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- """120 todo = deque([self])121 while todo:122 node = todo.popleft()123 if 'ctx' in node.fields:8 unmodified lines132 )133 134 135 class Stmt(Node):140- """141- Base node for all statements.142- """136+ """Base node for all statements."""137 138 139 class Helper(Node):146- """147- Nodes that exist in a specific context only.148- """140+ """Nodes that exist in a specific context only."""141 142 143 class Template(Node):152- """153- Node that represents a template.154- """144+ """Node that represents a template."""145 fields = ('body',)146 147 148 class Output(Stmt):149+ """A node that holds multiple expressions which are then printed out.150+ This is used both for the `print` statement and the regular template data.151 """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- """152 fields = ('nodes',)153 154 def optimized_nodes(self):155 """Try to optimize the nodes."""11 unmodified lines167 return buffer168 169 170 class Extends(Stmt):182- """183- Represents an extends statement.184- """171+ """Represents an extends statement."""172 fields = ('template',)173 174 175 class For(Stmt):189- """190- A node that represents a for loop191- """176+ """A node that represents a for loop"""177 fields = ('target', 'iter', 'body', 'else_', 'recursive')178 179 180 class If(Stmt):196- """197- A node that represents an if condition.198- """181+ """A node that represents an if condition."""182 fields = ('test', 'body', 'else_')183 184 185 class Macro(Stmt):203- """204- A node that represents a macro.205- """206- fields = ('name', 'args', 'defaults', 'dyn_args', 'dyn_kwargs', 'body')186+ """A node that represents a macro."""187+ fields = ('name', 'args', 'defaults', 'body')188 189 190 class CallBlock(Stmt):210- """211- A node that represents am extended macro call.212- """191+ """A node that represents am extended macro call."""192 fields = ('call', 'body')193 194 195 class Set(Stmt):217- """218- Allows defining own variables.219- """196+ """Allows defining own variables."""197 fields = ('name', 'expr')198 199 200 class FilterBlock(Stmt):224- """225- Node for filter sections.226- """201+ """Node for filter sections."""202 fields = ('body', 'filters')203 204 205 class Block(Stmt):231- """232- A node that represents a block.233- """206+ """A node that represents a block."""207 fields = ('name', 'body')208 209 210 class Include(Stmt):238- """239- A node that represents the include tag.240- """211+ """A node that represents the include tag."""212 fields = ('template', 'target')213 214 215 class Trans(Stmt):245- """246- A node for translatable sections.247- """216+ """A node for translatable sections."""217 fields = ('singular', 'plural', 'indicator', 'replacements')218 219 220 class ExprStmt(Stmt):252- """253- A statement that evaluates an expression to None.254- """221+ """A statement that evaluates an expression to None."""222 fields = ('node',)223 224 225 class Assign(Stmt):259- """260- Assigns an expression to a target.261- """226+ """Assigns an expression to a target."""227 fields = ('target', 'node')228 229 230 class Expr(Node):266- """267- Baseclass for all expressions.268- """231+ """Baseclass for all expressions."""232 233 def as_const(self):234+ """Return the value of the expression as constant or raise235+ `Impossible` if this was not possible.236 """272- Return the value of the expression as constant or raise `Impossible`273- if this was not possible.274- """237 raise Impossible()238 239 def can_assign(self):278- """279- Check if it's possible to assign something to this node.280- """240+ """Check if it's possible to assign something to this node."""241 return False242 243 244 class BinExpr(Expr):285- """286- Baseclass for all binary expressions.287- """245+ """Baseclass for all binary expressions."""246 fields = ('left', 'right')247 operator = None248 249 def as_const(self):250 f = _binop_to_func[self.operator]251 try:252 return f(self.left.as_const(), self.right.as_const())253 except:296- print self.left, f, self.right254 raise Impossible()255 256 257 class UnaryExpr(Expr):301- """302- Baseclass for all unary expressions.303- """258+ """Baseclass for all unary expressions."""259 fields = ('node',)260 operator = None261 262 def as_const(self):4 unmodified lines267 raise Impossible()268 269 270 class Name(Expr):316- """317- any name such as {{ foo }}318- """271+ """any name such as {{ foo }}"""272 fields = ('name', 'ctx')273 274 def can_assign(self):275 return self.name not in ('true', 'false', 'none')276 277 278 class Literal(Expr):326- """327- Baseclass for literals.328- """279+ """Baseclass for literals."""280 281 282 class Const(Literal):332- """333- any constat such as {{ "foo" }}334- """283+ """any constat such as {{ "foo" }}"""284 fields = ('value',)285 286 def as_const(self):287 return self.value288 289 290 class Tuple(Literal):342- """343- For loop unpacking and some other things like multiple arguments291+ """For loop unpacking and some other things like multiple arguments292 for subscripts.293 """294 fields = ('items', 'ctx')295 7 unmodified lines303 return True304 305 306 class List(Literal):359- """360- any list literal such as {{ [1, 2, 3] }}361- """307+ """any list literal such as {{ [1, 2, 3] }}"""308 fields = ('items',)309 310 def as_const(self):311 return [x.as_const() for x in self.items]312 313 314 class Dict(Literal):369- """370- any dict literal such as {{ {1: 2, 3: 4} }}371- """315+ """any dict literal such as {{ {1: 2, 3: 4} }}"""316 fields = ('items',)317 318 def as_const(self):319 return dict(x.as_const() for x in self.items)320 321 322 class Pair(Helper):379- """380- A key, value pair for dicts.381- """323+ """A key, value pair for dicts."""324 fields = ('key', 'value')325 326 def as_const(self):327 return self.key.as_const(), self.value.as_const()328 329 330+class Keyword(Helper):331+ """A key, value pair for keyword arguments."""332+ fields = ('key', 'value')333+334+335 class CondExpr(Expr):389- """390- {{ foo if bar else baz }}391- """336+ """{{ foo if bar else baz }}"""337 fields = ('test', 'expr1', 'expr2')338 339 def as_const(self):340 if self.test.as_const():1 unmodified line342 return self.expr2.as_const()343 344 345 class Filter(Expr):401- """402- {{ foo|bar|baz }}403- """346+ """{{ foo|bar|baz }}"""347 fields = ('node', 'filters')348 349 350 class FilterCall(Expr):408- """409- {{ |bar() }}410- """351+ """{{ |bar() }}"""352 fields = ('name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')353 354 355 class Test(Expr):415- """416- {{ foo is lower }}417- """356+ """{{ foo is lower }}"""357 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')358 359 360 class Call(Expr):422- """423- {{ foo(bar) }}424- """361+ """{{ foo(bar) }}"""362 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')363 364 365 class Subscript(Expr):429- """430- {{ foo.bar }} and {{ foo['bar'] }} etc.431- """366+ """{{ foo.bar }} and {{ foo['bar'] }} etc."""367 fields = ('node', 'arg', 'ctx')368 369 def as_const(self):370 try:5 unmodified lines376 return True377 378 379 class Slice(Expr):445- """446- 1:2:3 etc.447- """380+ """1:2:3 etc."""381 fields = ('start', 'stop', 'step')382 383 384 class Concat(Expr):452- """453- For {{ foo ~ bar }}. Concatenates strings.454- """385+ """For {{ foo ~ bar }}. Concatenates strings."""386 fields = ('nodes',)387 388 def as_const(self):389 return ''.join(unicode(x.as_const()) for x in self.nodes)390 391 392 class Compare(Expr):462- """463- {{ foo == bar }}, {{ foo >= bar }} etc.464- """393+ """{{ foo == bar }}, {{ foo >= bar }} etc."""394 fields = ('expr', 'ops')395 396 397 class Operand(Helper):469- """470- Operator + expression.471- """398+ """Operator + expression."""399 fields = ('op', 'expr')400 401 402 class Mul(BinExpr):476- """477- {{ foo * bar }}478- """403+ """{{ foo * bar }}"""404 operator = '*'405 406 407 class Div(BinExpr):483- """484- {{ foo / bar }}485- """408+ """{{ foo / bar }}"""409 operator = '/'410 411 412 class FloorDiv(BinExpr):490- """491- {{ foo // bar }}492- """413+ """{{ foo // bar }}"""414 operator = '//'415 416 417 class Add(BinExpr):497- """498- {{ foo + bar }}499- """418+ """{{ foo + bar }}"""419 operator = '+'420 421 422 class Sub(BinExpr):504- """505- {{ foo - bar }}506- """423+ """{{ foo - bar }}"""424 operator = '-'425 426 427 class Mod(BinExpr):511- """512- {{ foo % bar }}513- """428+ """{{ foo % bar }}"""429 operator = '%'430 431 432 class Pow(BinExpr):518- """519- {{ foo ** bar }}520- """433+ """{{ foo ** bar }}"""434 operator = '**'435 436 437 class And(BinExpr):525- """526- {{ foo and bar }}527- """438+ """{{ foo and bar }}"""439 operator = 'and'440 441 def as_const(self):442 return self.left.as_const() and self.right.as_const()443 444 445 class Or(BinExpr):535- """536- {{ foo or bar }}537- """446+ """{{ foo or bar }}"""447 operator = 'or'448 449 def as_const(self):450 return self.left.as_const() or self.right.as_const()451 452 453 class Not(UnaryExpr):545- """546- {{ not foo }}547- """454+ """{{ not foo }}"""455 operator = 'not'456 457 458 class Neg(UnaryExpr):552- """553- {{ -foo }}554- """459+ """{{ -foo }}"""460 operator = '-'461 462 463 class Pos(UnaryExpr):559- """560- {{ +foo }}561- """464+ """{{ +foo }}"""465 operator = '+'modified:jinja2/parser.py+4 added-3 removed
57 unmodified lines58 elif token_type is 'call':59 self.stream.next()60 return self.parse_call_block()61 lineno = self.stream.current62- expr = self.parse_expression()62+ expr = self.parse_tuple()63 if self.stream.current.type == 'assign':64 result = self.parse_assign(expr)65 else:66 result = nodes.ExprStmt(expr, lineno=lineno)134 unmodified lines201 self.filename)202 if self.stream.current.type is 'assign':203 self.stream.next()204 defaults.append(self.parse_expression())205+ args.append(arg)206 self.stream.expect('rparen')207 node.body = self.parse_statements(('endmacro',), drop_needle=True)208 return node209 345 unmodified lines555 if self.stream.current.type is 'name' and \556 self.stream.look().type is 'assign':557 key = self.stream.current.value558 self.stream.skip(2)558- kwargs.append(nodes.Pair(key, self.parse_expression(),559- lineno=key.lineno))559+ kwargs.append(nodes.Keyword(key, self.parse_expression(),560+ lineno=key.lineno))561 else:562 ensure(not kwargs)563 args.append(self.parse_expression())564 92 unmodified linesmodified:jinja2/runtime.py+23 added-12 removed
12 unmodified lines13 except ImportError:14 defaultdict = None15 16 17-__all__ = ['extends', 'TemplateContext']17+__all__ = ['extends', 'subscribe', 'TemplateContext']18 19 20 def extends(template, namespace):21- """22- This loads a template (and evaluates it) and replaces the blocks.23- """21+ """This loads a template (and evaluates it) and replaces the blocks."""22 23 24+def subscribe(obj, argument, undefined_factory):25+ """Get an item or attribute of an object."""26+ try:27+ return getattr(obj, argument)28+ except AttributeError:29+ try:30+ return obj[argument]31+ except LookupError:32+ return undefined_factory(attr=argument)33+34+35 class TemplateContext(dict):36 37 def __init__(self, globals, undefined_factory, filename):29- dict.__init__(self, globals)38+ dict.__init__(self)39+ self.globals = globals40 self.undefined_factory = undefined_factory41 self.filename = filename42+ self.filters = {}43+ self.tests = {}44 45 # if there is a default dict, dict has a __missing__ method we can use.46 if defaultdict is None:47 def __getitem__(self, name):48 if name in self:49 return self[name]50+ elif name in self.globals:51+ return self.globals[name]52 return self.undefined_factory(name)53 else:54 def __missing__(self, key):41- return self.undefined_factory(key)42-43- 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]] = value55+ try:56+ return self.globals[key]57+ except:58+ return self.undefined_factory(key)modified:test.py+7 added-6 removed
2 unmodified lines3 4 5 env = Environment()6 ast = env.parse("""7-Hello {{ 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 %}12-Name again: {{ name }}!7+{% (a, b), c = foo() %}8+{% macro foo(a, b, c=42) %}9+ 42 {{ arguments }}10+{% endmacro %}11+{% block body %}12+ {% bar = 23 %}13+{% endblock %}14 """)15 print ast16 print17 print generate(ast, "foo.html")