Skip to content
Myr

optimized child template code generation. we now have zero overhead for the most common inheritance case

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 2ba4c92 · Browse files · 3 files+109 added−35 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+109 added−35 removed

  • other:+109 added−35 removed

3 files+109 added−35 removed

modified:jinja2/compiler.py+93 added-20 removed
99 unmodified lines
100 return self.declared & (self.declared_locally | self.declared_parameter)101102103class Frame(object):104 """Holds compile time information for us."""105106 def __init__(self, parent=None):107 self.identifiers = Identifiers()108 # a toplevel frame is the root + soft frames such as if conditions.109 self.toplevel = False110 # the root frame is basically just the outermost frame, so no if111 # conditions. This information is used to optimize inheritance112 # situations.113 self.rootlevel = False114 self.parent = parent115 self.block = parent and parent.block or None116 if parent is not None:117 self.identifiers.declared.update(
20 unmodified lines
138 def inner(self):139 """Return an inner frame."""140 return Frame(self)141142 def soft(self):143 """Return a soft frame. A soft frame may not be modified as144 standalone thing as it shares the resources with the frame it145 was created of, but it's not a rootlevel frame any longer.146 """147 rv = copy(self)148 rv.rootlevel = False149 return rv150151152class FrameIdentifierVisitor(NodeVisitor):153 """A visitor for `Frame.inspect`."""154155 def __init__(self, identifiers, hard_scope):
28 unmodified lines
184 visit_Block = visit_CallBlock = visit_FilterBlock = \185 visit_For = lambda s, n: None186187188class CompilerExit(Exception):189 """Raised if the compiler encountered a situation where it just190 doesn't make sense to further process the code. Any block that191 raises such an exception is not further processed."""192193194class CodeGenerator(NodeVisitor):195196 def __init__(self, environment, is_child, filename, stream=None):197 if stream is None:
5 unmodified lines
203 self.blocks = {}204 self.indentation = 0205 self.new_lines = 0206 self.last_identifier = 0207 self.has_known_extends = False208 self._last_line = 0209 self._first_write = True210211 def temporary_identifier(self):
9 unmodified lines
221 def blockvisit(self, nodes, frame, force_generator=False):222 self.indent()223 if force_generator:224 self.writeline('if 0: yield None')225 try:203 for node in nodes:204 self.visit(node, frame)226 for node in nodes:227 self.visit(node, frame)228 except CompilerExit:229 pass230 self.outdent()231232 def write(self, x):233 if self.new_lines:
53 unmodified lines
287 assert frame is None, 'no root frame allowed'288 self.writeline('from jinja2.runtime import *')289 self.writeline('filename = %r' % self.filename)290291 # do we have an extends tag at all? If not, we can save some292 # overhead by just not processing any inheritance code.293 have_extends = node.find(nodes.Extends) is not None294295 # find all blocks296 for block in node.find_all(nodes.Block):297 if block.name in self.blocks:298 raise TemplateAssertionError('block %r defined twice' %
1 unmodified line
300 self.filename)301 self.blocks[block.name] = block302303 # generate the root render function.275 self.writeline('def root(context):', extra=1)304 self.writeline('def root(globals):', extra=1)305 self.indent()306 self.writeline('context = TemplateContext(globals, filename, blocks)')307 if have_extends:277 self.writeline('parent_root = None')308 self.writeline('parent_root = None')309 self.outdent()310311 # process the root312 frame = Frame()313 frame.inspect(node.body)281 frame.toplevel = True314 frame.toplevel = frame.rootlevel = True315 self.pull_locals(frame)316 self.blockvisit(node.body, frame, True)317318 # make sure that the parent root is called.286 self.indent()287 self.writeline('if parent_root is not None:')288 self.indent()289 self.writeline('for event in parent_root(context):')290 self.indent()291 self.writeline('yield event')292 self.outdent(3)319 if have_extends:320 if not self.has_known_extends:321 self.indent()322 self.writeline('if parent_root is not None:')323 self.indent()324 self.writeline('for event in parent_root(context):')325 self.indent()326 self.writeline('yield event')327 self.outdent(2 + self.has_known_extends)328329 # at this point we now have the blocks collected and can visit them too.330 for name, block in self.blocks.iteritems():331 block_frame = Frame()
2 unmodified lines
334 self.writeline('def block_%s(context):' % name, block, 1)335 self.pull_locals(block_frame)336 self.blockvisit(block.body, block_frame, True)337338 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)339 for x in self.blocks), extra=1)340341 def visit_Block(self, node, frame):342 """Call a block and register it for the template."""343 # if we know that we are a child template, there is no need to344 # check if we are one345 if self.has_known_extends:346 return347 if frame.toplevel:348 self.writeline('if parent_root is None:')349 self.indent()350 self.writeline('for event in block_%s(context):' % node.name)351 self.indent()352 self.writeline('yield event')308 self.outdent()353 self.outdent(1 + frame.toplevel)354355 def visit_Extends(self, node, frame):356 """Calls the extender."""357 if not frame.toplevel:358 raise TemplateAssertionError('cannot use extend from a non '359 'top-level scope', node.lineno,360 self.filename)361362 # if we have a known extends we just add a template runtime363 # error into the generated code. We could catch that at compile364 # time too, but i welcome it not to confuse users by throwing the365 # same error at different times just "because we can".366 if not self.has_known_extends:316 self.writeline('if parent_root is not None:')317 self.indent()367 self.writeline('if parent_root is not None:')368 self.indent()369 self.writeline('raise TemplateRuntimeError(%r)' %370 'extended multiple times')371372 # if we have a known extends already we don't need that code here373 # as we know that the template execution will end here.374 if self.has_known_extends:375 raise CompilerExit()376377 self.outdent()378 self.writeline('parent_root = extends(', node, 1)379 self.visit(node.template, frame)323 self.write(', globals())')380 self.write(', context)')381382 # if this extends statement was in the root level we can take383 # advantage of that information and simplify the generated code384 # in the top level from this point onwards385 self.has_known_extends = True386387 def visit_For(self, node, frame):388 loop_frame = frame.inner()389 loop_frame.inspect(node.iter_child_nodes())390 extended_loop = bool(node.else_) or \
37 unmodified lines
428 delete.discard('l_' + name)429 self.writeline('del %s' % ', '.join(delete))430431 def visit_If(self, node, frame):432 if_frame = frame.soft()433 self.writeline('if ', node)371 self.visit(node.test, frame)434 self.visit(node.test, if_frame)435 self.write(':')373 self.blockvisit(node.body, frame)436 self.blockvisit(node.body, if_frame)437 if node.else_:438 self.writeline('else:')376 self.blockvisit(node.else_, frame)439 self.blockvisit(node.else_, if_frame)440441 def visit_Macro(self, node, frame):442 macro_frame = frame.inner()443 macro_frame.inspect(node.iter_child_nodes(), hard_scope=True)
51 unmodified lines
495 self.newline(node)496 self.visit(node, frame)497498 def visit_Output(self, node, frame):436 self.newline(node)499 # if we have a known extends statement, we don't output anything500 if self.has_known_extends:501 return502503 self.newline(node)504 if self.environment.finalize is unicode:505 finalizer = 'unicode'506 else:507 finalizer = 'context.finalize'508509 if frame.toplevel:510 self.writeline('if parent_root is None:')511 self.indent()512513 # try to evaluate as many chunks as possible into a static514 # string at compile time.515 body = []516 for child in node.nodes:
39 unmodified lines
556 if finalizer != 'unicode':557 self.write(')')558 self.write(idx == 0 and ',)' or ')')559560 if frame.toplevel:561 self.outdent()562563 def visit_Assign(self, node, frame):564 self.newline(node)565 # toplevel assignments however go into the local namespace and566 # the current template's context. We create a copy of the frame
156 unmodified lines
modified:jinja2/runtime.py+5 added-4 removed
16 unmodified lines
17__all__ = ['extends', 'subscribe', 'LoopContext', 'StaticLoopContext',18 'TemplateContext', 'Macro', 'Undefined']192021def extends(template, namespace):21def extends(template, context):22 """This loads a template (and evaluates it) and replaces the blocks."""23 context.stream_muted = True242526def subscribe(obj, argument):27 """Get an item or attribute of an object."""
21 unmodified lines
49 update and other methods will not work as they seem (they don't update50 the exported variables for example).51 """5252 def __init__(self, globals, filename):53 def __init__(self, globals, filename, blocks):54 dict.__init__(self, globals)55 self.exported = set()56 self.filename = filename56 self.filters = {}57 self.tests = {}57 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())58 self.stream_muted = False5960 def __setitem__(self, key, value):61 """If we set items to the dict we track the variables set so62 that includes can access the exported variables."""
159 unmodified lines
modified:test.py+11 added-11 removed
1import sys 1import sys2from jinja2 import Environment3from jinja2.compiler import generate456env = Environment()7ast = env.parse("""8hallo9{% block root %}10 inhalt11 {% x = 3 %}12 {% block inner %}13 {% x = x + 2 %}14 {{ x }}15 {% endblock %}16 {{ x }}8{% extends master_layout or "foo.html" %}910{% baz = [1, 2, 3, 4] %}11{% macro foo() %}12 blah13{% endmacro %}14{% blah = 42 %}1516{% block body %}17 Das ist ein Test18{% endblock %}18ende19""")20source = generate(ast, env, "foo.html")21print source