Merge branch 'feature/no-locals'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parents 65fbf32, d1a32e7 · Browse files · 15 files·+868 added−503 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+868 added−503 removed
- tests:+285 added−6 removed
- other:+583 added−497 removed
Provenance
- Commit
2ce56dd- Tree
40f1e8c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
65fbf32- Parent 2
d1a32e7
15 files changed+868 added−503 removed
modified:jinja2/compiler.py+255 added-469 removed
16 unmodified lines17 from jinja2.exceptions import TemplateAssertionError18 from jinja2.utils import Markup, concat, escape19 from jinja2._compat import range_type, text_type, string_types, \20 iteritems, NativeStringIO, imap21+from jinja2.idtracking import Symbols, VAR_LOAD_PARAMETER, \22+ VAR_LOAD_RESOLVE, VAR_LOAD_ALIAS, VAR_LOAD_UNDEFINED23 24 25 operators = {26 'eq': '==',21 unmodified lines48 code_features.append('generator_stop')49 except SyntaxError:50 pass51 52+# does this python version support yield from?53+try:54+ exec('def f(): yield from x()')55+except SyntaxError:56+ supports_yield_from = False57+else:58+ supports_yield_from = True59 51-# does if 0: dummy(x) get us x into the scope?52-def unoptimize_before_dead_code():53- x = 4254- def f():55- if 0: dummy(x)56- return f60 58-# The getattr is necessary for pypy which does not set this attribute if59-# no closure is on the function60-unoptimize_before_dead_code = bool(61- getattr(unoptimize_before_dead_code(), '__closure__', None))62-63-61 def generate(node, environment, name, filename, stream=None,62 defer_init=False):63 """Generate the python source for a node tree."""64 if not isinstance(node, nodes.Template):39 unmodified lines104 pass105 return visitor.undeclared106 107 111-class Identifiers(object):112- """Tracks the status of identifiers in frames."""108+class MacroRef(object):109 114- def __init__(self):115- # variables that are known to be declared (probably from outer116- # frames or because they are special for the frame)117- self.declared = set()110+ def __init__(self, node):111+ self.node = node112+ self.accesses_caller = False113+ self.accesses_kwargs = False114+ self.accesses_varargs = False115 119- # undeclared variables from outer scopes120- self.outer_undeclared = set()116 122- # names that are accessed without being explicitly declared by123- # this one or any of the outer scopes. Names can appear both in124- # declared and undeclared.125- self.undeclared = set()126-127- # names that are declared locally128- self.declared_locally = set()129-130- # names that are declared by parameters131- self.declared_parameter = set()132-133- def add_special(self, name):134- """Register a special name like `loop`."""135- self.undeclared.discard(name)136- self.declared.add(name)137-138- def is_declared(self, name):139- """Check if a name is declared in this or an outer scope."""140- if name in self.declared_locally or name in self.declared_parameter:141- return True142- return name in self.declared143-144- def copy(self):145- return deepcopy(self)146-147-117 class Frame(object):118 """Holds compile time information for us."""119 120 def __init__(self, eval_ctx, parent=None):121 self.eval_ctx = eval_ctx153- self.identifiers = Identifiers()122+ self.symbols = Symbols(parent and parent.symbols or None)123 124 # a toplevel frame is the root + soft frames such as if conditions.125 self.toplevel = False126 14 unmodified lines141 142 # the name of the block we're in, otherwise None.143 self.block = parent and parent.block or None144 176- # a set of actually assigned names177- self.assigned_names = set()178-145 # the parent of this frame146 self.parent = parent147 148 if parent is not None:183- self.identifiers.declared.update(184- parent.identifiers.declared |185- parent.identifiers.declared_parameter |186- parent.assigned_names187- )188- self.identifiers.outer_undeclared.update(189- parent.identifiers.undeclared -190- self.identifiers.declared191- )149 self.buffer = parent.buffer150 151 def copy(self):152 """Create a copy of the current one."""153 rv = object.__new__(self.__class__)154 rv.__dict__.update(self.__dict__)198- rv.identifiers = object.__new__(self.identifiers.__class__)199- rv.identifiers.__dict__.update(self.identifiers.__dict__)155+ rv.symbols = self.symbols.copy()156 return rv157 202- def inspect(self, nodes):203- """Walk the node and check for identifiers. If the scope is hard (eg:204- enforce on a python level) overrides from outer scopes are tracked205- differently.206- """207- visitor = FrameIdentifierVisitor(self.identifiers)208- for node in nodes:209- visitor.visit(node)210-211- def find_shadowed(self, extra=()):212- """Find all the shadowed names. extra is an iterable of variables213- that may be defined with `add_special` which may occour scoped.214- """215- i = self.identifiers216- return (i.declared | i.outer_undeclared) & \217- (i.declared_locally | i.declared_parameter) | \218- set(x for x in extra if i.is_declared(x))219-158 def inner(self):159 """Return an inner frame."""160 return Frame(self.eval_ctx, self)161 162 def soft(self):163 """Return a soft frame. A soft frame may not be modified as164 standalone thing as it shares the resources with the frame it165 was created of, but it's not a rootlevel frame any longer.166+167+ This is only used to implement if-statements.168 """169 rv = self.copy()170 rv.rootlevel = False171 return rv45 unmodified lines217 def visit_Block(self, node):218 """Stop visiting a blocks."""219 220 281-class FrameIdentifierVisitor(NodeVisitor):282- """A visitor for `Frame.inspect`."""283-284- def __init__(self, identifiers):285- self.identifiers = identifiers286-287- def visit_Name(self, node):288- """All assignments to names go through this function."""289- if node.ctx == 'store':290- self.identifiers.declared_locally.add(node.name)291- elif node.ctx == 'param':292- self.identifiers.declared_parameter.add(node.name)293- elif node.ctx == 'load' and not \294- self.identifiers.is_declared(node.name):295- self.identifiers.undeclared.add(node.name)296-297- def visit_If(self, node):298- self.visit(node.test)299- real_identifiers = self.identifiers300-301- old_names = real_identifiers.declared_locally | \302- real_identifiers.declared_parameter303-304- def inner_visit(nodes):305- if not nodes:306- return set()307- self.identifiers = real_identifiers.copy()308- for subnode in nodes:309- self.visit(subnode)310- rv = self.identifiers.declared_locally - old_names311- # we have to remember the undeclared variables of this branch312- # because we will have to pull them.313- real_identifiers.undeclared.update(self.identifiers.undeclared)314- self.identifiers = real_identifiers315- return rv316-317- body = inner_visit(node.body)318- else_ = inner_visit(node.else_ or ())319-320- # the differences between the two branches are also pulled as321- # undeclared variables322- real_identifiers.undeclared.update(body.symmetric_difference(else_) -323- real_identifiers.declared)324-325- # remember those that are declared.326- real_identifiers.declared_locally.update(body | else_)327-328- def visit_Macro(self, node):329- self.identifiers.declared_locally.add(node.name)330-331- def visit_Import(self, node):332- self.generic_visit(node)333- self.identifiers.declared_locally.add(node.target)334-335- def visit_FromImport(self, node):336- self.generic_visit(node)337- for name in node.names:338- if isinstance(name, tuple):339- self.identifiers.declared_locally.add(name[1])340- else:341- self.identifiers.declared_locally.add(name)342-343- def visit_Assign(self, node):344- """Visit assignments in the correct order."""345- self.visit(node.node)346- self.visit(node.target)347-348- def visit_For(self, node):349- """Visiting stops at for blocks. However the block sequence350- is visited as part of the outer scope.351- """352- self.visit(node.iter)353-354- def visit_CallBlock(self, node):355- self.visit(node.call)356-357- def visit_FilterBlock(self, node):358- self.visit(node.filter)359-360- def visit_AssignBlock(self, node):361- """Stop visiting at block assigns."""362-363- def visit_Scope(self, node):364- """Stop visiting at scopes."""365-366- def visit_Block(self, node):367- """Stop visiting at blocks."""368-369-221 class CompilerExit(Exception):222 """Raised if the compiler encountered a situation where it just223 doesn't make sense to further process the code. Any block that224 raises such an exception is not further processed.54 unmodified lines279 280 # the current indentation281 self._indentation = 0282 283+ # Tracks toplevel assignments284+ self._assign_stack = []285+286 # -- Various compilation helpers287 288 def fail(self, msg, lineno):289 """Fail with a :exc:`TemplateAssertionError`."""52 unmodified lines342 self.end_write(frame)343 344 def blockvisit(self, nodes, frame):345 """Visit a list of nodes as block in a frame. If the current frame492- is no buffer a dummy ``if 0: yield None`` is written automatically493- unless the force_generator parameter is set to False.346+ is no buffer a dummy ``if 0: yield None`` is written automatically.347 """495- if frame.buffer is None:496- self.writeline('if 0: yield None')497- else:498- self.writeline('pass')348 try:349+ if not nodes:350+ self.writeline('pass')351 for node in nodes:352 self.visit(node, frame)353 except CompilerExit:354 pass77 unmodified lines432 elif node.dyn_kwargs is not None:433 self.write(', **')434 self.visit(node.dyn_kwargs, frame)435 585- def pull_locals(self, frame):586- """Pull all the references identifiers into the local scope."""587- for name in frame.identifiers.undeclared:588- self.writeline('l_%s = context.resolve(%r)' % (name, name))589-436 def pull_dependencies(self, nodes):437 """Pull all the dependencies."""438 visitor = DependencyFinderVisitor()439 for node in nodes:5 unmodified lines445 mapping[name] = self.temporary_identifier()446 self.writeline('%s = environment.%s[%r]' %447 (mapping[name], dependency, name))448 603- def unoptimize_scope(self, frame):604- """Disable Python optimizations for the frame."""605- # XXX: this is not that nice but it has no real overhead. It606- # mainly works because python finds the locals before dead code607- # is removed. If that breaks we have to add a dummy function608- # that just accepts the arguments and does nothing.609- if frame.identifiers.declared:610- self.writeline('%sdummy(%s)' % (611- unoptimize_before_dead_code and 'if 0: ' or '',612- ', '.join('l_' + name for name in frame.identifiers.declared)613- ))449+ def enter_frame(self, frame):450+ undefs = []451+ for target, (action, param) in iteritems(frame.symbols.loads):452+ if action == VAR_LOAD_PARAMETER:453+ pass454+ elif action == VAR_LOAD_RESOLVE:455+ self.writeline('%s = resolve(%r)' %456+ (target, param))457+ elif action == VAR_LOAD_ALIAS:458+ self.writeline('%s = %s' % (target, param))459+ elif action == VAR_LOAD_UNDEFINED:460+ undefs.append(target)461+ else:462+ raise NotImplementedError('unknown load instruction')463+ if undefs:464+ self.writeline('%s = missing' % ' = '.join(undefs))465 615- def push_scope(self, frame, extra_vars=()):616- """This function returns all the shadowed variables in a dict617- in the form name: alias and will write the required assignments618- into the current scope. No indentation takes place.466+ def leave_frame(self, frame, with_python_scope=False):467+ if not with_python_scope:468+ undefs = []469+ for target, _ in iteritems(frame.symbols.loads):470+ undefs.append(target)471+ if undefs:472+ self.writeline('%s = missing' % ' = '.join(undefs))473 620- This also predefines locally declared variables from the loop621- body because under some circumstances it may be the case that622-623- `extra_vars` is passed to `Frame.find_shadowed`.624- """625- aliases = {}626- for name in frame.find_shadowed(extra_vars):627- aliases[name] = ident = self.temporary_identifier()628- self.writeline('%s = l_%s' % (ident, name))629- to_declare = set()630- for name in frame.identifiers.declared_locally:631- if name not in aliases:632- to_declare.add('l_' + name)633- if to_declare:634- self.writeline(' = '.join(to_declare) + ' = missing')635- return aliases636-637- def pop_scope(self, aliases, frame):638- """Restore all aliases and delete unused variables."""639- for name, alias in iteritems(aliases):640- self.writeline('l_%s = %s' % (name, alias))641- to_delete = set()642- for name in frame.identifiers.declared_locally:643- if name not in aliases:644- to_delete.add('l_' + name)645- if to_delete:646- # we cannot use the del statement here because enclosed647- # scopes can trigger a SyntaxError:648- # a = 42; b = lambda: a; del a649- self.writeline(' = '.join(to_delete) + ' = missing')650-474 def func(self, name):475 if self.environment.is_async:476 return 'async def %s' % name477 return 'def %s' % name478 656- def function_scoping(self, node, frame, children=None,657- find_special=True):658- """In Jinja a few statements require the help of anonymous659- functions. Those are currently macros and call blocks and in660- the future also recursive loops. As there is currently661- technical limitation that doesn't allow reading and writing a662- variable in a scope where the initial value is coming from an663- outer scope, this function tries to fall back with a common664- error message. Additionally the frame passed is modified so665- that the argumetns are collected and callers are looked up.479+ def macro_body(self, node, frame):480+ """Dump the function def of a macro or call block."""481+ frame = frame.inner()482+ frame.symbols.analyze_node(node)483+ macro_ref = MacroRef(node)484 667- This will return the modified frame.668- """669- # we have to iterate twice over it, make sure that works670- if children is None:671- children = node.iter_child_nodes()672- children = list(children)673- func_frame = frame.inner()674- func_frame.inspect(children)485+ args = []486+ for arg in node.args:487+ args.append(frame.symbols.ref(arg.name))488 676- # variables that are undeclared (accessed before declaration) and677- # declared locally *and* part of an outside scope raise a template678- # assertion error. Reason: we can't generate reasonable code from679- # it without aliasing all the variables.680- # this could be fixed in Python 3 where we have the nonlocal681- # keyword or if we switch to bytecode generation682- overridden_closure_vars = (683- func_frame.identifiers.undeclared &684- func_frame.identifiers.declared &685- (func_frame.identifiers.declared_locally |686- func_frame.identifiers.declared_parameter)687- )688- if overridden_closure_vars:689- self.fail('It\'s not possible to set and access variables '690- 'derived from an outer scope! (affects: %s)' %691- ', '.join(sorted(overridden_closure_vars)), node.lineno)692-693- # remove variables from a closure from the frame's undeclared694- # identifiers.695- func_frame.identifiers.undeclared -= (696- func_frame.identifiers.undeclared &697- func_frame.identifiers.declared698- )699-700- # no special variables for this scope, abort early701- if not find_special:702- return func_frame703-704- func_frame.accesses_kwargs = False705- func_frame.accesses_varargs = False706- func_frame.accesses_caller = False707- func_frame.arguments = args = ['l_' + x.name for x in node.args]708-709- undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))489+ undeclared = find_undeclared(node.body, ('caller', 'kwargs', 'varargs'))710-490 if 'caller' in undeclared:712- func_frame.accesses_caller = True713- func_frame.identifiers.add_special('caller')714- args.append('l_caller')491+ args.append(frame.symbols.declare_parameter('caller'))492+ macro_ref.accesses_caller = True493 if 'kwargs' in undeclared:716- func_frame.accesses_kwargs = True717- func_frame.identifiers.add_special('kwargs')718- args.append('l_kwargs')494+ args.append(frame.symbols.declare_parameter('kwargs'))495+ macro_ref.accesses_kwargs = True496 if 'varargs' in undeclared:720- func_frame.accesses_varargs = True721- func_frame.identifiers.add_special('varargs')722- args.append('l_varargs')723- return func_frame497+ args.append(frame.symbols.declare_parameter('varargs'))498+ macro_ref.accesses_varargs = True499 725- def macro_body(self, node, frame, children=None):726- """Dump the function def of a macro or call block."""727- frame = self.function_scoping(node, frame, children)500 # macros are delayed, they never require output checks501 frame.require_output_check = False730- args = frame.arguments731- # XXX: this is an ugly fix for the loop nesting bug732- # (tests.test_old_bugs.test_loop_call_bug). This works around733- # a identifier nesting problem we have in general. It's just more734- # likely to happen in loops which is why we work around it. The735- # real solution would be "nonlocal" all the identifiers that are736- # leaking into a new python frame and might be used both unassigned737- # and assigned.738- if 'loop' in frame.identifiers.declared:739- args = args + ['l_loop=l_loop']502+ frame.symbols.analyze_node(node)503 self.writeline('%s(%s):' % (self.func('macro'), ', '.join(args)), node)504 self.indent()505+506 self.buffer(frame)743- self.pull_locals(frame)507+ self.enter_frame(frame)508+509+ for idx, arg in enumerate(node.args):510+ self.writeline('if %s is missing:' % frame.symbols.ref(arg.name))511+ self.indent()512+ try:513+ default = node.defaults[idx - len(node.args)]514+ except IndexError:515+ self.writeline('%s = undefined(%r, name=%r)' % (516+ frame.symbols.ref(arg.name),517+ 'parameter %r was not provided' % arg.name,518+ arg.name))519+ else:520+ self.writeline('%s = ' % frame.symbols.ref(arg.name))521+ self.visit(default, frame)522+ self.outdent()523+524 self.blockvisit(node.body, frame)525 self.return_buffer_contents(frame)526+ self.leave_frame(frame, with_python_scope=True)527 self.outdent()747- return frame528 529+ return frame, macro_ref530+749- def macro_def(self, node, frame):531+ def macro_def(self, macro_ref, frame):532 """Dump the macro definition for the def created by macro_body."""751- arg_tuple = ', '.join(repr(x.name) for x in node.args)752- name = getattr(node, 'name', None)753- if len(node.args) == 1:533+ arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args)534+ name = getattr(macro_ref.node, 'name', None)535+ if len(macro_ref.node.args) == 1:536 arg_tuple += ','755- self.write('Macro(environment, macro, %r, (%s), (' %756- (name, arg_tuple))757- for arg in node.defaults:758- self.visit(arg, frame)759- self.write(', ')760- self.write('), %r, %r, %r)' % (761- bool(frame.accesses_kwargs),762- bool(frame.accesses_varargs),763- bool(frame.accesses_caller)764- ))537+ self.write('Macro(environment, macro, %r, (%s), %r, %r, %r)' %538+ (name, arg_tuple, macro_ref.accesses_kwargs,539+ macro_ref.accesses_varargs, macro_ref.accesses_caller))540 541 def position(self, node):542 """Return a human readable position for the node."""543 rv = 'line %d' % node.lineno544 if self.name is not None:545 rv += ' in ' + repr(self.name)546 return rv547 548+ def dump_local_context(self, frame):549+ return '{%s}' % ', '.join(550+ '%r: %s' % (name, target) for name, target551+ in iteritems(frame.symbols.dump_stores()))552+553+ def write_commons(self):554+ self.writeline('resolve = context.resolve_or_missing')555+ self.writeline('undefined = environment.undefined')556+ self.writeline('if 0: yield None')557+558 # -- Statement Visitors559 560 def visit_Template(self, node, frame=None):561 assert frame is None, 'no root frame allowed'1 unmodified line563 564 from jinja2.runtime import __all__ as exported565 self.writeline('from __future__ import %s' % ', '.join(code_features))566 self.writeline('from jinja2.runtime import ' + ', '.join(exported))782- if not unoptimize_before_dead_code:783- self.writeline('dummy = lambda *x: None')567 568 if self.environment.is_async:569 self.writeline('from jinja2.asyncsupport import auto_await, '570 'auto_aiter, make_async_loop_context')27 unmodified lines598 # add the load name599 self.writeline('name = %r' % self.name)600 601 # generate the root render function.819- self.writeline('%s(context%s):' % (self.func('root'), envenv), extra=1)602+ self.writeline('%s(context, missing=missing%s):' %603+ (self.func('root'), envenv), extra=1)604+ self.indent()605+ self.write_commons()606 607 # process the root608 frame = Frame(eval_ctx)823- frame.inspect(node.body)609+ if 'self' in find_undeclared(node.body, ('self',)):610+ ref = frame.symbols.declare_parameter('self')611+ self.writeline('%s = TemplateReference(context)' % ref)612+ frame.symbols.analyze_node(node)613 frame.toplevel = frame.rootlevel = True614 frame.require_output_check = have_extends and not self.has_known_extends826- self.indent()615 if have_extends:616 self.writeline('parent_template = None')829- if 'self' in find_undeclared(node.body, ('self',)):830- frame.identifiers.add_special('self')831- self.writeline('l_self = TemplateReference(context)')832- self.pull_locals(frame)617+ self.enter_frame(frame)618 self.pull_dependencies(node.body)619 self.blockvisit(node.body, frame)620+ self.leave_frame(frame, with_python_scope=True)621 self.outdent()622 623 # make sure that the parent root is called.624 if have_extends:625 if not self.has_known_extends:626 self.indent()627 self.writeline('if parent_template is not None:')628 self.indent()629+ if supports_yield_from:630+ self.writeline('yield from parent_template.'631+ 'root_render_func(context)')632+ else:843- self.writeline('for event in parent_template.'844- 'root_render_func(context):')845- self.indent()846- self.writeline('yield event')847- self.outdent(2 + (not self.has_known_extends))633+ self.writeline('for event in parent_template.'634+ 'root_render_func(context):')635+ self.indent()636+ self.writeline('yield event')637+ self.outdent()638+ self.outdent(1 + (not self.has_known_extends))639 640 # at this point we now have the blocks collected and can visit them too.641 for name, block in iteritems(self.blocks):851- block_frame = Frame(eval_ctx)852- block_frame.inspect(block.body)853- block_frame.block = name854- self.writeline('%s(context%s):' % (self.func('block_' + name), envenv),642+ self.writeline('%s(context, missing=missing%s):' %643+ (self.func('block_' + name), envenv),644 block, 1)645 self.indent()646+ self.write_commons()647+ # It's important that we do not make this frame a child of the648+ # toplevel template. This would cause a variety of649+ # interesting issues with identifier tracking.650+ block_frame = Frame(eval_ctx)651 undeclared = find_undeclared(block.body, ('self', 'super'))652 if 'self' in undeclared:859- block_frame.identifiers.add_special('self')860- self.writeline('l_self = TemplateReference(context)')653+ ref = block_frame.symbols.declare_parameter('self')654+ self.writeline('%s = TemplateReference(context)' % ref)655 if 'super' in undeclared:862- block_frame.identifiers.add_special('super')863- self.writeline('l_super = context.super(%r, '864- 'block_%s)' % (name, name))865- self.pull_locals(block_frame)656+ ref = block_frame.symbols.declare_parameter('super')657+ self.writeline('%s = context.super(%r, '658+ 'block_%s)' % (ref, name, name))659+ block_frame.symbols.analyze_node(block)660+ block_frame.block = name661+ self.enter_frame(block_frame)662 self.pull_dependencies(block.body)663 self.blockvisit(block.body, block_frame)664+ self.leave_frame(block_frame, with_python_scope=True)665 self.outdent()666 667 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)668 for x in self.blocks),4 unmodified lines673 in self.debug_info))674 675 def visit_Block(self, node, frame):676 """Call a block and register it for the template."""880- level = 1677+ level = 0678 if frame.toplevel:679 # if we know that we are a child template, there is no need to680 # check if we are one681 if self.has_known_extends:1 unmodified line683 if self.extends_so_far > 0:684 self.writeline('if parent_template is None:')685 self.indent()686 level += 1890- context = node.scoped and 'context.derived(locals())' or 'context'687+ context = node.scoped and (688+ 'context.derived(%s)' % self.dump_local_context(frame)) or 'context'689 690+ if supports_yield_from and not self.environment.is_async:691+ self.writeline('yield from context.blocks[%r][0](%s)' % (692+ node.name, context), node)693+ else:892- loop = self.environment.is_async and 'async for' or 'for'893- self.writeline('%s event in context.blocks[%r][0](%s):' % (894- loop, node.name, context), node)895- self.indent()896- self.simple_write('event', frame)694+ loop = self.environment.is_async and 'async for' or 'for'695+ self.writeline('%s event in context.blocks[%r][0](%s):' % (696+ loop, node.name, context), node)697+ self.indent()698+ self.simple_write('event', frame)699+ self.outdent()700+701 self.outdent(level)702 703 def visit_Extends(self, node, frame):704 """Calls the extender."""43 unmodified lines748 self.extends_so_far += 1749 750 def visit_Include(self, node, frame):751 """Handles includes."""948- if node.with_context:949- self.unoptimize_scope(frame)752 if node.ignore_missing:753 self.writeline('try:')754 self.indent()755 17 unmodified lines773 self.outdent()774 self.writeline('else:')775 self.indent()776 777+ skip_event_yield = False778 if node.with_context:779 loop = self.environment.is_async and 'async for' or 'for'780 self.writeline('%s event in template.root_render_func('781 'template.new_context(context.parent, True, '979- 'locals())):' % loop)782+ '%s)):' % (loop, self.dump_local_context(frame)))783 elif self.environment.is_async:784 self.writeline('for event in (await '785 'template._get_default_module_async())'786 '._body_stream:')787 else:788+ if supports_yield_from:789+ self.writeline('yield from template._get_default_module()'790+ '._body_stream')791+ skip_event_yield = True792+ else:985- self.writeline('for event in template._get_default_module()'986- '._body_stream:')793+ self.writeline('for event in template._get_default_module()'794+ '._body_stream:')795 796+ if not skip_event_yield:988- self.indent()989- self.simple_write('event', frame)990- self.outdent()797+ self.indent()798+ self.simple_write('event', frame)799+ self.outdent()800 801 if node.ignore_missing:802 self.outdent()803 804 def visit_Import(self, node, frame):805 """Visit regular imports."""997- if node.with_context:998- self.unoptimize_scope(frame)999- self.writeline('l_%s = ' % node.target, node)806+ self.writeline('%s = ' % frame.symbols.ref(node.target), node)807 if frame.toplevel:808 self.write('context.vars[%r] = ' % node.target)809 if self.environment.is_async:810 self.write('await ')811 self.write('environment.get_template(')812 self.visit(node.template, frame)813 self.write(', %r).' % self.name)814 if node.with_context:1008- self.write('make_module%s(context.parent, True, locals())'1009- % (self.environment.is_async and '_async' or ''))815+ self.write('make_module%s(context.parent, True, %s)'816+ % (self.environment.is_async and '_async' or '',817+ self.dump_local_context(frame)))818 elif self.environment.is_async:819 self.write('_get_default_module_async()')820 else:821 self.write('_get_default_module()')822 if frame.toplevel and not node.target.startswith('_'):823 self.writeline('context.exported_vars.discard(%r)' % node.target)1016- frame.assigned_names.add(node.target)824 825 def visit_FromImport(self, node, frame):826 """Visit named imports."""827 self.newline(node)1 unmodified line829 % (self.environment.is_async and 'await ' or ''))830 self.visit(node.template, frame)831 self.write(', %r).' % self.name)832 if node.with_context:1026- self.write('make_module%s(context.parent, True)'1027- % (self.environment.is_async and '_async' or ''))833+ self.write('make_module%s(context.parent, True, %s)'834+ % (self.environment.is_async and '_async' or '',835+ self.dump_local_context(frame)))836 elif self.environment.is_async:837 self.write('_get_default_module_async()')838 else:839 self.write('_get_default_module()')4 unmodified lines844 if isinstance(name, tuple):845 name, alias = name846 else:847 alias = name1040- self.writeline('l_%s = getattr(included_template, '1041- '%r, missing)' % (alias, name))1042- self.writeline('if l_%s is missing:' % alias)848+ self.writeline('%s = getattr(included_template, '849+ '%r, missing)' % (frame.symbols.ref(alias), name))850+ self.writeline('if %s is missing:' % frame.symbols.ref(alias))851 self.indent()1044- self.writeline('l_%s = environment.undefined(%r %% '852+ self.writeline('%s = undefined(%r %% '853 'included_template.__name__, '854 'name=%r)' %855+ (frame.symbols.ref(alias),1047- (alias, 'the template %%r (imported on %s) does '1048- 'not export the requested name %s' % (856+ 'the template %%r (imported on %s) does '857+ 'not export the requested name %s' % (858 self.position(node),859 repr(name)860 ), name))861 self.outdent()862 if frame.toplevel:863 var_names.append(alias)864 if not alias.startswith('_'):865 discarded_names.append(alias)1057- frame.assigned_names.add(alias)866 867 if var_names:868 if len(var_names) == 1:869 name = var_names[0]1062- self.writeline('context.vars[%r] = l_%s' % (name, name))870+ self.writeline('context.vars[%r] = %s' %871+ (name, frame.symbols.ref(name)))872 else:873 self.writeline('context.vars.update({%s})' % ', '.join(1065- '%r: l_%s' % (name, name) for name in var_names874+ '%r: %s' % (name, frame.symbols.ref(name)) for name in var_names875 ))876 if discarded_names:877 if len(discarded_names) == 1:878 self.writeline('context.exported_vars.discard(%r)' %2 unmodified lines881 self.writeline('context.exported_vars.difference_'882 'update((%s))' % ', '.join(imap(repr, discarded_names)))883 884 def visit_For(self, node, frame):1076- # when calculating the nodes for the inner frame we have to exclude1077- # the iterator contents from it1078- children = node.iter_child_nodes(exclude=('iter',))1079- if node.recursive:1080- loop_frame = self.function_scoping(node, frame, children,1081- find_special=False)1082- else:1083- loop_frame = frame.inner()1084- loop_frame.inspect(children)885+ loop_frame = frame.inner()886+ else_frame = frame.inner()887 888 # try to figure out if we have an extended loop. An extended loop889 # is necessary if the loop is in recursive mode if the special loop890 # variable is accessed in the body.891 extended_loop = node.recursive or 'loop' in \892 find_undeclared(node.iter_child_nodes(893 only=('body',)), ('loop',))894 895+ loop_ref = None896+ if extended_loop:897+ loop_ref = loop_frame.symbols.declare_parameter('loop')898+ loop_frame.symbols.analyze_node(node)899+900+ if node.else_:901+ else_frame.symbols.analyze_node(node, for_branch='else')902+903 # if we don't have an recursive loop we have to find the shadowed904 # variables at that point. Because loops can be nested but the loop905 # variable is a special one we have to enforce aliasing for it.1096- if not node.recursive:1097- aliases = self.push_scope(loop_frame, ('loop',))1098-1099- # otherwise we set up a buffer and add a function def1100- else:906+ if node.recursive:907 self.writeline('%s(reciter, loop_render_func, depth=0):' %908 self.func('loop'), node)909 self.indent()910 self.buffer(loop_frame)1105- aliases = {}911 912 # make sure the loop variable is a special one and raise a template913 # assertion error if a loop tries to write to loop914 if extended_loop:1110- self.writeline('l_loop = missing')1111- loop_frame.identifiers.add_special('loop')915+ self.writeline('%s = missing' % loop_ref)916+917 for name in node.find_all(nodes.Name):918 if name.ctx == 'store' and name.name == 'loop':919 self.fail('Can\'t assign to special loop variable '920 'in for-loop target', name.lineno)921 1117- self.pull_locals(loop_frame)922 if node.else_:923 iteration_indicator = self.temporary_identifier()924 self.writeline('%s = 1' % iteration_indicator)925 1122- # Create a fake parent loop if the else or test section of a1123- # loop is accessing the special loop variable and no parent loop1124- # exists.1125- if 'loop' not in aliases and 'loop' in find_undeclared(1126- node.iter_child_nodes(only=('else_', 'test')), ('loop',)):1127- self.writeline("l_loop = environment.undefined(%r, name='loop')" %1128- ("'loop' is undefined. the filter section of a loop as well "1129- "as the else block don't have access to the special 'loop'"1130- " variable of the current loop. Because there is no parent "1131- "loop it's undefined. Happened in loop on %s" %1132- self.position(node)))1133-926 self.writeline(self.environment.is_async and 'async for ' or 'for ', node)927 self.visit(node.target, loop_frame)928 if extended_loop:929 if self.environment.is_async:1138- self.write(', l_loop in await make_async_loop_context(')930+ self.write(', %s in await make_async_loop_context(' % loop_ref)931 else:1140- self.write(', l_loop in LoopContext(')932+ self.write(', %s in LoopContext(' % loop_ref)933 else:934 self.write(' in ')935 936 # if we have an extened loop and a node test, we filter in the12 unmodified lines949 self.visit(node.iter, loop_frame)950 if self.environment.is_async:951 self.write(')')952 self.write(' if (')1161- test_frame = loop_frame.copy()1162- self.visit(node.test, test_frame)953+ self.visit(node.test, loop_frame)954 self.write('))')955 956 elif node.recursive:957 self.write('reciter')8 unmodified lines966 self.write(', loop_render_func, depth):')967 else:968 self.write(extended_loop and '):' or ':')969 970+ self.indent()971+ self.enter_frame(loop_frame)972+973 # tests in not extended loops become a continue974 if not extended_loop and node.test is not None:1181- self.indent()975 self.writeline('if not ')976 self.visit(node.test, loop_frame)977 self.write(':')978 self.indent()979 self.writeline('continue')1187- self.outdent(2)980+ self.outdent()981 1189- self.indent()982 self.blockvisit(node.body, loop_frame)983 if node.else_:984 self.writeline('%s = 0' % iteration_indicator)985 self.outdent()986+ self.leave_frame(loop_frame, with_python_scope=node.recursive987+ and not node.else_)988 989 if node.else_:990 self.writeline('if %s:' % iteration_indicator)991 self.indent()992+ self.enter_frame(else_frame)1198- self.blockvisit(node.else_, loop_frame)993+ self.blockvisit(node.else_, else_frame)994+ self.leave_frame(else_frame)995 self.outdent()996 1201- # reset the aliases if there are any.1202- if not node.recursive:1203- self.pop_scope(aliases, loop_frame)1204-997 # if the node was recursive we have to return the buffer contents998 # and start the iteration code999 if node.recursive:1000 self.return_buffer_contents(loop_frame)24 unmodified lines1025 self.blockvisit(node.else_, if_frame)1026 self.outdent()1027 1028 def visit_Macro(self, node, frame):1237- macro_frame = self.macro_body(node, frame)1029+ macro_frame, macro_ref = self.macro_body(node, frame)1030 self.newline()1031 if frame.toplevel:1032 if not node.name.startswith('_'):1033 self.write('context.exported_vars.add(%r)' % node.name)1034+ ref = frame.symbols.ref(node.name)1035 self.writeline('context.vars[%r] = ' % node.name)1243- self.write('l_%s = ' % node.name)1244- self.macro_def(node, macro_frame)1245- frame.assigned_names.add(node.name)1036+ self.write('%s = ' % frame.symbols.ref(node.name))1037+ self.macro_def(macro_ref, macro_frame)1038 1039 def visit_CallBlock(self, node, frame):1248- children = node.iter_child_nodes(exclude=('call',))1249- call_frame = self.macro_body(node, frame, children)1040+ call_frame, macro_ref = self.macro_body(node, frame)1041 self.writeline('caller = ')1251- self.macro_def(node, call_frame)1042+ self.macro_def(macro_ref, call_frame)1043 self.start_write(frame, node)1044 self.visit_Call(node.call, call_frame, forward_caller=True)1045 self.end_write(frame)1046 1047 def visit_FilterBlock(self, node, frame):1048 filter_frame = frame.inner()1258- filter_frame.inspect(node.iter_child_nodes())1259- aliases = self.push_scope(filter_frame)1260- self.pull_locals(filter_frame)1049+ filter_frame.symbols.analyze_node(node)1050+ self.enter_frame(filter_frame)1051 self.buffer(filter_frame)1052 self.blockvisit(node.body, filter_frame)1053 self.start_write(frame, node)1054 self.visit_Filter(node.filter, filter_frame)1055 self.end_write(frame)1266- self.pop_scope(aliases, filter_frame)1056+ self.leave_frame(filter_frame)1057 1058 def visit_ExprStmt(self, node, frame):1059 self.newline(node)1060 self.visit(node.node, frame)78 unmodified lines1139 else:1140 self.newline(item)1141 close = 11142 if frame.eval_ctx.volatile:1353- self.write('(context.eval_ctx.autoescape and'1354- ' escape or to_string)(')1143+ self.write('(escape if context.eval_ctx.autoescape'1144+ ' else to_string)(')1145 elif frame.eval_ctx.autoescape:1146 self.write('escape(')1147 else:1148 self.write('to_string(')28 unmodified lines1177 for argument in arguments:1178 self.newline(argument)1179 close = 01180 if frame.eval_ctx.volatile:1391- self.write('(context.eval_ctx.autoescape and'1392- ' escape or to_string)(')1181+ self.write('(escape if context.eval_ctx.autoescape else'1182+ ' to_string)(')1183 close += 11184 elif frame.eval_ctx.autoescape:1185 self.write('escape(')1186 close += 116 unmodified lines1203 1204 if outdent_later:1205 self.outdent()1206 1417- def make_assignment_frame(self, frame):1418- # toplevel assignments however go into the local namespace and1419- # the current template's context. We create a copy of the frame1420- # here and add a set so that the Name visitor can add the assigned1421- # names here.1422- if not frame.toplevel:1423- return frame1424- assignment_frame = frame.copy()1425- assignment_frame.toplevel_assignments = set()1426- return assignment_frame1207+ def push_assign_tracking(self):1208+ self._assign_stack.append(set())1209 1428- def export_assigned_vars(self, frame, assignment_frame):1429- if not frame.toplevel:1210+ def pop_assign_tracking(self, frame):1211+ vars = self._assign_stack.pop()1212+ if not frame.toplevel or not vars:1213 return1431- public_names = [x for x in assignment_frame.toplevel_assignments1432- if not x.startswith('_')]1433- if len(assignment_frame.toplevel_assignments) == 1:1434- name = next(iter(assignment_frame.toplevel_assignments))1435- self.writeline('context.vars[%r] = l_%s' % (name, name))1214+ public_names = [x for x in vars if x[:1] != '_']1215+ if len(vars) == 1:1216+ name = next(iter(vars))1217+ ref = frame.symbols.ref(name)1218+ self.writeline('context.vars[%r] = %s' % (name, ref))1219 else:1220 self.writeline('context.vars.update({')1438- for idx, name in enumerate(assignment_frame.toplevel_assignments):1221+ for idx, name in enumerate(vars):1222 if idx:1223 self.write(', ')1441- self.write('%r: l_%s' % (name, name))1224+ ref = frame.symbols.ref(name)1225+ self.write('%r: %s' % (name, ref))1226 self.write('})')1227 if public_names:1228 if len(public_names) == 1:1229 self.writeline('context.exported_vars.add(%r)' %2 unmodified lines1232 self.writeline('context.exported_vars.update((%s))' %1233 ', '.join(imap(repr, public_names)))1234 1235 def visit_Assign(self, node, frame):1236+ self.push_assign_tracking()1237 self.newline(node)1453- assignment_frame = self.make_assignment_frame(frame)1454- self.visit(node.target, assignment_frame)1238+ self.visit(node.target, frame)1239 self.write(' = ')1240 self.visit(node.node, frame)1457- self.export_assigned_vars(frame, assignment_frame)1241+ self.pop_assign_tracking(frame)1242 1243 def visit_AssignBlock(self, node, frame):1244+ self.push_assign_tracking()1245 block_frame = frame.inner()1246 # This is a special case. Since a set block always captures we1247 # will disable output checks. This way one can use set blocks1248 # toplevel even in extended templates.1249 block_frame.require_output_check = False1465- block_frame.inspect(node.body)1466- aliases = self.push_scope(block_frame)1467- self.pull_locals(block_frame)1250+ block_frame.symbols.analyze_node(node)1251+ self.enter_frame(block_frame)1252 self.buffer(block_frame)1253 self.blockvisit(node.body, block_frame)1470- self.pop_scope(aliases, block_frame)1471-1472- assignment_frame = self.make_assignment_frame(frame)1254 self.newline(node)1474- self.visit(node.target, assignment_frame)1255+ self.visit(node.target, frame)1256 self.write(' = concat(%s)' % block_frame.buffer)1476- self.export_assigned_vars(frame, assignment_frame)1257+ self.pop_assign_tracking(frame)1258+ self.leave_frame(block_frame)1259 1260 # -- Expression Visitors1261 1262 def visit_Name(self, node, frame):1263 if node.ctx == 'store' and frame.toplevel:1482- frame.toplevel_assignments.add(node.name)1483- self.write('l_' + node.name)1484- frame.assigned_names.add(node.name)1264+ if self._assign_stack and node.name[:1] != '_':1265+ self._assign_stack[-1].add(node.name)1266+ ref = frame.symbols.ref(node.name)1267+ if node.ctx == 'load':1268+ self.write('(undefined(name=%r) if %s is missing else %s)' %1269+ (node.name, ref, ref))1270+ else:1271+ self.write(ref)1272 1273 def visit_Const(self, node, frame):1274 val = node.value1275 if isinstance(val, float):4 unmodified lines1280 def visit_TemplateData(self, node, frame):1281 try:1282 self.write(repr(node.as_const(frame.eval_ctx)))1283 except nodes.Impossible:1497- self.write('(context.eval_ctx.autoescape and Markup or identity)(%r)'1284+ self.write('(Markup if context.eval_ctx.autoescape else identity)(%r)'1285 % node.data)1286 1287 def visit_Tuple(self, node, frame):1288 self.write('(')158 unmodified lines1447 def visit_CondExpr(self, node, frame):1448 def write_expr2():1449 if node.expr2 is not None:1450 return self.visit(node.expr2, frame)1664- self.write('environment.undefined(%r)' % ('the inline if-'1451+ self.write('undefined(%r)' % ('the inline if-'1452 'expression on %s evaluated to false and '1453 'no else section was defined.' % self.position(node)))1454 1455 self.write('(')56 unmodified lines1512 self.writeline('break', node)1513 1514 def visit_Scope(self, node, frame):1515 scope_frame = frame.inner()1729- scope_frame.inspect(node.iter_child_nodes())1730- aliases = self.push_scope(scope_frame)1731- self.pull_locals(scope_frame)1516+ scope_frame.symbols.analyze_node(node)1517+ self.enter_frame(scope_frame)1518 self.blockvisit(node.body, scope_frame)1733- self.pop_scope(aliases, scope_frame)1519+ self.leave_frame(scope_frame)1520 1521 def visit_EvalContextModifier(self, node, frame):1522 for keyword in node.options:1523 self.writeline('context.eval_ctx.%s = ' % keyword.key)17 unmodified linesmodified:jinja2/debug.py+31 added-9 removed
193 unmodified lines194 195 return ProcessedTraceback(exc_info[0], exc_info[1], frames)196 197 198+def get_jinja_locals(real_locals):199+ ctx = real_locals.get('context')200+ if ctx:201+ locals = ctx.get_all()202+ else:203+ locals = {}204+205+ local_overrides = {}206+207+ for name, value in iteritems(real_locals):208+ if not name.startswith('l_') or value is missing:209+ continue210+ try:211+ _, depth, name = name.split('_', 2)212+ depth = int(depth)213+ except ValueError:214+ continue215+ cur_depth = local_overrides.get(name, (-1,))[0]216+ if cur_depth < depth:217+ local_overrides[name] = (depth, value)218+219+ for name, (_, value) in iteritems(local_overrides):220+ if value is missing:221+ locals.pop(name, None)222+ else:223+ locals[name] = value224+225+ return locals226+227+228 def fake_exc_info(exc_info, filename, lineno):229 """Helper for `translate_exception`."""230 exc_type, exc_value, tb = exc_info231 232 # figure the real context out233 if tb is not None:204- real_locals = tb.tb_frame.f_locals.copy()205- ctx = real_locals.get('context')206- if ctx:207- locals = ctx.get_all()208- else:209- locals = {}210- for name, value in iteritems(real_locals):211- if name.startswith('l_') and value is not missing:212- locals[name[2:]] = value234+ locals = get_jinja_locals(tb.tb_frame.f_locals)235 236 # if there is a local called __jinja_exception__, we get237 # rid of it to not break the debug functionality.238 locals.pop('__jinja_exception__', None)134 unmodified linesmodified:jinja2/environment.py+12 added-2 removed
86 unmodified lines87 result[extension.identifier] = extension(environment)88 return result89 90 91+def fail_for_missing_callable(string, name):92+ msg = string % name93+ if isinstance(name, Undefined):94+ try:95+ name._fail_with_undefined_error()96+ except Exception as e:97+ msg = '%s (%s; did you forget to quote the callable name?)' % (msg, e)98+ raise TemplateRuntimeError(msg)99+100+101 def _environment_sanity_check(environment):102 """Perform a sanity check on the environment."""103 assert issubclass(environment.undefined, Undefined), 'undefined must ' \104 'be a subclass of undefined because filters depend on it.'343 unmodified lines448 .. versionadded:: 2.7449 """450 func = self.filters.get(name)451 if func is None:442- raise TemplateRuntimeError('no filter named %r' % name)452+ fail_for_missing_callable('no filter named %r', name)453 args = [value] + list(args or ())454 if getattr(func, 'contextfilter', False):455 if context is None:456 raise TemplateRuntimeError('Attempted to invoke context '16 unmodified lines473 .. versionadded:: 2.7474 """475 func = self.tests.get(name)476 if func is None:467- raise TemplateRuntimeError('no test named %r' % name)477+ fail_for_missing_callable('no test named %r', name)478 return func(value, *(args or ()), **(kwargs or {}))479 480 @internalcode481 def parse(self, source, name=None, filename=None):797 unmodified linesadded:jinja2/idtracking.py+232 added
1+from jinja2.visitor import NodeVisitor2+from jinja2._compat import iteritems3+4+5+VAR_LOAD_PARAMETER = 'param'6+VAR_LOAD_RESOLVE = 'resolve'7+VAR_LOAD_ALIAS = 'alias'8+VAR_LOAD_UNDEFINED = 'undefined'9+10+11+def find_symbols(nodes, parent_symbols=None):12+ sym = Symbols(parent=parent_symbols)13+ visitor = FrameSymbolVisitor(sym)14+ for node in nodes:15+ visitor.visit(node)16+ return sym17+18+19+def symbols_for_node(node, parent_symbols=None):20+ sym = Symbols(parent=parent_symbols)21+ sym.analyze_node(node)22+ return sym23+24+25+class Symbols(object):26+27+ def __init__(self, parent=None):28+ if parent is None:29+ self.level = 030+ else:31+ self.level = parent.level + 132+ self.parent = parent33+ self.refs = {}34+ self.loads = {}35+ self.stores = set()36+37+ def analyze_node(self, node, **kwargs):38+ visitor = RootVisitor(self)39+ visitor.visit(node, **kwargs)40+41+ def _define_ref(self, name, load=None):42+ ident = 'l_%d_%s' % (self.level, name)43+ self.refs[name] = ident44+ if load is not None:45+ self.loads[ident] = load46+ return ident47+48+ def find_ref(self, name):49+ if name in self.refs:50+ return self.refs[name]51+ if self.parent is not None:52+ return self.parent.find_ref(name)53+54+ def ref(self, name):55+ rv = self.find_ref(name)56+ if rv is None:57+ raise AssertionError('Tried to resolve a name to a reference that '58+ 'was unknown to the frame (%r)' % name)59+ return rv60+61+ def copy(self):62+ rv = object.__new__(self.__class__)63+ rv.__dict__.update(self.__dict__)64+ rv.refs = self.refs.copy()65+ rv.loads = self.loads.copy()66+ rv.stores = self.stores.copy()67+ return rv68+69+ def store(self, name):70+ # We already have that name locally, so we can just bail71+ if name not in self.refs:72+ self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))73+ self.stores.add(name)74+75+ def declare_parameter(self, name):76+ self.stores.add(name)77+ return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))78+79+ def load(self, name):80+ target = self.find_ref(name)81+ if target is None:82+ self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))83+84+ def branch_update(self, branch_symbols):85+ stores = {}86+ for branch in branch_symbols:87+ for target in branch.stores:88+ if target in self.stores:89+ continue90+ stores[target] = stores.get(target, 0) + 191+92+ for sym in branch_symbols:93+ self.refs.update(sym.refs)94+ self.loads.update(sym.loads)95+ self.stores.update(sym.stores)96+97+ for name, branch_count in iteritems(stores):98+ if branch_count == len(branch_symbols):99+ continue100+ target = self.find_ref(name)101+ assert target is not None, 'should not happen'102+103+ if self.parent is not None:104+ outer_target = self.parent.find_ref(name)105+ if outer_target is not None:106+ self.loads[target] = (VAR_LOAD_ALIAS, outer_target)107+ continue108+ self.loads[target] = (VAR_LOAD_RESOLVE, name)109+110+ def dump_stores(self):111+ rv = {}112+ node = self113+ while node is not None:114+ for name in node.stores:115+ if name not in rv:116+ rv[name] = self.find_ref(name)117+ node = node.parent118+ return rv119+120+121+class RootVisitor(NodeVisitor):122+123+ def __init__(self, symbols):124+ self.sym_visitor = FrameSymbolVisitor(symbols)125+126+ def _simple_visit(self, node, **kwargs):127+ for child in node.iter_child_nodes():128+ self.sym_visitor.visit(child)129+130+ visit_Template = visit_Block = visit_Macro = visit_FilterBlock = \131+ visit_Scope = visit_If = visit_ScopedEvalContextModifier = \132+ _simple_visit133+134+ def visit_AssignBlock(self, node, **kwargs):135+ for child in node.body:136+ self.sym_visitor.visit(child)137+138+ def visit_CallBlock(self, node, **kwargs):139+ for child in node.iter_child_nodes(exclude=('call',)):140+ self.sym_visitor.visit(child)141+142+ def visit_For(self, node, for_branch='body', **kwargs):143+ if node.test is not None:144+ self.sym_visitor.visit(node.test)145+ if for_branch == 'body':146+ self.sym_visitor.visit(node.target, store_as_param=True)147+ branch = node.body148+ elif for_branch == 'else':149+ branch = node.else_150+ else:151+ raise RuntimeError('Unknown for branch')152+ for item in branch or ():153+ self.sym_visitor.visit(item)154+155+ def generic_visit(self, node, *args, **kwargs):156+ raise NotImplementedError('Cannot find symbols for %r' %157+ node.__class__.__name__)158+159+160+class FrameSymbolVisitor(NodeVisitor):161+ """A visitor for `Frame.inspect`."""162+163+ def __init__(self, symbols):164+ self.symbols = symbols165+166+ def visit_Name(self, node, store_as_param=False, **kwargs):167+ """All assignments to names go through this function."""168+ if store_as_param or node.ctx == 'param':169+ self.symbols.declare_parameter(node.name)170+ elif node.ctx == 'store':171+ self.symbols.store(node.name)172+ elif node.ctx == 'load':173+ self.symbols.load(node.name)174+175+ def visit_If(self, node, **kwargs):176+ self.visit(node.test, **kwargs)177+178+ original_symbols = self.symbols179+180+ def inner_visit(nodes):181+ self.symbols = rv = original_symbols.copy()182+ for subnode in nodes:183+ self.visit(subnode, **kwargs)184+ self.symbols = original_symbols185+ return rv186+187+ body_symbols = inner_visit(node.body)188+ else_symbols = inner_visit(node.else_ or ())189+190+ self.symbols.branch_update([body_symbols, else_symbols])191+192+ def visit_Macro(self, node, **kwargs):193+ self.symbols.store(node.name)194+195+ def visit_Import(self, node, **kwargs):196+ self.generic_visit(node, **kwargs)197+ self.symbols.store(node.target)198+199+ def visit_FromImport(self, node, **kwargs):200+ self.generic_visit(node, **kwargs)201+ for name in node.names:202+ if isinstance(name, tuple):203+ self.symbols.store(name[1])204+ else:205+ self.symbols.store(name)206+207+ def visit_Assign(self, node, **kwargs):208+ """Visit assignments in the correct order."""209+ self.visit(node.node, **kwargs)210+ self.visit(node.target, **kwargs)211+212+ def visit_For(self, node, **kwargs):213+ """Visiting stops at for blocks. However the block sequence214+ is visited as part of the outer scope.215+ """216+ self.visit(node.iter, **kwargs)217+218+ def visit_CallBlock(self, node, **kwargs):219+ self.visit(node.call, **kwargs)220+221+ def visit_FilterBlock(self, node, **kwargs):222+ self.visit(node.filter, **kwargs)223+224+ def visit_AssignBlock(self, node, **kwargs):225+ """Stop visiting at block assigns."""226+ self.visit(node.target, **kwargs)227+228+ def visit_Scope(self, node, **kwargs):229+ """Stop visiting at scopes."""230+231+ def visit_Block(self, node, **kwargs):232+ """Stop visiting at blocks."""modified:jinja2/meta.py+6 added-3 removed
9 unmodified lines10 :license: BSD, see LICENSE for more details.11 """12 from jinja2 import nodes13 from jinja2.compiler import CodeGenerator14-from jinja2._compat import string_types14+from jinja2._compat import string_types, iteritems15 16 17 class TrackingCodeGenerator(CodeGenerator):18 """We abuse the code generator for introspection."""5 unmodified lines24 25 def write(self, x):26 """Don't write."""27 28- def pull_locals(self, frame):28+ def enter_frame(self, frame):29 """Remember all undeclared identifiers."""30- self.undeclared_identifiers.update(frame.identifiers.undeclared)30+ CodeGenerator.enter_frame(self, frame)31+ for _, (action, param) in iteritems(frame.symbols.loads):32+ if action == 'resolve':33+ self.undeclared_identifiers.add(param)34 35 36 def find_undeclared_variables(ast):37 """Returns a set of all variables in the AST that will be looked up from69 unmodified linesmodified:jinja2/nodes.py+29 added
240 unmodified lines241 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for242 arg in self.fields)243 )244 245+ def dump(self):246+ def _dump(node):247+ if not isinstance(node, Node):248+ buf.append(repr(node))249+ return250 251+ buf.append('nodes.%s(' % node.__class__.__name__)252+ if not node.fields:253+ buf.append(')')254+ return255+ for idx, field in enumerate(node.fields):256+ if idx:257+ buf.append(', ')258+ value = getattr(node, field)259+ if isinstance(value, list):260+ buf.append('[')261+ for idx, item in enumerate(value):262+ if idx:263+ buf.append(', ')264+ _dump(item)265+ buf.append(']')266+ else:267+ _dump(value)268+ buf.append(')')269+ buf = []270+ _dump(self)271+ return ''.join(buf)272+273+274+275 class Stmt(Node):276 """Base node for all statements."""277 abstract = True278 670 unmodified linesmodified:jinja2/runtime.py+16 added-14 removed
22 unmodified lines23 # these variables are exported to the template runtime24 __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',25 'TemplateRuntimeError', 'missing', 'concat', 'escape',26 'markup_join', 'unicode_join', 'to_string', 'identity',27- 'TemplateNotFound', 'make_logging_undefined']27+ 'TemplateNotFound']28 29 #: the name of the function that is used to convert something into30 #: a string. We can just use the text type here.31 to_string = text_type33 unmodified lines65 # if the parent is shared a copy should be created because66 # we don't want to modify the dict passed67 if shared:68 parent = dict(parent)69- for key, value in iteritems(locals):70- if key[:2] == 'l_' and value is not missing:71- parent[key[2:]] = value69+ parent.update(locals or ())70 return environment.context_class(environment, parent, template_name,71 blocks)72 73 73 unmodified lines147 def resolve(self, key):148 """Looks up a variable like `__getitem__` or `get` but returns an149 :class:`Undefined` object with the name of the name looked up.150 """151+ rv = self.resolve_or_missing(key)152+ if rv is missing:153+ return self.environment.undefined(name=key)154+ return rv155+156+ def resolve_or_missing(self, key):157+ """Resolves a variable like :meth:`resolve` but returns the158+ special `missing` value if it cannot be found.159+ """160 if key in self.vars:161 return self.vars[key]162 if key in self.parent:163 return self.parent[key]157- return self.environment.undefined(name=key)164+ return missing165 166 def get_exported(self):167 """Get a new dict with the exported variables."""168 return dict((k, self.vars[k]) for k in self.exported_vars)69 unmodified lines238 def __getitem__(self, key):239 """Lookup a variable or raise `KeyError` if the variable is240 undefined.241 """235- item = self.resolve(key)236- if isinstance(item, Undefined):242+ item = self.resolve_or_missing(key)243+ if item is missing:244 raise KeyError(key)245 return item246 247 def __repr__(self):148 unmodified lines396 397 class Macro(object):398 """Wraps a macro function."""399 393- def __init__(self, environment, func, name, arguments, defaults,400+ def __init__(self, environment, func, name, arguments,401 catch_kwargs, catch_varargs, caller):402 self._environment = environment403 self._func = func404 self._argument_count = len(arguments)405 self.name = name406 self.arguments = arguments400- self.defaults = defaults407 self.catch_kwargs = catch_kwargs408 self.catch_varargs = catch_varargs409 self.caller = caller410 10 unmodified lines421 for idx, name in enumerate(self.arguments[len(arguments):]):422 try:423 value = kwargs.pop(name)424 except KeyError:419- try:420- value = self.defaults[idx - self._argument_count + off]421- except IndexError:422- value = self._environment.undefined(423- 'parameter %r was not provided' % name, name=name)425+ value = missing426 arguments.append(value)427 428 # it's important that the order of these arguments does not change429 # if not also changed in the compiler's `function_scoping` method.249 unmodified linesmodified:tests/test_api.py+1 added-1 removed
327 unmodified lines328 assert tmpl.render() == 'bar'329 330 def test_custom_context(self):331 class CustomContext(Context):332- def resolve(self, key):332+ def resolve_or_missing(self, key):333 return 'resolve-' + key334 335 class CustomEnvironment(Environment):336 context_class = CustomContext4 unmodified linesmodified:tests/test_core_tags.py+6 added-3 removed
18 unmodified lines19 20 21 @pytest.mark.core_tags22 @pytest.mark.for_loop23-class TestForLoop():23+class TestForLoop(object):24 25 def test_simple(self, env):26 tmpl = env.from_string('{% for item in seq %}{{ item }}{% endfor %}')27 assert tmpl.render(seq=list(range(10))) == '0123456789'2 unmodified lines30 tmpl = env.from_string(31 '{% for item in seq %}XXX{% else %}...{% endfor %}')32 assert tmpl.render() == '...'33 34+ def test_else_scoping_item(self, env):35+ tmpl = env.from_string(36+ '{% for item in [] %}{% else %}{{ item }}{% endfor %}')37+ assert tmpl.render(item=42) == '42'38+39 def test_empty_blocks(self, env):40 tmpl = env.from_string('<{% for item in seq %}{% else %}{% endfor %}>')41 assert tmpl.render() == '<>'42 264 unmodified lines307 '{% macro foo(a, b) %}{% endmacro %}'308 '{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}'309 '{% macro baz() %}{{ caller() }}{% endmacro %}')310 assert tmpl.module.foo.arguments == ('a', 'b')306- assert tmpl.module.foo.defaults == ()311 assert tmpl.module.foo.name == 'foo'312 assert not tmpl.module.foo.caller313 assert not tmpl.module.foo.catch_kwargs314 assert not tmpl.module.foo.catch_varargs315 assert tmpl.module.bar.arguments == ()312- assert tmpl.module.bar.defaults == ()316 assert not tmpl.module.bar.caller317 assert tmpl.module.bar.catch_kwargs318 assert tmpl.module.bar.catch_varargs319 assert tmpl.module.baz.caller21 unmodified linesmodified:tests/test_debug.py+14 added-1 removed
25 unmodified lines26 return Environment(loader=filesystem_loader)27 28 29 @pytest.mark.debug30-class TestDebug():30+class TestDebug(object):31 32 def assert_traceback_matches(self, callback, expected_tb):33 try:34 callback()35 unmodified lines70 File ".*debug.pyc?", line \d+, in test71 raise TemplateSyntaxError\('wtf', 42\)72 (jinja2\.exceptions\.)?TemplateSyntaxError: wtf73 line 42''')74+75+ def test_local_extraction(self):76+ from jinja2.debug import get_jinja_locals77+ from jinja2.runtime import missing78+ locals = get_jinja_locals({79+ 'l_0_foo': 42,80+ 'l_1_foo': 23,81+ 'l_2_foo': 13,82+ 'l_0_bar': 99,83+ 'l_1_bar': missing,84+ 'l_0_baz': missing,85+ })86+ assert locals == {'foo': 13, 'bar': 99}modified:tests/test_ext.py+1 added-1 removed
366 unmodified lines367 # quite hacky, but the only way to properly test that. The idea is368 # that the generated code does not pass num twice (although that369 # would work) for better performance. This only works on the370 # newstyle gettext of course371- assert re.search(r"l_ngettext, u?'\%\(num\)s apple', u?'\%\(num\)s "371+ assert re.search(r"u?'\%\(num\)s apple', u?'\%\(num\)s "372 r"apples', 3", source) is not None373 374 def test_trans_vars(self):375 t1 = newstyle_i18n_env.get_template('transvars1.html')92 unmodified linesadded:tests/test_idtracking.py+218 added
1+import pytest2+3+from jinja2 import nodes4+from jinja2.idtracking import symbols_for_node5+6+7+def test_basics():8+ for_loop = nodes.For(9+ nodes.Name('foo', 'store'),10+ nodes.Name('seq', 'load'),11+ [nodes.Output([nodes.Name('foo', 'load')])],12+ [], None, False)13+ tmpl = nodes.Template([14+ nodes.Assign(15+ nodes.Name('foo', 'store'),16+ nodes.Name('bar', 'load')),17+ for_loop])18+19+ sym = symbols_for_node(tmpl)20+ assert sym.refs == {21+ 'foo': 'l_0_foo',22+ 'bar': 'l_0_bar',23+ 'seq': 'l_0_seq',24+ }25+ assert sym.loads == {26+ 'l_0_foo': ('undefined', None),27+ 'l_0_bar': ('resolve', 'bar'),28+ 'l_0_seq': ('resolve', 'seq'),29+ }30+31+ sym = symbols_for_node(for_loop, sym)32+ assert sym.refs == {33+ 'foo': 'l_1_foo',34+ }35+ assert sym.loads == {36+ 'l_1_foo': ('param', None),37+ }38+39+40+def test_complex():41+ title_block = nodes.Block('title', [42+ nodes.Output([nodes.TemplateData(u'Page Title')])43+ ], False)44+45+ render_title_macro = nodes.Macro('render_title', [nodes.Name('title', 'param')], [], [46+ nodes.Output([47+ nodes.TemplateData(u'\n <div class="title">\n <h1>'),48+ nodes.Name('title', 'load'),49+ nodes.TemplateData(u'</h1>\n <p>'),50+ nodes.Name('subtitle', 'load'),51+ nodes.TemplateData(u'</p>\n ')]),52+ nodes.Assign(53+ nodes.Name('subtitle', 'store'), nodes.Const('something else')),54+ nodes.Output([55+ nodes.TemplateData(u'\n <p>'),56+ nodes.Name('subtitle', 'load'),57+ nodes.TemplateData(u'</p>\n </div>\n'),58+ nodes.If(59+ nodes.Name('something', 'load'), [60+ nodes.Assign(nodes.Name('title_upper', 'store'),61+ nodes.Filter(nodes.Name('title', 'load'),62+ 'upper', [], [], None, None)),63+ nodes.Output([64+ nodes.Name('title_upper', 'load'),65+ nodes.Call(nodes.Name('render_title', 'load'), [66+ nodes.Const('Aha')], [], None, None)])], [])])])67+68+ for_loop = nodes.For(69+ nodes.Name('item', 'store'),70+ nodes.Name('seq', 'load'), [71+ nodes.Output([72+ nodes.TemplateData(u'\n <li>'),73+ nodes.Name('item', 'load'),74+ nodes.TemplateData(u'</li>\n <span>')]),75+ nodes.Include(nodes.Const('helper.html'), True, False),76+ nodes.Output([77+ nodes.TemplateData(u'</span>\n ')])], [], None, False)78+79+ body_block = nodes.Block('body', [80+ nodes.Output([81+ nodes.TemplateData(u'\n '),82+ nodes.Call(nodes.Name('render_title', 'load'), [83+ nodes.Name('item', 'load')], [], None, None),84+ nodes.TemplateData(u'\n <ul>\n ')]),85+ for_loop,86+ nodes.Output([nodes.TemplateData(u'\n </ul>\n')])],87+ False)88+89+ tmpl = nodes.Template([90+ nodes.Extends(nodes.Const('layout.html')),91+ title_block,92+ render_title_macro,93+ body_block,94+ ])95+96+ tmpl_sym = symbols_for_node(tmpl)97+ assert tmpl_sym.refs == {98+ 'render_title': 'l_0_render_title',99+ }100+ assert tmpl_sym.loads == {101+ 'l_0_render_title': ('undefined', None),102+ }103+ assert tmpl_sym.stores == set(['render_title'])104+ assert tmpl_sym.dump_stores() == {105+ 'render_title': 'l_0_render_title',106+ }107+108+ macro_sym = symbols_for_node(render_title_macro, tmpl_sym)109+ assert macro_sym.refs == {110+ 'subtitle': 'l_1_subtitle',111+ 'something': 'l_1_something',112+ 'title': 'l_1_title',113+ 'title_upper': 'l_1_title_upper',114+ }115+ assert macro_sym.loads == {116+ 'l_1_subtitle': ('resolve', 'subtitle'),117+ 'l_1_something': ('resolve','something'),118+ 'l_1_title': ('param', None),119+ 'l_1_title_upper': ('resolve', 'title_upper'),120+ }121+ assert macro_sym.stores == set(['title', 'title_upper', 'subtitle'])122+ assert macro_sym.find_ref('render_title') == 'l_0_render_title'123+ assert macro_sym.dump_stores() == {124+ 'title': 'l_1_title',125+ 'title_upper': 'l_1_title_upper',126+ 'subtitle': 'l_1_subtitle',127+ 'render_title': 'l_0_render_title',128+ }129+130+ body_sym = symbols_for_node(body_block)131+ assert body_sym.refs == {132+ 'item': 'l_0_item',133+ 'seq': 'l_0_seq',134+ 'render_title': 'l_0_render_title',135+ }136+ assert body_sym.loads == {137+ 'l_0_item': ('resolve', 'item'),138+ 'l_0_seq': ('resolve', 'seq'),139+ 'l_0_render_title': ('resolve', 'render_title'),140+ }141+ assert body_sym.stores == set([])142+143+ for_sym = symbols_for_node(for_loop, body_sym)144+ assert for_sym.refs == {145+ 'item': 'l_1_item',146+ }147+ assert for_sym.loads == {148+ 'l_1_item': ('param', None),149+ }150+ assert for_sym.stores == set(['item'])151+ assert for_sym.dump_stores() == {152+ 'item': 'l_1_item',153+ }154+155+156+def test_if_branching_stores():157+ tmpl = nodes.Template([158+ nodes.If(nodes.Name('expression', 'load'), [159+ nodes.Assign(nodes.Name('variable', 'store'),160+ nodes.Const(42))], [])])161+162+ sym = symbols_for_node(tmpl)163+ assert sym.refs == {164+ 'variable': 'l_0_variable',165+ 'expression': 'l_0_expression'166+ }167+ assert sym.stores == set(['variable'])168+ assert sym.loads == {169+ 'l_0_variable': ('resolve', 'variable'),170+ 'l_0_expression': ('resolve', 'expression')171+ }172+ assert sym.dump_stores() == {173+ 'variable': 'l_0_variable',174+ }175+176+177+def test_if_branching_stores_undefined():178+ tmpl = nodes.Template([179+ nodes.Assign(nodes.Name('variable', 'store'), nodes.Const(23)),180+ nodes.If(nodes.Name('expression', 'load'), [181+ nodes.Assign(nodes.Name('variable', 'store'),182+ nodes.Const(42))], [])])183+184+ sym = symbols_for_node(tmpl)185+ assert sym.refs == {186+ 'variable': 'l_0_variable',187+ 'expression': 'l_0_expression'188+ }189+ assert sym.stores == set(['variable'])190+ assert sym.loads == {191+ 'l_0_variable': ('undefined', None),192+ 'l_0_expression': ('resolve', 'expression')193+ }194+ assert sym.dump_stores() == {195+ 'variable': 'l_0_variable',196+ }197+198+199+def test_if_branching_multi_scope():200+ for_loop = nodes.For(nodes.Name('item', 'store'), nodes.Name('seq', 'load'), [201+ nodes.If(nodes.Name('expression', 'load'), [202+ nodes.Assign(nodes.Name('x', 'store'), nodes.Const(42))], []),203+ nodes.Include(nodes.Const('helper.html'), True, False)204+ ], [], None, False)205+206+ tmpl = nodes.Template([207+ nodes.Assign(nodes.Name('x', 'store'), nodes.Const(23)),208+ for_loop209+ ])210+211+ tmpl_sym = symbols_for_node(tmpl)212+ for_sym = symbols_for_node(for_loop, tmpl_sym)213+ assert for_sym.stores == set(['item', 'x'])214+ assert for_sym.loads == {215+ 'l_1_x': ('alias', 'l_0_x'),216+ 'l_1_item': ('param', None),217+ 'l_1_expression': ('resolve', 'expression'),218+ }modified:tests/test_imports.py+8 added
144 unmodified lines145 {% endmacro %}146 {{ outer("FOO") }}147 """)148 assert t.render().strip() == '(FOO)'149+150+ def test_import_from_with_context(self):151+ env = Environment(loader=DictLoader({152+ 'a': '{% macro x() %}{{ foobar }}{% endmacro %}',153+ }))154+ t = env.from_string('{% set foobar = 42 %}{% from "a" '155+ 'import x with context %}{{ x() }}')156+ assert t.render() == '42'modified:tests/test_regression.py+37 added
289 unmodified lines290 'main': '{% block body %}[{{ x }}]{% endblock %}',291 }))292 t = env.from_string('{% extends "main" %}{% set x %}42{% endset %}')293 assert t.render() == '[42]'294+295+ def test_nested_for_else(self, env):296+ tmpl = env.from_string('{% for x in y %}{{ loop.index0 }}{% else %}'297+ '{% for i in range(3) %}{{ i }}{% endfor %}'298+ '{% endfor %}')299+ assert tmpl.render() == '012'300+301+ def test_macro_var_bug(self, env):302+ tmpl = env.from_string('''303+ {% set i = 1 %}304+ {% macro test() %}305+ {% for i in range(0, 10) %}{{ i }}{% endfor %}306+ {% endmacro %}{{ test() }}307+ ''')308+ assert tmpl.render().strip() == '0123456789'309+310+ def test_macro_var_bug_advanced(self, env):311+ tmpl = env.from_string('''312+ {% macro outer() %}313+ {% set i = 1 %}314+ {% macro test() %}315+ {% for i in range(0, 10) %}{{ i }}{% endfor %}316+ {% endmacro %}{{ test() }}317+ {% endmacro %}{{ outer() }}318+ ''')319+ assert tmpl.render().strip() == '0123456789'320+321+ def test_callable_defaults(self):322+ env = Environment()323+ env.globals['get_int'] = lambda: 42324+ t = env.from_string('''325+ {% macro test(a, b, c=get_int()) -%}326+ {{ a + b + c }}327+ {%- endmacro %}328+ {{ test(1, 2) }}|{{ test(1, 2, 3) }}329+ ''')330+ assert t.render().strip() == '45|6'modified:CHANGES+2 added
16 unmodified lines17 - Support toplevel set statements in extend situations.18 - Restored behavior of Cycler for Python 3 users.19 - Subtraction now follows the same behavior as other operators on undefined20 values.21+- `map` and friends will now give better error messages if you forgot to22+ quote the parameter.23 24 Version 2.8.225 -------------26 381 unmodified lines