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
Provenance
- Commit
625215e- Tree
67e12ce- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2e7b54f
5 files changed+74 added−27 removed
modified:examples/test_loop_filter.py+3 added-3 removed
1 from jinja2 import Environment2 3 tmpl = 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 }}9+if condition: {{ 1 if foo else 0 }}10 """)11 12 print tmpl.render(foo=True)modified:jinja2/compiler.py+31 added-18 removed
238 unmodified lines239 240 def outdent(self, step=1):241 self.indentation -= step242 243- 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()255 256 def write(self, x):257 if self.new_lines:258 if not self._first_write:39 unmodified lines298 touch_comma()299 self.write('**')300 self.visit(node.dyn_kwargs, frame)301 300- 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()313 314 def collect_shadowed(self, frame):315 # make sure we "backup" overridden, local identifiers79 unmodified lines395 # 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)404 405 # make sure that the parent root is called.406 if have_extends:407 if not self.has_known_extends:14 unmodified lines422 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)427 428 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)429 for x in self.blocks), extra=1)430 96 unmodified lines527 if extended_loop:528 loop_frame.identifiers.add_special('loop')529 530 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')534 535 self.newline(node)41 unmodified lines577 self.indent()578 self.writeline('continue')579 self.outdent(2)580 579- self.blockvisit(node.body, loop_frame)581+ self.blockvisit(node.body, loop_frame, force_generator=False)582 583 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)589 590 # reset the aliases if there are any.591 for name, alias in aliases.iteritems():592 self.writeline('l_%s = %s' % (name, alias))11 unmodified lines604 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 line620 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 lines631 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 lines659 filter_frame = frame.inner()660 filter_frame.inspect(node.iter_child_nodes())661 662 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()665 666 self.writeline('%s = []' % buf, node)667 for child in node.body:290 unmodified linesmodified:jinja2/nodes.py+19 added
33 unmodified lines34 '+': operator.pos,35 '-': operator.neg36 }37 38+_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+}48 49+50 class Impossible(Exception):51 """Raised if the node could not perform a requested action."""52 53 440 unmodified lines494 class Compare(Expr):495 """{{ foo == bar }}, {{ foo >= bar }} etc."""496 fields = ('expr', 'ops')497 498+ 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 result505 506+507 class Operand(Helper):508 """Operator + expression."""509 fields = ('op', 'expr')510 65 unmodified linesmodified:jinja2/optimizer.py+16 added-4 removed
121 unmodified lines122 return nodes.Output([const], lineno=node.lineno)123 124 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 fallback137 138 parent = context.get('loop')139 context.push()140 result = []13 unmodified lines154 assign(name, val)155 else:156 raise AssertionError('unexpected assignable node')157 158+ 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_sequence171+172 try:173 try:174 for item, loop in LoopContext(iterable, parent, True):175 context['loop'] = loop.make_static()81 unmodified linesmodified:jinja2/runtime.py+5 added-2 removed
13 unmodified lines14 defaultdict = None15 16 17 __all__ = ['subscribe', 'LoopContext', 'StaticLoopContext', 'TemplateContext',18- 'Macro', 'IncludedTemplate', 'Undefined']18+ 'Macro', 'IncludedTemplate', 'Undefined', 'TemplateData']19 20 21 def subscribe(obj, argument):22 """Get an item or attribute of an object."""166 unmodified lines189 self._length,190 self.parent191 )192 193+ def __len__(self):194+ return self._length195+196 def make_static(self):197 return self198 199 33 unmodified lines233 '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)238 239 def __repr__(self):240 return '<%s %s>' % (241 self.__class__.__name__,35 unmodified lines