Skip to content
Myr

Fixed a bug that caused internal errors if names where used as iteration

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

variable and regular variable *after* the loop if that variable was unused *before* the loop. (#331) --HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 7887a8c · Browse files · 6 files+147 added−18 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+147 added−18 removed

  • tests:+103 added−0 removed
  • other:+44 added−18 removed

6 files+147 added−18 removed

modified:jinja2/compiler.py+36 added-18 removed
113 unmodified lines
114 if local_only:115 return False116 return name in self.declared117118 def find_shadowed(self, extra=()):119 """Find all the shadowed names. extra is an iterable of variables120 that may be defined with `add_special` which may occour scoped.121 """122 return (self.declared | self.outer_undeclared) & \123 (self.declared_locally | self.declared_parameter) | \124 set(x for x in extra if self.is_declared(x))118126119class Frame(object):120 """Holds compile time information for us."""121122 def __init__(self, parent=None):
19 unmodified lines
142143 # the name of the block we're in, otherwise None.144 self.block = parent and parent.block or None145146 # a set of actually assigned names147 self.assigned_names = set()148149 # the parent of this frame150 self.parent = parent151152 if parent is not None:153 self.identifiers.declared.update(154 parent.identifiers.declared |160 parent.identifiers.declared_locally |155 parent.identifiers.declared_parameter |162 parent.identifiers.undeclared156 parent.assigned_names157 )158 self.identifiers.outer_undeclared.update(159 parent.identifiers.undeclared -160 self.identifiers.declared
16 unmodified lines
177 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)178 for node in nodes:179 visitor.visit(node)180181 def find_shadowed(self, extra=()):182 """Find all the shadowed names. extra is an iterable of variables183 that may be defined with `add_special` which may occour scoped.184 """185 i = self.identifiers186 return (i.declared | i.outer_undeclared) & \187 (i.declared_locally | i.declared_parameter) | \188 set(x for x in extra if i.is_declared(x))189190 def inner(self):191 """Return an inner frame."""192 return Frame(self)193
103 unmodified lines
297298 def visit_FilterBlock(self, node):299 self.visit(node.filter)300301 def visit_Scope(self, node):302 """Stop visiting at scopes."""303304 def visit_Block(self, node):305 """Stop visiting at blocks."""306307
235 unmodified lines
543544 This also predefines locally declared variables from the loop545 body because under some circumstances it may be the case that546541 `extra_vars` is passed to `Identifiers.find_shadowed`.547 `extra_vars` is passed to `Frame.find_shadowed`.548 """549 aliases = {}544 for name in frame.identifiers.find_shadowed(extra_vars):550 for name in frame.find_shadowed(extra_vars):551 aliases[name] = ident = self.temporary_identifier()552 self.writeline('%s = l_%s' % (ident, name))553 to_declare = set()554 for name in frame.identifiers.declared_locally:
328 unmodified lines
883 else:884 self.write('module')885 if frame.toplevel and not node.target.startswith('_'):886 self.writeline('context.exported_vars.discard(%r)' % node.target)887 frame.assigned_names.add(node.target)888889 def visit_FromImport(self, node, frame):890 """Visit named imports."""891 self.newline(node)
28 unmodified lines
920 if frame.toplevel:921 var_names.append(alias)922 if not alias.startswith('_'):923 discarded_names.append(alias)924 frame.assigned_names.add(alias)925926 if var_names:927 if len(var_names) == 1:928 name = var_names[0]
157 unmodified lines
1086 self.write('context.exported_vars.add(%r)' % node.name)1087 self.writeline('context.vars[%r] = ' % node.name)1088 self.write('l_%s = ' % node.name)1089 self.macro_def(node, macro_frame)1090 frame.assigned_names.add(node.name)10911092 def visit_CallBlock(self, node, frame):1093 children = node.iter_child_nodes(exclude=('call',))1094 call_frame = self.macro_body(node, frame, children)
141 unmodified lines
1236 # here and add a set so that the Name visitor can add the assigned1237 # names here.1238 if frame.toplevel:1239 assignment_frame = frame.copy()1231 assignment_frame.assigned_names = set()1240 assignment_frame.toplevel_assignments = set()1241 else:1242 assignment_frame = frame1243 self.visit(node.target, assignment_frame)1244 self.write(' = ')1245 self.visit(node.node, frame)12461247 # make sure toplevel assignments are added to the context.1248 if frame.toplevel:1240 public_names = [x for x in assignment_frame.assigned_names1249 public_names = [x for x in assignment_frame.toplevel_assignments1250 if not x.startswith('_')]1242 if len(assignment_frame.assigned_names) == 1:1243 name = iter(assignment_frame.assigned_names).next()1251 if len(assignment_frame.toplevel_assignments) == 1:1252 name = iter(assignment_frame.toplevel_assignments).next()1253 self.writeline('context.vars[%r] = l_%s' % (name, name))1254 else:1255 self.writeline('context.vars.update({')1247 for idx, name in enumerate(assignment_frame.assigned_names):1256 for idx, name in enumerate(assignment_frame.toplevel_assignments):1257 if idx:1258 self.write(', ')1259 self.write('%r: l_%s' % (name, name))1260 self.write('})')
8 unmodified lines
1269 # -- Expression Visitors12701271 def visit_Name(self, node, frame):1272 if node.ctx == 'store' and frame.toplevel:1264 frame.assigned_names.add(node.name)1273 frame.toplevel_assignments.add(node.name)1274 self.write('l_' + node.name)1275 frame.assigned_names.add(node.name)12761277 def visit_Const(self, node, frame):1278 val = node.value1279 if isinstance(val, float):
201 unmodified lines
1481 self.writeline('continue', node)14821483 def visit_Break(self, node, frame):1484 self.writeline('break', node)14851486 def visit_Scope(self, node, frame):1487 scope_frame = frame.inner()1488 scope_frame.inspect(node.iter_child_nodes())1489 aliases = self.push_scope(scope_frame)1490 self.pull_locals(scope_frame)1491 self.blockvisit(node.body, scope_frame)1492 self.pop_scope(aliases, scope_frame)
modified:jinja2/nodes.py+5 added
776 unmodified lines
777class Break(Stmt):778 """Break a loop."""779780781class Scope(Stmt):782 """An artificial scope."""783 fields = ('body',)784785786# make sure nobody creates custom nodes787def _failing_new(*args, **kwargs):788 raise TypeError('can\'t create custom node types')789NodeType.__new__ = staticmethod(_failing_new); del _failing_new
modified:tests/test_ext.py+23 added
133 unmodified lines
134 env = Environment(extensions=[StreamFilterExtension])135 env.globals['gettext'] = lambda x: x.title()136 tmpl = env.from_string('Foo _(bar) Baz')137 assert tmpl.render() == 'Foo Bar Baz'138139140class WithExtension(Extension):141 tags = frozenset(['with'])142143 def parse(self, parser):144 lineno = parser.stream.next().lineno145 value = parser.parse_expression()146 parser.stream.expect('name:as')147 name = parser.stream.expect('name')148149 body = parser.parse_statements(['name:endwith'], drop_needle=True)150 body.insert(0, nodes.Assign(nodes.Name(name.value, 'store'), value))151 return nodes.Scope(body)152153154def test_with_extension():155 env = Environment(extensions=[WithExtension])156 t = env.from_string('{{ a }}{% with 2 as a %}{{ a }}{% endwith %}{{ a }}')157 assert t.render(a=1) == '121'158159 t = env.from_string('{% with 2 as a %}{{ a }}{% endwith %}{{ a }}')160 assert t.render(a=3) == '23'
modified:tests/test_forloop.py+9 added
173 unmodified lines
174 {%- endcall %}175 {%- endfor -%}176 ''')177 assert t.render() == '[1][2][3]'178179180def test_scoping_bug(env):181 t = env.from_string('''182 {%- for item in foo %}...{{ item }}...{% endfor %}183 {%- macro item(a) %}...{{ a }}...{% endmacro %}184 {{- item(2) -}}185 ''')186 assert t.render(foo=(1,)) == '...1......2...'
added:tests/test_heavy.py+71 added
1# -*- coding: utf-8 -*-2"""3 Heavy tests4 ~~~~~~~~~~~56 The tests in this module test complex Jinja2 situations to ensure7 corner cases (unfortunately mostly undocumented scoping behavior)8 does not change between versions.910 :copyright: Copyright 2009 by the Jinja Team.11 :license: BSD.12"""131415def test_assigned_scoping(env):16 t = env.from_string('''17 {%- for item in (1, 2, 3, 4) -%}18 [{{ item }}]19 {%- endfor %}20 {{- item -}}21 ''')22 assert t.render(item=42) == '[1][2][3][4]42'2324 t = env.from_string('''25 {%- for item in (1, 2, 3, 4) -%}26 [{{ item }}]27 {%- endfor %}28 {%- set item = 42 %}29 {{- item -}}30 ''')31 assert t.render() == '[1][2][3][4]42'3233 t = env.from_string('''34 {%- set item = 42 %}35 {%- for item in (1, 2, 3, 4) -%}36 [{{ item }}]37 {%- endfor %}38 {{- item -}}39 ''')40 assert t.render() == '[1][2][3][4]42'414243def test_closure_scoping(env):44 t = env.from_string('''45 {%- set wrapper = "<FOO>" %}46 {%- for item in (1, 2, 3, 4) %}47 {%- macro wrapper() %}[{{ item }}]{% endmacro %}48 {{- wrapper() }}49 {%- endfor %}50 {{- wrapper -}}51 ''')52 assert t.render() == '[1][2][3][4]<FOO>'5354 t = env.from_string('''55 {%- for item in (1, 2, 3, 4) %}56 {%- macro wrapper() %}[{{ item }}]{% endmacro %}57 {{- wrapper() }}58 {%- endfor %}59 {%- set wrapper = "<FOO>" %}60 {{- wrapper -}}61 ''')62 assert t.render() == '[1][2][3][4]<FOO>'6364 t = env.from_string('''65 {%- for item in (1, 2, 3, 4) %}66 {%- macro wrapper() %}[{{ item }}]{% endmacro %}67 {{- wrapper() }}68 {%- endfor %}69 {{- wrapper -}}70 ''')71 assert t.render(wrapper=23) == '[1][2][3][4]23'
modified:CHANGES+3 added
13 unmodified lines
14 `{% call %}` tag inside loops.15- Fixed a bug in the parser that made ``{{ foo[1, 2] }}`` impossible.16- Made it possible to refer to names from outer scopes in included templates17 that were unused in the callers frame (#327)18- Fixed a bug that caused internal errors if names where used as iteration19 variable and regular variable *after* the loop if that variable was unused20 *before* the loop. (#331)2122Version 2.1.123-------------24(Bugfix release)
84 unmodified lines