Skip to content
Myr

Fixed self references in macros

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 · parent 3cb7d8a · Browse files · 4 files+100 added−36 removed
This commit

State

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

Diff stats

4 files+100 added−36 removed

  • tests:+13 added−3 removed
  • other:+87 added−33 removed

4 files+100 added−36 removed

modified:jinja2/compiler.py+74 added-32 removed
281 unmodified lines
282283 # Tracks toplevel assignments284 self._assign_stack = []285286 # Tracks parameter definition blocks287 self._param_def_block = []288289 # -- Various compilation helpers290291 def fail(self, msg, lineno):292 """Fail with a :exc:`TemplateAssertionError`."""
217 unmodified lines
510511 self.buffer(frame)512 self.enter_frame(frame)513514 self.push_parameter_definitions(frame)515 for idx, arg in enumerate(node.args):516 ref = frame.symbols.ref(arg.name)512 self.writeline('if %s is missing:' % frame.symbols.ref(arg.name))517 self.writeline('if %s is missing:' % ref)518 self.indent()519 try:520 default = node.defaults[idx - len(node.args)]521 except IndexError:522 self.writeline('%s = undefined(%r, name=%r)' % (518 frame.symbols.ref(arg.name),523 ref,524 'parameter %r was not provided' % arg.name,525 arg.name))526 else:522 self.writeline('%s = ' % frame.symbols.ref(arg.name))527 self.writeline('%s = ' % ref)528 self.visit(default, frame)529 self.mark_parameter_stored(ref)530 self.outdent()531 self.pop_parameter_definitions()532533 self.blockvisit(node.body, frame)534 self.return_buffer_contents(frame, force_unescaped=True)535 self.leave_frame(frame, with_python_scope=True)
24 unmodified lines
560 '%r: %s' % (name, target) for name, target561 in iteritems(frame.symbols.dump_stores()))562563 def write_commons(self):564 """Writes a common preamble that is used by root and block functions.565 Primarily this sets up common local helpers and enforces a generator566 through a dead branch.567 """568 self.writeline('resolve = context.resolve_or_missing')569 self.writeline('undefined = environment.undefined')570 self.writeline('if 0: yield None')571572 def push_parameter_definitions(self, frame):573 """Pushes all parameter targets from the given frame into a local574 stack that permits tracking of yet to be assigned parameters. In575 particular this enables the optimization from `visit_Name` to skip576 undefined expressions for parameters in macros as macros can reference577 otherwise unbound parameters.578 """579 self._param_def_block.append(frame.symbols.dump_param_targets())580581 def pop_parameter_definitions(self):582 """Pops the current parameter definitions set."""583 self._param_def_block.pop()584585 def mark_parameter_stored(self, target):586 """Marks a parameter in the current parameter definitions as stored.587 This will skip the enforced undefined checks.588 """589 if self._param_def_block:590 self._param_def_block[-1].discard(target)591592 def parameter_is_undeclared(self, target):593 """Checks if a given target is an undeclared parameter."""594 if not self._param_def_block:595 return True596 return target in self._param_def_block[-1]597598 def push_assign_tracking(self):599 """Pushes a new layer for assignment tracking."""600 self._assign_stack.append(set())601602 def pop_assign_tracking(self, frame):603 """Pops the topmost level for assignment tracking and updates the604 context variables if necessary.605 """606 vars = self._assign_stack.pop()607 if not frame.toplevel or not vars:608 return609 public_names = [x for x in vars if x[:1] != '_']610 if len(vars) == 1:611 name = next(iter(vars))612 ref = frame.symbols.ref(name)613 self.writeline('context.vars[%r] = %s' % (name, ref))614 else:615 self.writeline('context.vars.update({')616 for idx, name in enumerate(vars):617 if idx:618 self.write(', ')619 ref = frame.symbols.ref(name)620 self.write('%r: %s' % (name, ref))621 self.write('})')622 if public_names:623 if len(public_names) == 1:624 self.writeline('context.exported_vars.add(%r)' %625 public_names[0])626 else:627 self.writeline('context.exported_vars.update((%s))' %628 ', '.join(imap(repr, public_names)))629630 # -- Statement Visitors631632 def visit_Template(self, node, frame=None):633 assert frame is None, 'no root frame allowed'
641 unmodified lines
12751276 if outdent_later:1277 self.outdent()12781210 def push_assign_tracking(self):1211 self._assign_stack.append(set())12121213 def pop_assign_tracking(self, frame):1214 vars = self._assign_stack.pop()1215 if not frame.toplevel or not vars:1216 return1217 public_names = [x for x in vars if x[:1] != '_']1218 if len(vars) == 1:1219 name = next(iter(vars))1220 ref = frame.symbols.ref(name)1221 self.writeline('context.vars[%r] = %s' % (name, ref))1222 else:1223 self.writeline('context.vars.update({')1224 for idx, name in enumerate(vars):1225 if idx:1226 self.write(', ')1227 ref = frame.symbols.ref(name)1228 self.write('%r: %s' % (name, ref))1229 self.write('})')1230 if public_names:1231 if len(public_names) == 1:1232 self.writeline('context.exported_vars.add(%r)' %1233 public_names[0])1234 else:1235 self.writeline('context.exported_vars.update((%s))' %1236 ', '.join(imap(repr, public_names)))12371279 def visit_Assign(self, node, frame):1280 self.push_assign_tracking()1281 self.newline(node)1282 self.visit(node.target, frame)
30 unmodified lines
1313 # case where it's undefined. We can skip that case if the load1314 # instruction indicates a parameter which are always defined.1315 if node.ctx == 'load':1316 load = frame.symbols.find_load(ref)1276 if load is None or load[0] != VAR_LOAD_PARAMETER:1317 if not (load is not None and load[0] == VAR_LOAD_PARAMETER and \1318 not self.parameter_is_undeclared(ref)):1319 self.write('(undefined(name=%r) if %s is missing else %s)' %1320 (node.name, ref, ref))1321 return1322
270 unmodified lines
modified:jinja2/idtracking.py+10 added
121 unmodified lines
122 rv[name] = self.find_ref(name)123 node = node.parent124 return rv125126 def dump_param_targets(self):127 rv = set()128 node = self129 while node is not None:130 for target, (instr, _) in iteritems(self.loads):131 if instr == VAR_LOAD_PARAMETER:132 rv.add(target)133 node = node.parent134 return rv135136137class RootVisitor(NodeVisitor):138139 def __init__(self, symbols):140 self.sym_visitor = FrameSymbolVisitor(symbols)
108 unmodified lines
modified:jinja2/runtime.py+3 added-1 removed
64 unmodified lines
65 # 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 parent.update(locals or ())69 for key, value in iteritems(locals):70 if value is not missing:71 parent[key] = value72 return environment.context_class(environment, parent, template_name,73 blocks)7475
637 unmodified lines
modified:tests/test_core_tags.py+13 added-3 removed
200 unmodified lines
201202203@pytest.mark.core_tags204@pytest.mark.if_condition205class TestIfCondition():205class TestIfCondition(object):206207 def test_simple(self, env):208 tmpl = env.from_string('''{% if true %}...{% endif %}''')209 assert tmpl.render() == '...'
26 unmodified lines
236237238@pytest.mark.core_tags239@pytest.mark.macros240class TestMacros():240class TestMacros(object):241 def test_simple(self, env_trim):242 tmpl = env_trim.from_string('''\243{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}244{{ say_hello('Peter') }}''')
78 unmodified lines
323 '{{ foo(x - 1) }}{% endif %}{% endmacro %}'324 '{{ foo(5) }}')325 assert tmpl.render() == '5|4|3|2|1'326327 def test_macro_defaults_self_ref(self, env):328 tmpl = env.from_string('''329 {%- set x = 42 %}330 {%- macro m(a, b=x, x=23) %}{{ a }}|{{ b }}|{{ x }}{% endmacro -%}331 ''')332 assert tmpl.module.m(1) == '1||23'333 assert tmpl.module.m(1, 2) == '1|2|23'334 assert tmpl.module.m(1, 2, 3) == '1|2|3'335 assert tmpl.module.m(1, x=7) == '1|7|7'336337338@pytest.mark.core_tags339@pytest.mark.set330class TestSet():340class TestSet(object):341342 def test_normal(self, env_trim):343 tmpl = env_trim.from_string('{% set foo = 1 %}{{ foo }}')344 assert tmpl.render() == '1'
6 unmodified lines