Skip to content
Myr

refactored compiler and improved identifier handling for for-loops

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 903d168 · Browse files · 3 files+75 added−42 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+75 added−42 removed

  • tests:+12 added−0 removed
  • other:+63 added−42 removed

3 files+75 added−42 removed

modified:jinja2/compiler.py+54 added-38 removed
531 unmodified lines
532 aliases[name] = ident = self.temporary_identifier()533 self.writeline('%s = l_%s' % (ident, name))534 return aliases535536 def restore_shadowed(self, aliases):537 """Restore all aliases."""538 for name, alias in aliases.iteritems():539 self.writeline('l_%s = %s' % (name, alias))540541 def function_scoping(self, node, frame, children=None,542 find_special=True):543 """In Jinja a few statements require the help of anonymous544 functions. Those are currently macros and call blocks and in
329 unmodified lines
874875 def visit_For(self, node, frame):876 # when calculating the nodes for the inner frame we have to exclude877 # the iterator contents from it873 children = list(node.iter_child_nodes(exclude=('iter',)))874878 children = node.iter_child_nodes(exclude=('iter',))879 if node.recursive:880 loop_frame = self.function_scoping(node, frame, children,881 find_special=False)882 else:883 loop_frame = frame.inner()884 loop_frame.inspect(children)885882 undeclared = find_undeclared(children, ('loop',))883 extended_loop = node.recursive or node.else_ or 'loop' in undeclared884 if extended_loop:885 loop_frame.identifiers.add_special('loop')886 # try to figure out if we have an extended loop. An extended loop887 # is necessary if the loop is in recursive mode if the special loop888 # variable is accessed in the body.889 extended_loop = node.recursive or 'loop' in \890 find_undeclared(node.iter_child_nodes(891 only=('body',)), ('loop',))892893 # make sure the loop variable is a special one and raise a template894 # assertion error if a loop tries to write to loop895 loop_frame.identifiers.add_special('loop')896 for name in node.find_all(nodes.Name):897 if name.ctx == 'store' and name.name == 'loop':898 self.fail('Can\'t assign to special loop variable '899 'in for-loop target', name.lineno)900901 # if we don't have an recursive loop we have to find the shadowed902 # variables at that point903 if not node.recursive:904 aliases = self.collect_shadowed(loop_frame)
6 unmodified lines
911 aliases = {}912913 self.pull_locals(loop_frame)914 if node.else_:901 self.writeline('l_loop = None')915 iteration_indicator = self.temporary_identifier()916 self.writeline('%s = 1' % iteration_indicator)917903 self.newline(node)904 self.writeline('for ')918 # Create a fake parent loop if the else or test section of a919 # loop is accessing the special loop variable and no parent loop920 # exists.921 if 'loop' not in aliases and 'loop' in find_undeclared(922 node.iter_child_nodes(only=('else_', 'test')), ('loop',)):923 self.writeline("l_loop = environment.undefined(%r, name='loop')" %924 "'loop' is undefined. the filter section of a loop as well " \925 "as the else block doesn't have access to the special 'loop' "926 "variable of the current loop. Because there is no parent "927 "loop it's undefined.")928929 self.writeline('for ', node)930 self.visit(node.target, loop_frame)931 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')932908 # the expression pointing to the parent loop. We make the909 # undefined a bit more debug friendly at the same time.910 parent_loop = 'loop' in aliases and aliases['loop'] \911 or "environment.undefined(%r, name='loop')" % "'loop' " \912 'is undefined. "the filter section of a loop as well ' \913 'as the else block doesn\'t have access to the ' \914 "special 'loop' variable of the current loop. " \915 "Because there is no parent loop it's undefined."916933 # if we have an extened loop and a node test, we filter in the934 # "outer frame".935 if extended_loop and node.test is not None:936 self.write('(')
6 unmodified lines
943 else:944 self.visit(node.iter, loop_frame)945 self.write(' if (')946 test_frame = loop_frame.copy()931 self.writeline('l_loop = ' + parent_loop)947 self.visit(node.test, test_frame)948 self.write('))')949950 elif node.recursive:
17 unmodified lines
968 self.outdent(2)969970 self.indent()971 self.blockvisit(node.body, loop_frame, force_generator=True)972 if node.else_:973 self.writeline('%s = 0' % iteration_indicator)974 self.outdent()975976 if node.else_:960 self.writeline('if l_loop is None:')977 self.writeline('if %s:' % iteration_indicator)978 self.indent()962 self.writeline('l_loop = ' + parent_loop)979 self.blockvisit(node.else_, loop_frame, force_generator=False)980 self.outdent()981982 # reset the aliases if there are any.967 for name, alias in aliases.iteritems():968 self.writeline('l_%s = %s' % (name, alias))983 self.restore_shadowed(aliases)984985 # if the node was recursive we have to return the buffer contents986 # and start the iteration code987 if node.recursive:
34 unmodified lines
1022 (exclude=('call',)))1023 self.writeline('caller = ')1024 self.macro_def(node, call_frame)1025 self.start_write(frame, node)1011 self.visit_Call(node.call, call_frame,1012 extra_kwargs={'caller': 'caller'})1026 self.visit_Call(node.call, call_frame, forward_caller=True)1027 self.end_write(frame)10281029 def visit_FilterBlock(self, node, frame):1030 filter_frame = frame.inner()1031 filter_frame.inspect(node.iter_child_nodes())10181032 aliases = self.collect_shadowed(filter_frame)1033 self.pull_locals(filter_frame)1034 self.buffer(filter_frame)10221023 for child in node.body:1024 self.visit(child, filter_frame)10251035 self.blockvisit(node.body, filter_frame, force_generator=False)1036 self.start_write(frame, node)1027 self.visit_Filter(node.filter, filter_frame, 'concat(%s)'1028 % filter_frame.buffer)1037 self.visit_Filter(node.filter, filter_frame)1038 self.end_write(frame)1039 self.restore_shadowed(aliases)10401041 def visit_ExprStmt(self, node, frame):1042 self.newline(node)1043 self.visit(node.node, frame)
248 unmodified lines
1292 if node.step is not None:1293 self.write(':')1294 self.visit(node.step, frame)12951286 def visit_Filter(self, node, frame, initial=None):1296 def visit_Filter(self, node, frame):1297 self.write(self.filters[node.name] + '(')1298 func = self.environment.filters.get(node.name)1299 if func is None:1300 self.fail('no filter named %r' % node.name, node.lineno)1301 if getattr(func, 'contextfilter', False):1302 self.write('context, ')1303 elif getattr(func, 'environmentfilter', False):1304 self.write('environment, ')1295 if isinstance(node.node, nodes.Filter):1296 self.visit_Filter(node.node, frame, initial)1297 elif node.node is None:1298 self.write(initial)13051306 # if the filter node is None we are inside a filter block1307 # and want to write to the current buffer1308 if node.node is None:1309 if self.environment.autoescape:1310 tmpl = 'Markup(concat(%s))'1311 else:1312 tmpl = 'concat(%s)'1313 self.write(tmpl % frame.buffer)1314 else:1315 self.visit(node.node, frame)1316 self.signature(node, frame)1317 self.write(')')
23 unmodified lines
1341 self.write(' else ')1342 self.visit(node.expr2, frame)1343 self.write(')')13441330 def visit_Call(self, node, frame, extra_kwargs=None):1345 def visit_Call(self, node, frame, forward_caller=False):1346 if self.environment.sandboxed:1347 self.write('environment.call(')1348 self.visit(node.node, frame)1349 self.write(self.environment.sandboxed and ', ' or '(')1350 extra_kwargs = forward_caller and {'caller': 'caller'} or None1351 self.signature(node, frame, False, extra_kwargs)1352 self.write(')')13531354 def visit_Keyword(self, node, frame):
27 unmodified lines
modified:jinja2/nodes.py+9 added-4 removed
114 unmodified lines
115 if attributes:116 raise TypeError('unknown attribute %r' %117 iter(attributes).next())118119 def iter_fields(self, exclude=()):119 def iter_fields(self, exclude=None, only=None):120 """This method iterates over all fields that are defined and yields121 ``(key, value)`` tuples. Optionally a parameter of ignored fields122 can be provided.123 """124 for name in self.fields:125 if name not in exclude:125 if (exclude is only is None) or \126 (exclude is not None and name not in exclude) or \127 (only is not None and name in only):128 try:129 yield name, getattr(self, name)130 except AttributeError:131 pass132131 def iter_child_nodes(self, exclude=()):133 def iter_child_nodes(self, exclude=None, only=None):134 """Iterates over all direct child nodes of the node. This iterates135 over all fields and yields the values of they are nodes. If the value136 of a field is a list all the nodes in that list are returned.137 """136 for field, item in self.iter_fields(exclude):138 for field, item in self.iter_fields(exclude, only):139 if isinstance(item, list):140 for n in item:141 if isinstance(n, Node):142 yield n
387 unmodified lines
530531class Filter(Expr):532 """This node applies a filter on an expression. `name` is the name of533 the filter, the rest of the fields are the same as for :class:`Call`.534535 If the `node` of a filter is `None` the contents of the last buffer are536 filtered. Buffers are created by macros and filter blocks.537 """538 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')539540 def as_const(self, obj=None):
273 unmodified lines
modified:tests/test_forloop.py+12 added
5 unmodified lines
6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from py.test import raises10from jinja2.exceptions import UndefinedError111213SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''14ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''
15 unmodified lines
30 {% for cell in row -%}31 [{{ rowloop.index }}|{{ loop.index }}]32 {%- endfor %}33{%- endfor %}'''34LOOPERROR1 = '''\35{% for item in [1] if loop.index == 0 %}...{% endfor %}'''36LOOPERROR2 = '''\37{% for item in [] %}...{% else %}{{ loop }}{% endfor %}'''383940def test_simple(env):41 tmpl = env.from_string(SIMPLE)
64 unmodified lines
106107def test_looploop(env):108 tmpl = env.from_string(LOOPLOOP)109 assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'110111112def test_loop_errors(env):113 tmpl = env.from_string(LOOPERROR1)114 raises(UndefinedError, tmpl.render)115 tmpl = env.from_string(LOOPERROR2)116 assert tmpl.render() == ''