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
Provenance
- Commit
d1d2f3d- Tree
f9197f7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
180a1bd
3 files changed+91 added−17 removed
modified:jinja2/optimizer.py+6 added-5 removed
81 unmodified lines82 83 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)92 93 parent = context.get('loop')15 unmodified lines109 assign(name, val)110 else:111 raise AssertionError('unexpected assignable node')112 110- # 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 = True85 unmodified linesmodified:jinja2/runtime.py+84 added-11 removed
12 unmodified lines13 except ImportError:14 defaultdict = None15 16 17+# 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']21 22 23 def extends(template, namespace):24 """This loads a template (and evaluates it) and replaces the blocks."""51 unmodified lines76 def __missing__(self, key):77 return self.undefined_factory(key)78 79 77-class LoopContext(object):80+class LoopContextBase(object):81 """Helper for extended iteration."""82 83 def __init__(self, iterable, parent=None):84 self._iterable = iterable85+ self._length = None86 self.index0 = 087 self.parent = parent88 85- def __iter__(self):86- for item in self._iterable:87- yield self, item88- self.index0 += 189-89 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))95 96- @property97- def length(self):98- if not hasattr(self, '_length'):96+97+class LoopContext(LoopContextBase):98+99+ 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)106+107+ 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)113+114+ def __iter__(self):115+ for item in self._iterable:116+ yield self, item117+ self.index0 += 1118+119+ 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._length128 129 130+class StaticLoopContext(LoopContextBase):131+132+ def __init__(self, index0, length, parent):133+ self.index0 = index0134+ self.parent = parent135+ self._length = length136+137+ def __repr__(self):138+ return 'StaticLoopContext(%r, %r, %r)' % (139+ self.index0,140+ self._length,141+ self.parent142+ )143+144+ def make_static(self):145+ return self146+147+148 class Macro(object):149 """150 Wraps a macor151 """27 unmodified lines179 arguments['l_' + name] = arg180 if self.catch_all:181 arguments['l_arguments'] = kwargs182 return u''.join(self.func(**arguments))183+184+185+class Undefined(object):186+ """The default undefined behavior."""187+188+ 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)196+197+ 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 fail202+203+ def __unicode__(self):204+ return ''205+206+ def __repr__(self):207+ return 'Undefined'208+209+ def __len__(self):210+ return 0211+212+ def __iter__(self):213+ if 0:214+ yield Nonemodified:test_optimizer.py+1 added-1 removed
18 unmodified lines19 20 {% 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 """)27 print ast7 unmodified lines