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
Provenance
- Commit
75cfb86- Tree
05a5992- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2ba4c92
3 files changed+109 added−35 removed
modified:jinja2/compiler.py+93 added-20 removed
99 unmodified lines100 return self.declared & (self.declared_locally | self.declared_parameter)101 102 103 class Frame(object):104+ """Holds compile time information for us."""105 106 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 lines138 def inner(self):139 """Return an inner frame."""140 return Frame(self)141 142+ 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 rv150 151+152 class FrameIdentifierVisitor(NodeVisitor):153 """A visitor for `Frame.inspect`."""154 155 def __init__(self, identifiers, hard_scope):28 unmodified lines184 visit_Block = visit_CallBlock = visit_FilterBlock = \185 visit_For = lambda s, n: None186 187 188+class 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."""192+193+194 class CodeGenerator(NodeVisitor):195 196 def __init__(self, environment, is_child, filename, stream=None):197 if stream is None:5 unmodified lines203 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 = True210 211 def temporary_identifier(self):9 unmodified lines221 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()231 232 def write(self, x):233 if self.new_lines:53 unmodified lines287 assert frame is None, 'no root frame allowed'288 self.writeline('from jinja2.runtime import *')289 self.writeline('filename = %r' % self.filename)290 291+ # 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 None294+295 # 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 line300 self.filename)301 self.blocks[block.name] = block302 303 # 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()310+311+ # 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)317 318 # 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)328 329 # 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 lines334 self.writeline('def block_%s(context):' % name, block, 1)335 self.pull_locals(block_frame)336 self.blockvisit(block.body, block_frame, True)337 338+ self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)339+ for x in self.blocks), extra=1)340+341 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)354 355 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)361+362+ # 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')371+372+ # 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()376+377 self.outdent()378 self.writeline('parent_root = extends(', node, 1)379 self.visit(node.template, frame)323- self.write(', globals())')380+ self.write(', context)')381 382+ # 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 = True386+387 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 lines428 delete.discard('l_' + name)429 self.writeline('del %s' % ', '.join(delete))430 431 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)440 441 def visit_Macro(self, node, frame):442 macro_frame = frame.inner()443 macro_frame.inspect(node.iter_child_nodes(), hard_scope=True)51 unmodified lines495 self.newline(node)496 self.visit(node, frame)497 498 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+ return502 503+ self.newline(node)504 if self.environment.finalize is unicode:505 finalizer = 'unicode'506 else:507 finalizer = 'context.finalize'508 509+ if frame.toplevel:510+ self.writeline('if parent_root is None:')511+ self.indent()512+513 # 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 lines556 if finalizer != 'unicode':557 self.write(')')558 self.write(idx == 0 and ',)' or ')')559 560+ if frame.toplevel:561+ self.outdent()562+563 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 frame156 unmodified linesmodified:jinja2/runtime.py+5 added-4 removed
16 unmodified lines17 __all__ = ['extends', 'subscribe', 'LoopContext', 'StaticLoopContext',18 'TemplateContext', 'Macro', 'Undefined']19 20 21-def extends(template, namespace):21+def extends(template, context):22 """This loads a template (and evaluates it) and replaces the blocks."""23+ context.stream_muted = True24 25 26 def subscribe(obj, argument):27 """Get an item or attribute of an object."""21 unmodified lines49 update and other methods will not work as they seem (they don't update50 the exported variables for example).51 """52 52- 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 = False59 60 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 linesmodified:test.py+11 added-11 removed
1-import sys 1+import sys2 from jinja2 import Environment3 from jinja2.compiler import generate4 5 6 env = Environment()7 ast = env.parse("""8-hallo9-{% 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" %}9+10+{% baz = [1, 2, 3, 4] %}11+{% macro foo() %}12+ blah13+{% endmacro %}14+{% blah = 42 %}15+16+{% block body %}17+ Das ist ein Test18 {% endblock %}18-ende19 """)20 source = generate(ast, env, "foo.html")21 print source