Skip to content
Myr

improved loop unrolling

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 180a1bd · Browse files · 3 files+91 added−17 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+91 added−17 removed

  • other:+91 added−17 removed

3 files+91 added−17 removed

modified:jinja2/optimizer.py+6 added-5 removed
81 unmodified lines
8283 def visit_For(self, node, context):84 """Loop unrolling for iterable constant values."""85 try:86 iterable = iter(self.visit(node.iter, context).as_const())86 iterable = self.visit(node.iter, context).as_const()87 # we only unroll them if they have a length and are iterable88 iter(iterable)89 len(iterable)90 except (nodes.Impossible, TypeError):91 return self.generic_visit(node, context)9293 parent = context.get('loop')
15 unmodified lines
109 assign(name, val)110 else:111 raise AssertionError('unexpected assignable node')112110 # XXX: not covered cases:111 # - item is accessed by dynamic part in the iteration113 try:114 try:114 for loop, item in LoopContext(iterable, parent):115 context['loop'] = loop115 for loop, item in LoopContext(iterable, parent, True):116 context['loop'] = loop.make_static()117 assign(node.target, item)118 result.extend(self.visit(n, context)119 for n in deepcopy(node.body))120 iterated = True
85 unmodified lines
modified:jinja2/runtime.py+84 added-11 removed
12 unmodified lines
13except ImportError:14 defaultdict = None151617# contains only the variables the template will import automatically, not the18# objects injected by the evaluation loop (such as undefined objects)17__all__ = ['extends', 'subscribe', 'LoopContext', 'TemplateContext', 'Macro']19__all__ = ['extends', 'subscribe', 'LoopContext', 'StaticLoopContext',20 'TemplateContext', 'Macro']212223def extends(template, namespace):24 """This loads a template (and evaluates it) and replaces the blocks."""
51 unmodified lines
76 def __missing__(self, key):77 return self.undefined_factory(key)787977class LoopContext(object):80class LoopContextBase(object):81 """Helper for extended iteration."""8283 def __init__(self, iterable, parent=None):84 self._iterable = iterable85 self._length = None86 self.index0 = 087 self.parent = parent8885 def __iter__(self):86 for item in self._iterable:87 yield self, item88 self.index0 += 18989 first = property(lambda x: x.index0 == 0)90 last = property(lambda x: x.revindex0 == 0)91 index = property(lambda x: x.index0 + 1)92 revindex = property(lambda x: x.length)93 revindex0 = property(lambda x: x.length - 1)94 length = property(lambda x: len(x))9596 @property97 def length(self):98 if not hasattr(self, '_length'):9697class LoopContext(LoopContextBase):9899 def __init__(self, iterable, parent=None, enforce_length=False):100 self._iterable = iterable101 self._length = None102 self.index0 = 0103 self.parent = parent104 if enforce_length:105 len(self)106107 def make_static(self):108 """Return a static loop context for the optimizer."""109 parent = None110 if self.parent is not None:111 parent = self.parent.make_static()112 return StaticLoopContext(self.index0, self.length, parent)113114 def __iter__(self):115 for item in self._iterable:116 yield self, item117 self.index0 += 1118119 def __len__(self):120 if self._length is None:121 try:122 length = len(self._iterable)123 except TypeError:124 self._iterable = tuple(self._iterable)102 length = len(tuple(self._iterable))125 length = self.index0 + len(tuple(self._iterable))126 self._length = length127 return self._length128129130class StaticLoopContext(LoopContextBase):131132 def __init__(self, index0, length, parent):133 self.index0 = index0134 self.parent = parent135 self._length = length136137 def __repr__(self):138 return 'StaticLoopContext(%r, %r, %r)' % (139 self.index0,140 self._length,141 self.parent142 )143144 def make_static(self):145 return self146147148class Macro(object):149 """150 Wraps a macor151 """
27 unmodified lines
179 arguments['l_' + name] = arg180 if self.catch_all:181 arguments['l_arguments'] = kwargs182 return u''.join(self.func(**arguments))183184185class Undefined(object):186 """The default undefined behavior."""187188 def __init__(self, name=None, attr=None):189 if attr is None:190 self._undefined_hint = '%r is undefined' % attr191 elif name is None:192 self._undefined_hint = 'attribute %r is undefined' % name193 else:194 self._undefined_hint = 'attribute %r of %r is undefined' \195 % (attr, name)196197 def fail(self, *args, **kwargs):198 raise TypeError(self._undefined_hint)199 __getattr__ = __getitem__ = __add__ = __mul__ = __div__ = \200 __realdiv__ = __floordiv__ = __mod__ = __pos__ = __neg__ = fail201 del fail202203 def __unicode__(self):204 return ''205206 def __repr__(self):207 return 'Undefined'208209 def __len__(self):210 return 0211212 def __iter__(self):213 if 0:214 yield None
modified:test_optimizer.py+1 added-1 removed
18 unmodified lines
1920 {% navigation = [('#foo', 'Foo'), ('#bar', 'Bar'), ('#baz', 42 * 2 + 23)] %}21 <ul>22 {% for key, value in navigation %}23 <li>{{ loop.index }}: <a href="{{ key|e }}">{{ value|e }}</a></li>23 <li>{{ test(loop) }}: <a href="{{ key|e }}">{{ value|e }}</a></li>24 {% endfor %}25 </ul>26""")27print ast
7 unmodified lines