Skip to content
Myr

optimizer can optimize filtered for loops now

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 2e7b54f · Browse files · 5 files+74 added−27 removed
This commit

State

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

Diff stats

5 files+74 added−27 removed

  • other:+74 added−27 removed

5 files+74 added−27 removed

modified:examples/test_loop_filter.py+3 added-3 removed
1from jinja2 import Environment23tmpl = Environment().from_string("""\4<ul>5{% for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %}5{%- for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %}6 <li>{{ loop.index }} / {{ loop.length }}: {{ item }}</li>7{% endfor %}7{%- endfor %}8</ul>9{{ 1 if foo else 0 }}9if condition: {{ 1 if foo else 0 }}10""")1112print tmpl.render(foo=True)
modified:jinja2/compiler.py+31 added-18 removed
238 unmodified lines
239240 def outdent(self, step=1):241 self.indentation -= step242243 def blockvisit(self, nodes, frame, force_generator=False):244 self.indent()245 if force_generator and frame.buffer is None:243 def blockvisit(self, nodes, frame, indent=True, force_generator=True):244 if indent:245 self.indent()246 if frame.buffer is None and force_generator:247 self.writeline('if 0: yield None')248 try:249 for node in nodes:250 self.visit(node, frame)251 except CompilerExit:252 pass253 if indent:252 self.outdent()254 self.outdent()255256 def write(self, x):257 if self.new_lines:258 if not self._first_write:
39 unmodified lines
298 touch_comma()299 self.write('**')300 self.visit(node.dyn_kwargs, frame)301300 def pull_locals(self, frame, no_indent=False):301 if not no_indent:302 def pull_locals(self, frame, indent=True):303 if indent:304 self.indent()305 for name in frame.identifiers.undeclared:306 self.writeline('l_%s = context[%r]' % (name, name))307 for name in frame.identifiers.filters:308 self.writeline('f_%s = environment.filters[%r]' % (name, name))309 for name in frame.identifiers.tests:310 self.writeline('t_%s = environment.tests[%r]' % (name, name))309 if not no_indent:311 if indent:312 self.outdent()313314 def collect_shadowed(self, frame):315 # make sure we "backup" overridden, local identifiers
79 unmodified lines
395 # process the root396 frame = Frame()397 frame.inspect(node.body)398 frame.toplevel = frame.rootlevel = True397 self.pull_locals(frame)399 self.indent()400 self.pull_locals(frame, indent=False)401 self.writeline('yield context')402 self.blockvisit(node.body, frame, indent=False)403 self.outdent()401 self.blockvisit(node.body, frame)404405 # make sure that the parent root is called.406 if have_extends:407 if not self.has_known_extends:
14 unmodified lines
422 block_frame.block = name423 self.writeline('def block_%s(context, environment=environment):'424 % name, block, 1)425 self.pull_locals(block_frame)424 self.blockvisit(block.body, block_frame, True)426 self.blockvisit(block.body, block_frame)427428 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)429 for x in self.blocks), extra=1)430
96 unmodified lines
527 if extended_loop:528 loop_frame.identifiers.add_special('loop')529530 aliases = self.collect_shadowed(loop_frame)529 self.pull_locals(loop_frame, True)531 self.pull_locals(loop_frame, indent=False)532 if node.else_:533 self.writeline('l_loop = None')534535 self.newline(node)
41 unmodified lines
577 self.indent()578 self.writeline('continue')579 self.outdent(2)580579 self.blockvisit(node.body, loop_frame)581 self.blockvisit(node.body, loop_frame, force_generator=False)582583 if node.else_:584 self.writeline('if l_loop is None:')585 self.indent()586 self.writeline('l_loop = ' + parent_loop)587 self.outdent()586 self.blockvisit(node.else_, loop_frame)588 self.blockvisit(node.else_, loop_frame, force_generator=False)589590 # reset the aliases if there are any.591 for name, alias in aliases.iteritems():592 self.writeline('l_%s = %s' % (name, alias))
11 unmodified lines
604 def visit_Macro(self, node, frame):605 macro_frame = self.function_scoping(node, frame)606 args = macro_frame.arguments607 self.writeline('def macro(%s):' % ', '.join(args), node)606 self.pull_locals(macro_frame)607 self.blockvisit(node.body, macro_frame, True)608 macro_frame.buffer = buf = self.temporary_identifier()609 self.indent()610 self.pull_locals(macro_frame, indent=False)611 self.writeline('%s = []' % buf)612 self.blockvisit(node.body, macro_frame, indent=False)613 self.writeline("return TemplateData(u''.join(%s))" % buf)614 self.outdent()615 self.newline()616 if frame.toplevel:617 self.write('context[%r] = ' % node.name)618 arg_tuple = ', '.join(repr(x.name) for x in node.args)
1 unmodified line
620 arg_tuple += ','621 self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,622 arg_tuple))623 for arg in node.defaults:617 self.visit(arg)624 self.visit(arg, macro_frame)625 self.write(', ')626 self.write('), %s, %s)' % (627 macro_frame.accesses_arguments and '1' or '0',628 macro_frame.accesses_caller and '1' or '0'
2 unmodified lines
631 def visit_CallBlock(self, node, frame):632 call_frame = self.function_scoping(node, frame)633 args = call_frame.arguments634 self.writeline('def call(%s):' % ', '.join(args), node)635 call_frame.buffer = buf = self.temporary_identifier()636 self.indent()637 self.pull_locals(call_frame, indent=False)638 self.writeline('%s = []' % buf)628 self.blockvisit(node.body, call_frame, node)639 self.blockvisit(node.body, call_frame, indent=False)640 self.writeline("return TemplateData(u''.join(%s))" % buf)641 self.outdent()642 arg_tuple = ', '.join(repr(x.name) for x in node.args)643 if len(node.args) == 1:644 arg_tuple += ','645 self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)
13 unmodified lines
659 filter_frame = frame.inner()660 filter_frame.inspect(node.iter_child_nodes())661662 aliases = self.collect_shadowed(filter_frame)650 self.pull_locals(filter_frame, True)663 self.pull_locals(filter_frame, indent=False)664 filter_frame.buffer = buf = self.temporary_identifier()665666 self.writeline('%s = []' % buf, node)667 for child in node.body:
290 unmodified lines
modified:jinja2/nodes.py+19 added
33 unmodified lines
34 '+': operator.pos,35 '-': operator.neg36}3738_cmpop_to_func = {39 'eq': operator.eq,40 'ne': operator.ne,41 'gt': operator.gt,42 'gteq': operator.ge,43 'lt': operator.lt,44 'lteq': operator.le,45 'in': operator.contains,46 'notin': lambda a, b: not operator.contains(a, b)47}484950class Impossible(Exception):51 """Raised if the node could not perform a requested action."""5253
440 unmodified lines
494class Compare(Expr):495 """{{ foo == bar }}, {{ foo >= bar }} etc."""496 fields = ('expr', 'ops')497498 def as_const(self):499 result = value = self.expr.as_const()500 for op in self.ops:501 new_value = op.expr.as_const()502 result = _cmpop_to_func[op.op](value, new_value)503 value = new_value504 return result505506507class Operand(Helper):508 """Operator + expression."""509 fields = ('op', 'expr')510
65 unmodified lines
modified:jinja2/optimizer.py+16 added-4 removed
121 unmodified lines
122 return nodes.Output([const], lineno=node.lineno)123124 def visit_For(self, node, context):125 """Loop unrolling for iterable constant values."""126 fallback = self.generic_visit(node.copy(), context)127 try:128 iterable = self.visit(node.iter, context).as_const()129 # we only unroll them if they have a length and are iterable130 iter(iterable)131 len(iterable)132 # we also don't want unrolling if macros are defined in it133 if node.find(nodes.Macro) is not None:134 raise TypeError()134 # XXX: add support for loop test clauses in the optimizer135 if node.test is not None:136 raise TypeError()135 except (nodes.Impossible, TypeError):138 return self.generic_visit(node, context)136 return fallback137138 parent = context.get('loop')139 context.push()140 result = []
13 unmodified lines
154 assign(name, val)155 else:156 raise AssertionError('unexpected assignable node')157158 if node.test is not None:159 filtered_sequence = []160 for item in iterable:161 context.push()162 assign(node.target, item)163 try:164 rv = self.visit(node.test.copy(), context).as_const()165 except:166 return fallback167 context.pop()168 if rv:169 filtered_sequence.append(item)170 iterable = filtered_sequence171172 try:173 try:174 for item, loop in LoopContext(iterable, parent, True):175 context['loop'] = loop.make_static()
81 unmodified lines
modified:jinja2/runtime.py+5 added-2 removed
13 unmodified lines
14 defaultdict = None151617__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext', 'TemplateContext',18 'Macro', 'IncludedTemplate', 'Undefined']18 'Macro', 'IncludedTemplate', 'Undefined', 'TemplateData']192021def subscribe(obj, argument):22 """Get an item or attribute of an object."""
166 unmodified lines
189 self._length,190 self.parent191 )192193 def __len__(self):194 return self._length195196 def make_static(self):197 return self198199
33 unmodified lines
233 'from an expression and not a call block.')234 arguments['l_caller'] = caller235 if self.catch_all:236 arguments['l_arguments'] = kwargs234 return TemplateData(u''.join(self._func(**arguments)))237 return self._func(**arguments)238239 def __repr__(self):240 return '<%s %s>' % (241 self.__class__.__name__,
35 unmodified lines