work on the macro 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 8efc522 · Browse files · 3 files·+72 added−20 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+72 added−20 removed
- other:+72 added−20 removed
Provenance
- Commit
4f62a9f- Tree
71dfa09- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
8efc522
3 files changed+72 added−20 removed
modified:jinja2/compiler.py+49 added-15 removed
59 unmodified lines60 """Register a special name like `loop`."""61 self.undeclared.discard(name)62 self.declared.add(name)63 64- def is_declared(self, name):64+ def is_declared(self, name, local_only=False):65 """Check if a name is declared in this or an outer scope."""66- return name in self.declared or name in self.declared_locally or \67- name in self.declared_parameter66+ if name in self.declared_locally or name in self.declared_parameter:67+ return True68+ if local_only:69+ return False70+ return name in self.declared71 72 def find_shadowed(self):73 """Find all the shadowed names."""74 return self.declared & (self.declared_locally | self.declared_parameter)8 unmodified lines83 self.block = parent and parent.block or None84 if parent is not None:85 self.identifiers.declared.update(86 parent.identifiers.declared |84- parent.identifiers.undeclared |87 parent.identifiers.declared_locally |88 parent.identifiers.declared_parameter89 )90 2 unmodified lines93 rv = copy(self)94 rv.identifiers = copy(self)95 return rv96 95- def inspect(self, nodes):96- """Walk the node and check for identifiers."""97- visitor = FrameIdentifierVisitor(self.identifiers)97+ def inspect(self, nodes, hard_scope=False):98+ """Walk the node and check for identifiers. If the scope99+ is hard (eg: enforce on a python level) overrides from outer100+ scopes are tracked differently.101+ """102+ visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)103 for node in nodes:104 visitor.visit(node)105 106 def inner(self):3 unmodified lines110 111 class FrameIdentifierVisitor(NodeVisitor):112 """A visitor for `Frame.inspect`."""113 109- def __init__(self, identifiers):114+ def __init__(self, identifiers, hard_scope):115 self.identifiers = identifiers116+ self.hard_scope = hard_scope117 118 def visit_Name(self, node):119 """All assignments to names go through this function."""120 if node.ctx in ('store', 'param'):121 self.identifiers.declared_locally.add(node.name)122 elif node.ctx == 'load':117- if not self.identifiers.is_declared(node.name):123+ if not self.identifiers.is_declared(node.name, self.hard_scope):124 self.identifiers.undeclared.add(node.name)125 126 def visit_Macro(self, node):127 """Macros set local."""203 unmodified lines331 self.blockvisit(node.else_, frame)332 333 def visit_Macro(self, node, frame):334 macro_frame = frame.inner()329- macro_frame.inspect(node.body)335+ macro_frame.inspect(node.iter_child_nodes(), hard_scope=True)336+337+ # variables that are undeclared (accessed before declaration) and338+ # declared locally *and* part of an outside scope raise a template339+ # assertion error. Reason: we can't generate reasonable code from340+ # it without aliasing all the variables. XXX: alias them ^^341+ overriden_closure_vars = (342+ macro_frame.identifiers.undeclared &343+ macro_frame.identifiers.declared &344+ (macro_frame.identifiers.declared_locally |345+ macro_frame.identifiers.declared_parameter)346+ )347+ if overriden_closure_vars:348+ vars = ', '.join(sorted(overriden_closure_vars))349+ raise TemplateAssertionError('It\'s not possible to set and '350+ 'access variables derived from '351+ 'an outer scope! (affects: %s' %352+ vars, node.lineno, self.filename)353+354+ # remove variables from a closure from the frame's undeclared355+ # identifiers.356+ macro_frame.identifiers.undeclared -= (357+ macro_frame.identifiers.undeclared &358+ macro_frame.identifiers.declared359+ )360+361 args = ['l_' + x.name for x in node.args]362 if 'arguments' in macro_frame.identifiers.undeclared:363 accesses_arguments = True364 args.append('l_arguments')2 unmodified lines367 self.writeline('def macro(%s):' % ', '.join(args), node)368 self.indent()369 self.writeline('if 0: yield None')370 self.outdent()340- self.blockvisit(node.body, frame)371+ self.pull_locals(macro_frame)372+ self.blockvisit(node.body, macro_frame)373 self.newline()374 if frame.toplevel:375 self.write('context[%r] = ' % node.name)376 arg_tuple = ', '.join(repr(x.name) for x in node.args)377 if len(node.args) == 1:378 arg_tuple += ','347- self.write('l_%s = Macro(macro, %r, (%s), %s)' % (348- node.name, node.name,349- arg_tuple, accesses_arguments350- ))379+ self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,380+ arg_tuple))381+ for arg in node.defaults:382+ self.visit(arg)383+ self.write(', ')384+ self.write('), %r)' % accesses_arguments)385 386 def visit_ExprStmt(self, node, frame):387 self.newline(node)388 self.visit(node, frame)186 unmodified linesmodified:jinja2/runtime.py+18 added
54 unmodified lines55 try:56 return self.globals[key]57 except:58 return self.undefined_factory(key)59+60+61+class Macro(object):62+63+ def __init__(self, func, name, arguments, defaults, catch_all):64+ self.func = func65+ self.name = name66+ self.arguments = arguments67+ self.defaults = defaults68+ self.catch_all = catch_all69+70+ def __call__(self, *args, **kwargs):71+ if len(args) > len(self.arguments):72+ raise TypeError('macro %r takes not more than %d argument(s).' %73+ (self.name, len(self.arguments)))74+ arguments = {}75+ # XXX: assemble arguments76+ return u''.join(self.func(*args, **kwargs))modified:test.py+5 added-5 removed
2 unmodified lines3 4 5 env = Environment()6 ast = env.parse("""7-{% (a, b), c = foo() %}8-{% macro foo(a, b, c=42) %}9- 42 {{ arguments }}10-{% endmacro %}7 {% block body %}12- {% bar = 23 %}8+ {% b = 23 %}9+ {% macro foo(a) %}[{{ a }}|{{ b }}|{{ c }}]{% endmacro %}10+ {% for item in seq %}11+ {{ foo(item) }}12+ {% endfor %}13 {% endblock %}14 """)15 print ast16 print1 unmodified line