Skip to content
Myr

all unittests pass, the special and dependency lookups have their own visitors now, with `self` one can get a reference to the current template and render blocks multiple times.

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 32a910f · Browse files · 10 files+294 added−232 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+294 added−232 removed

  • tests:+13 added−11 removed
  • other:+281 added−221 removed

10 files+294 added−232 removed

modified:examples/bench.py+3 added-1 removed
293 unmodified lines
294 '=' * 80,295 __doc__,296 '-' * 80297)) + '\n')298299298for test in 'jinja', 'tenjin', 'mako', 'spitfire', 'django', 'genshi', 'cheetah':300for test in 'jinja', 'mako', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah':301 if locals()['test_' + test] is None:302 sys.stdout.write(' %-20s*not installed*\n' % test)303 continue304 t = Timer(setup='from __main__ import test_%s as bench' % test,
12 unmodified lines
modified:jinja2/compiler.py+168 added-126 removed
30 unmodified lines
31 'in': 'in',32 'notin': 'not in'33}343535try:36 exec '(0 if 0 else 0)'37except SyntaxError:38 have_condexpr = False
30 unmodified lines
69 return True70 return False717273def find_undeclared(nodes, names):74 """Check if the names passed are accessed undeclared. The return value75 is a set of all the undeclared names from the sequence of names found.76 """77 visitor = UndeclaredNameVisitor(names)78 try:79 for node in nodes:80 visitor.visit(node)81 except VisitorExit:82 pass83 return visitor.undeclared848586class Identifiers(object):87 """Tracks the status of identifiers in frames."""8889 def __init__(self):
14 unmodified lines
104105 # names that are declared by parameters106 self.declared_parameter = set()10796 # filters/tests that are referenced97 self.filters = set()98 self.tests = set()99108 def add_special(self, name):109 """Register a special name like `loop`."""110 self.undeclared.discard(name)111 self.declared.add(name)
31 unmodified lines
143 # is buffered this variable points to the name of the list used as144 # buffer.145 self.buffer = None146139 # if a frame has name_overrides, all read access to a name in this140 # dict is redirected to a string expression.141 self.name_overrides = {}142147 # the name of the block we're in, otherwise None.148 self.block = parent and parent.block or None149150 # the parent of this frame
9 unmodified lines
160 parent.identifiers.undeclared -161 self.identifiers.declared162 )163 self.buffer = parent.buffer160 self.name_overrides = parent.name_overrides.copy()164165 def copy(self):166 """Create a copy of the current one."""167 rv = copy(self)168 rv.identifiers = copy(self.identifiers)166 rv.name_overrides = self.name_overrides.copy()169 return rv170169 def inspect(self, nodes, with_depenencies=False, hard_scope=False):171 def inspect(self, nodes, hard_scope=False):172 """Walk the node and check for identifiers. If the scope is hard (eg:173 enforce on a python level) overrides from outer scopes are tracked174 differently.173174 Per default filters and tests (dependencies) are not tracked. That's175 the case because filters and tests are absolutely immutable and so we176 can savely use them in closures too. The `Template` and `Block`177 visitor visits the frame with dependencies to collect them.175 """176 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)177 for node in nodes:181 visitor.visit(node, True, with_depenencies)178 visitor.visit(node)179180 def inner(self):181 """Return an inner frame."""182 return Frame(self)
7 unmodified lines
190 rv.rootlevel = False191 return rv192193194class VisitorExit(RuntimeError):195 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196197198class DependencyFinderVisitor(NodeVisitor):199 """A visitor that collects filter and test calls."""200201 def __init__(self):202 self.filters = set()203 self.tests = set()204205 def visit_Filter(self, node):206 self.generic_visit(node)207 self.filters.add(node.name)208209 def visit_Test(self, node):210 self.generic_visit(node)211 self.tests.add(node.name)212213 def visit_Block(self, node):214 """Stop visiting at blocks."""215216217class UndeclaredNameVisitor(NodeVisitor):218 """A visitor that checks if a name is accessed without being219 declared. This is different from the frame visitor as it will220 not stop at closure frames.221 """222223 def __init__(self, names):224 self.names = set(names)225 self.undeclared = set()226227 def visit_Name(self, node):228 if node.ctx == 'load' and node.name in self.names:229 self.undeclared.add(node.name)230 if self.undeclared == self.names:231 raise VisitorExit()232 else:233 self.names.discard(node.name)234235 def visit_Block(self, node):236 """Stop visiting a blocks."""237238239class FrameIdentifierVisitor(NodeVisitor):240 """A visitor for `Frame.inspect`."""241242 def __init__(self, identifiers, hard_scope):243 self.identifiers = identifiers244 self.hard_scope = hard_scope245204 def visit_Name(self, node, visit_ident, visit_deps):246 def visit_Name(self, node):247 """All assignments to names go through this function."""206 if visit_ident:207 if node.ctx in ('store', 'param'):248 if node.ctx in ('store', 'param'):208 self.identifiers.declared_locally.add(node.name)209 elif node.ctx == 'load' and not \210 self.identifiers.is_declared(node.name, self.hard_scope):211 self.identifiers.undeclared.add(node.name)212213 def visit_Filter(self, node, visit_ident, visit_deps):214 if visit_deps:215 self.generic_visit(node, visit_ident, True)216 self.identifiers.filters.add(node.name)217218 def visit_Test(self, node, visit_ident, visit_deps):219 if visit_deps:220 self.generic_visit(node, visit_ident, True)221 self.identifiers.tests.add(node.name)222223 def visit_Macro(self, node, visit_ident, visit_deps):224 if visit_ident:249 self.identifiers.declared_locally.add(node.name)250 elif node.ctx == 'load' and not \251 self.identifiers.is_declared(node.name, self.hard_scope):252 self.identifiers.undeclared.add(node.name)253227 def visit_Import(self, node, visit_ident, visit_deps):228 if visit_ident:229 self.generic_visit(node, True, visit_deps)230 self.identifiers.declared_locally.add(node.target)254 def visit_Macro(self, node):255 self.generic_visit(node)256 self.identifiers.declared_locally.add(node.name)257232 def visit_FromImport(self, node, visit_ident, visit_deps):233 if visit_ident:234 self.generic_visit(node, True, visit_deps)235 for name in node.names:236 if isinstance(name, tuple):237 self.identifiers.declared_locally.add(name[1])238 else:239 self.identifiers.declared_locally.add(name)258 def visit_Import(self, node):259 self.generic_visit(node)260 self.identifiers.declared_locally.add(node.target)261241 def visit_Assign(self, node, visit_ident, visit_deps):262 def visit_FromImport(self, node):263 self.generic_visit(node)264 for name in node.names:265 if isinstance(name, tuple):266 self.identifiers.declared_locally.add(name[1])267 else:268 self.identifiers.declared_locally.add(name)269270 def visit_Assign(self, node):271 """Visit assignments in the correct order."""243 self.visit(node.node, visit_ident, visit_deps)244 self.visit(node.target, visit_ident, visit_deps)272 self.visit(node.node)273 self.visit(node.target)274246 def visit_For(self, node, visit_ident, visit_deps):275 def visit_For(self, node):276 """Visiting stops at for blocks. However the block sequence277 is visited as part of the outer scope.278 """250 if visit_ident:251 self.visit(node.iter, True, visit_deps)279 self.visit(node.iter)252 if visit_deps:253 for child in node.iter_child_nodes(exclude=('iter',)):254 self.visit(child, False, True)280256 def ident_stop(self, node, visit_ident, visit_deps):257 if visit_deps:258 self.generic_visit(node, False, True)259 visit_CallBlock = visit_FilterBlock = ident_stop260 visit_Block = lambda s, n, a, b: None281 def visit_CallBlock(self, node):282 for child in node.iter_child_nodes(exclude=('body',)):283 self.visit(child)284285 def visit_FilterBlock(self, node):286 self.visit(node.filter)287288 def visit_Block(self, node):289 """Stop visiting at blocks."""290291292class CompilerExit(Exception):293 """Raised if the compiler encountered a situation where it just294 doesn't make sense to further process the code. Any block that295 raises such an exception is not further processed.
57 unmodified lines
353 def outdent(self, step=1):354 """Outdent by step."""355 self._indentation -= step356328 def blockvisit(self, nodes, frame, indent=True, force_generator=True):329 """Visit a list of nodes as block in a frame. Per default the330 code is indented, but this can be disabled by setting the indent331 parameter to False. If the current frame is no buffer a dummy332 ``if 0: yield None`` is written automatically unless the333 force_generator parameter is set to False.357 def blockvisit(self, nodes, frame, force_generator=True):358 """Visit a list of nodes as block in a frame. If the current frame359 is no buffer a dummy ``if 0: yield None`` is written automatically360 unless the force_generator parameter is set to False.361 """335 if indent:336 self.indent()362 if frame.buffer is None and force_generator:363 self.writeline('if 0: yield None')364 try:365 for node in nodes:366 self.visit(node, frame)367 except CompilerExit:368 pass344 if indent:345 self.outdent()369370 def write(self, x):371 """Write a string into the output stream."""372 if self._new_lines:
72 unmodified lines
445 self.visit(kwarg.value, frame)446 self.write(', ')447 if extra_kwargs is not None:448 for key, value in extra_kwargs.iteritems():426 touch_comma()449 self.write('%r: %s, ' % (key, value))450 if node.dyn_kwargs is not None:451 self.write('}, **')452 self.visit(node.dyn_kwargs, frame)
5 unmodified lines
458 touch_comma()459 self.write('**')460 self.visit(node.dyn_kwargs, frame)461440 def pull_locals(self, frame, indent=True):441 """Pull all the references identifiers into the local scope.442 This affects regular names, filters and tests. If indent is443 set to False, no automatic indentation will take place.444 """445 if indent:446 self.indent()462 def pull_locals(self, frame):463 """Pull all the references identifiers into the local scope."""464 for name in frame.identifiers.undeclared:465 self.writeline('l_%s = context[%r]' % (name, name))466467 def pull_dependencies(self, nodes):468 """Pull all the dependencies."""469 visitor = DependencyFinderVisitor()470 for node in nodes:471 visitor.visit(node)449 for name in frame.identifiers.filters:472 for name in visitor.filters:473 self.writeline('f_%s = environment.filters[%r]' % (name, name))451 for name in frame.identifiers.tests:474 for name in visitor.tests:475 self.writeline('t_%s = environment.tests[%r]' % (name, name))453 if indent:454 self.outdent()476477 def collect_shadowed(self, frame):478 """This function returns all the shadowed variables in a dict479 in the form name: alias and will write the required assignments
7 unmodified lines
487 aliases[name] = ident = self.temporary_identifier()488 self.writeline('%s = l_%s' % (ident, name))489 return aliases490470 def function_scoping(self, node, frame):491 def function_scoping(self, node, frame, children=None):492 """In Jinja a few statements require the help of anonymous493 functions. Those are currently macros and call blocks and in494 the future also recursive loops. As there is currently495 technical limitation that doesn't allow reading and writing a
3 unmodified lines
499 that the argumetns are collected and callers are looked up.500501 This will return the modified frame.502 """503 # we have to iterate twice over it, make sure that works504 if children is None:505 children = node.iter_child_nodes()506 children = list(children)507 func_frame = frame.inner()483 func_frame.inspect(node.iter_child_nodes(), hard_scope=True)508 func_frame.inspect(children, hard_scope=True)509510 # variables that are undeclared (accessed before declaration) and511 # declared locally *and* part of an outside scope raise a template512 # assertion error. Reason: we can't generate reasonable code from
22 unmodified lines
535 func_frame.accesses_varargs = False536 func_frame.accesses_caller = False537 func_frame.arguments = args = ['l_' + x.name for x in node.args]538514 if 'caller' in func_frame.identifiers.undeclared:539 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))540541 if 'caller' in undeclared:542 func_frame.accesses_caller = True543 func_frame.identifiers.add_special('caller')544 args.append('l_caller')518 if 'kwargs' in func_frame.identifiers.undeclared:545 if 'kwargs' in undeclared:546 func_frame.accesses_kwargs = True547 func_frame.identifiers.add_special('kwargs')548 args.append('l_kwargs')522 if 'varargs' in func_frame.identifiers.undeclared:549 if 'varargs' in undeclared:550 func_frame.accesses_varargs = True551 func_frame.identifiers.add_special('varargs')552 args.append('l_varargs')553 return func_frame
19 unmodified lines
573 self.blocks[block.name] = block574575 # generate the root render function.576 self.writeline('def root(context, environment=environment):', extra=1)550 if have_extends:551 self.indent()552 self.writeline('parent_template = None')553 self.outdent()577578 # process the root579 frame = Frame()557 frame.inspect(node.body, with_depenencies=True)580 frame.inspect(node.body)581 frame.toplevel = frame.rootlevel = True582 self.indent()560 self.pull_locals(frame, indent=False)561 self.blockvisit(node.body, frame, indent=False)583 if have_extends:584 self.writeline('parent_template = None')585 self.pull_locals(frame)586 self.pull_dependencies(node.body)587 if 'self' in find_undeclared(node.body, ('self',)):588 frame.identifiers.add_special('self')589 self.writeline('l_self = TemplateReference(context)')590 self.blockvisit(node.body, frame)591 self.outdent()592593 # make sure that the parent root is called.594 if have_extends:
9 unmodified lines
604605 # at this point we now have the blocks collected and can visit them too.606 for name, block in self.blocks.iteritems():607 block_frame = Frame()579 block_frame.inspect(block.body, with_depenencies=True)608 block_frame.inspect(block.body)609 block_frame.block = name581 block_frame.identifiers.add_special('super')582 block_frame.name_overrides['super'] = 'context.super(%r, ' \583 'block_%s)' % (name, name)610 self.writeline('def block_%s(context, environment=environment):'611 % name, block, 1)612 self.indent()613 undeclared = find_undeclared(block.body, ('self', 'super'))614 if 'self' in undeclared:615 block_frame.identifiers.add_special('self')616 self.writeline('l_self = TemplateReference(context)')617 if 'super' in undeclared:618 block_frame.identifiers.add_special('super')619 self.writeline('l_super = context.super(%r, '620 'block_%s)' % (name, name))621 self.pull_locals(block_frame)622 self.pull_dependencies(block.body)623 self.blockvisit(block.body, block_frame)624 self.outdent()625626 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)627 for x in self.blocks),628 extra=1)
13 unmodified lines
642 if self.extends_so_far > 0:643 self.writeline('if parent_template is None:')644 self.indent()645 level += 1609 self.writeline('for event in context.blocks[%r][-1](context):' % node.name)646 self.writeline('for event in context.blocks[%r][-1](context):' %647 node.name, node)648 self.indent()649 if frame.buffer is None:650 self.writeline('yield event')651 else:
51 unmodified lines
703 self.writeline('included_template = environment.get_template(', node)704 self.visit(node.template, frame)705 self.write(', %r)' % self.name)706 self.writeline('for event in included_template.root_render_func('669 'included_template.new_context(context.get_root())):')707 'included_template.new_context(context.parent, True)):')708 self.indent()709 if frame.buffer is None:710 self.writeline('yield event')711 else:
7 unmodified lines
719 self.write('context.vars[%r] = ' % node.target)720 self.write('environment.get_template(')721 self.visit(node.template, frame)722 self.write(', %r).include(context)' % self.name)685 if frame.toplevel:723 if frame.toplevel and not node.target.startswith('__'):724 self.writeline('context.exported_vars.discard(%r)' % node.target)725726 def visit_FromImport(self, node, frame):727 """Visit named imports."""
16 unmodified lines
744 'the requested name ' + repr(name)))745 self.outdent()746 if frame.toplevel:747 self.writeline('context.vars[%r] = l_%s' % (alias, alias))748 if not alias.startswith('__'):710 self.writeline('context.exported_vars.discard(%r)' % alias)749 self.writeline('context.exported_vars.discard(%r)' % alias)750751 def visit_For(self, node, frame):752 loop_frame = frame.inner()753 loop_frame.inspect(node.iter_child_nodes(exclude=('iter',)))
2 unmodified lines
756 if extended_loop:757 loop_frame.identifiers.add_special('loop')758759 aliases = self.collect_shadowed(loop_frame)721 self.pull_locals(loop_frame, indent=False)760 self.pull_locals(loop_frame)761 if node.else_:762 self.writeline('l_loop = None')763764 self.newline(node)
20 unmodified lines
785 self.write(' in ')786 self.visit(node.iter, loop_frame)787 self.write(' if (')788 test_frame = loop_frame.copy()750 test_frame.name_overrides['loop'] = parent_loop789 self.writeline('l_loop = ' + parent_loop)790 self.visit(node.test, test_frame)791 self.write('))')792793 else:
10 unmodified lines
804 self.indent()805 self.writeline('continue')806 self.outdent(2)807808 self.indent()809 self.blockvisit(node.body, loop_frame, force_generator=True)810 self.outdent()811812 if node.else_:813 self.writeline('if l_loop is None:')814 self.indent()815 self.writeline('l_loop = ' + parent_loop)775 self.outdent()816 self.blockvisit(node.else_, loop_frame, force_generator=False)817 self.outdent()818819 # reset the aliases if there are any.820 for name, alias in aliases.iteritems():821 self.writeline('l_%s = %s' % (name, alias))
2 unmodified lines
824 if_frame = frame.soft()825 self.writeline('if ', node)826 self.visit(node.test, if_frame)827 self.write(':')828 self.indent()829 self.blockvisit(node.body, if_frame)830 self.outdent()831 if node.else_:832 self.writeline('else:')833 self.indent()834 self.blockvisit(node.else_, if_frame)835 self.outdent()836837 def visit_Macro(self, node, frame):838 macro_frame = self.function_scoping(node, frame)839 args = macro_frame.arguments840 self.writeline('def macro(%s):' % ', '.join(args), node)841 macro_frame.buffer = buf = self.temporary_identifier()842 self.indent()798 self.pull_locals(macro_frame, indent=False)843 self.pull_locals(macro_frame)844 self.writeline('%s = []' % buf)800 self.blockvisit(node.body, macro_frame, indent=False)845 self.blockvisit(node.body, macro_frame)846 self.writeline("return Markup(concat(%s))" % buf)847 self.outdent()848 self.newline()849 if frame.toplevel:850 if not node.name.startswith('__'):805 self.write('context.exported_vars.add(%r)' % node.name)851 self.write('context.exported_vars.add(%r)' % node.name)852 self.writeline('context.vars[%r] = ' % node.name)853 arg_tuple = ', '.join(repr(x.name) for x in node.args)854 if len(node.args) == 1:855 arg_tuple += ','
8 unmodified lines
864 macro_frame.accesses_caller and '1' or '0'865 ))866867 def visit_CallBlock(self, node, frame):822 call_frame = self.function_scoping(node, frame)868 call_frame = self.function_scoping(node, frame, node.iter_child_nodes869 (exclude=('call',)))870 args = call_frame.arguments871 self.writeline('def call(%s):' % ', '.join(args), node)872 call_frame.buffer = buf = self.temporary_identifier()873 self.indent()827 self.pull_locals(call_frame, indent=False)874 self.pull_locals(call_frame)875 self.writeline('%s = []' % buf)829 self.blockvisit(node.body, call_frame, indent=False)876 self.blockvisit(node.body, call_frame)877 self.writeline("return Markup(concat(%s))" % buf)878 self.outdent()879 arg_tuple = ', '.join(repr(x.name) for x in node.args)880 if len(node.args) == 1:881 arg_tuple += ','882 self.writeline('caller = Macro(environment, call, None, (%s), (' %883 arg_tuple)884 for arg in node.defaults:838 self.visit(arg)885 self.visit(arg, call_frame)886 self.write(', ')887 self.write('), %s, %s, 0)' % (888 call_frame.accesses_kwargs and '1' or '0',889 call_frame.accesses_varargs and '1' or '0'
11 unmodified lines
901 filter_frame = frame.inner()902 filter_frame.inspect(node.iter_child_nodes())903904 aliases = self.collect_shadowed(filter_frame)858 self.pull_locals(filter_frame, indent=False)905 self.pull_locals(filter_frame)906 filter_frame.buffer = buf = self.temporary_identifier()907908 self.writeline('%s = []' % buf, node)909 for child in node.body:
121 unmodified lines
1031 # make sure toplevel assignments are added to the context.1032 if frame.toplevel:1033 for name in assignment_frame.assigned_names:1034 self.writeline('context.vars[%r] = l_%s' % (name, name))1035 if not name.startswith('__'):988 self.writeline('context.exported_vars.add(%r)' % name)1036 self.writeline('context.exported_vars.add(%r)' % name)10371038 def visit_Name(self, node, frame):991 if node.ctx == 'store':992 if frame.toplevel:993 frame.assigned_names.add(node.name)994 frame.name_overrides.pop(node.name, None)995 elif node.ctx == 'load':996 if node.name in frame.name_overrides:997 self.write(frame.name_overrides[node.name])998 return1039 if node.ctx == 'store' and frame.toplevel:1040 frame.assigned_names.add(node.name)1041 self.write('l_' + node.name)10421043 def visit_Const(self, node, frame):1044 val = node.value
160 unmodified lines
modified:jinja2/environment.py+26 added-10 removed
33 unmodified lines
34 return Environment(*args)35 if env is not None:36 return env37 _spontaneous_environments[args] = env = Environment(*args)38 env.shared = True39 return env404142def template_from_code(environment, code, globals, uptodate=None,
33 unmodified lines
76 #: the environment sandboxed though. For a real sandboxed environment77 #: have a look at jinja2.sandbox78 sandboxed = False7980 #: shared environments have this set to `True`. A shared environment81 #: must not be modified82 shared = False8384 def __init__(self,85 block_start_string='{%',86 block_end_string='%}',87 variable_start_string='{{',
257 unmodified lines
345 except:346 exc_type, exc_value, tb = translate_exception(sys.exc_info())347 raise exc_type, exc_value, tb348344 def new_context(self, vars):345 """Create a new template context for this template."""346 return TemplateContext(self.environment, dict(self.globals, **vars),347 self.name, self.blocks)349 def new_context(self, vars=None, shared=False):350 """Create a new template context for this template. The vars351 provided will be passed to the template. Per default the globals352 are added to the context, if shared is set to `True` the data353 provided is used as parent namespace. This is used to share the354 same globals in multiple contexts without consuming more memory.355 (This works because the context does not modify the parent dict)356 """357 if vars is None:358 vars = {}359 if shared:360 parent = vars361 else:362 parent = dict(self.globals, **vars)363 return TemplateContext(self.environment, parent, self.name,364 self.blocks)365349 def include(self, context=None):366 def include(self, vars=None):367 """Include this template. When passed a template context or dict368 the template is evaluated in that context and an `IncludedTemplate`369 object is returned. This object then exposes all the exported370 variables as attributes and renders the contents of the template371 when converted to unicode.372 """356 if context is None:357 context = self.new_context({})358 elif isinstance(context, TemplateContext):359 context = self.new_context(context.get_root())373 if isinstance(vars, TemplateContext):374 context = TemplateContext(self.environment, vars.parent,375 self.name, self.blocks)376 else:361 context = self.new_context(context)377 context = self.new_context(vars)378 return IncludedTemplate(self, context)379380 def get_corresponding_lineno(self, lineno):381 """Return the source line number of a line number in the
105 unmodified lines
modified:jinja2/filters.py+4 added-2 removed
579 unmodified lines
580 attribute and the `list` contains all the objects that have this grouper581 in common.582 """583 expr = lambda x: environment.subscribe(x, attribute)584 return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)),585 key=itemgetter('grouper'))584 return sorted(map(_GroupTuple, groupby(sorted(value, key=expr), expr)))585586587class _GroupTuple(tuple):588 __slots__ = ()589 grouper = property(itemgetter(0))590 list = property(itemgetter(1))591592 def __new__(cls, (key, value)):593 return tuple.__new__(cls, (key, list(value)))594595596FILTERS = {597 'replace': do_replace,598 'upper': do_upper,599 'lower': do_lower,
41 unmodified lines
modified:jinja2/nodes.py+1 added-1 removed
242 unmodified lines
243244245class CallBlock(Stmt):246 """A node that represents am extended macro call."""247 fields = ('call', 'body')247 fields = ('call', 'args', 'defaults', 'body')248249250class Set(Stmt):251 """Allows defining own variables."""
368 unmodified lines
modified:jinja2/optimizer.py+38 added-59 removed
81 unmodified lines
82 def __init__(self, environment):83 self.environment = environment8485 def visit_Block(self, node, context):86 block_context = context.blank()87 for name in 'super', 'self':88 block_context.undef(name)86 return self.generic_visit(node, context.blank())89 return self.generic_visit(node, block_context)9088 def scoped_section(self, node, context):91 def visit_For(self, node, context):92 context.push()93 context.undef('loop')94 try:95 return self.generic_visit(node, context)96 finally:97 context.pop()94 visit_For = visit_Macro = scoped_section9896 def visit_FilterBlock(self, node, context):97 """Try to filter a block at compile time."""98 node = self.generic_visit(node, context)99 def visit_Macro(self, node, context):100 context.push()101 for name in 'varargs', 'kwargs', 'caller':102 context.undef(name)103 try:104 return self.generic_visit(node, context)105 finally:106 context.pop()107101 # check if we can evaluate the wrapper body into a string102 # at compile time103 buffer = []104 for child in node.body:105 if not isinstance(child, nodes.Output):106 return node107 for item in child.optimized_nodes():108 if isinstance(item, nodes.Node):109 return node110 buffer.append(item)108 def visit_CallBlock(self, node, context):109 context.push()110 for name in 'varargs', 'kwargs':111 context.undef(name)112 try:113 return self.generic_visit(node, context)114 finally:115 context.pop()116112 # now check if we can evaluate the filter at compile time.117 def visit_FilterBlock(self, node, context):118 """Try to filter a block at compile time."""119 context.push()120 try:114 data = node.filter.as_const(concat(buffer))115 except nodes.Impossible:116 return node121 return self.generic_visit(node, context)122 finally:123 context.pop()124118 context.pop()119 const = nodes.Const(data, lineno=node.lineno)120 return nodes.Output([const], lineno=node.lineno)121125 def visit_If(self, node, context):126 try:127 val = self.visit(node.test, context).as_const()128 except nodes.Impossible:129 return self.generic_visit(node, context)130 if val:128 return node.body129 return node.else_131 body = node.body132 else:133 body = node.else_134 result = []135 for node in body:136 result.extend(self.visit_list(node, context))137 return result138139 def visit_Name(self, node, context):140 if node.ctx != 'load':141 # something overwrote the variable, we can no longer use
6 unmodified lines
148 environment=self.environment)149 except (KeyError, nodes.Impossible):150 return node151144 def visit_Assign(self, node, context):145 try:146 target = node.target = self.generic_visit(node.target, context)147 value = self.generic_visit(node.node, context).as_const()148 except nodes.Impossible:149 return node150151 result = []152 lineno = node.lineno153 def walk(target, value):154 if isinstance(target, nodes.Name):155 const = nodes.Const.from_untrusted(value, lineno=lineno)156 result.append(nodes.Assign(target, const, lineno=lineno))157 context[target.name] = value158 elif isinstance(target, nodes.Tuple):159 try:160 value = tuple(value)161 except TypeError:162 raise nodes.Impossible()163 if len(target.items) != len(value):164 raise nodes.Impossible()165 for name, val in zip(target.items, value):166 walk(name, val)167 else:168 raise AssertionError('unexpected assignable node')169170 try:171 walk(target, value)172 except nodes.Impossible:173 return node174 return result175152 def visit_Import(self, node, context):153 rv = self.generic_visit(node, context)154 context.undef(node.target)155 return rv156157 def visit_FromImport(self, node, context):158 rv = self.generic_visit(node, context)159 for name in node.names:160 if isinstance(name, tuple):161 context.undef(name[1])162 else:184 context.undef(name)163 context.undef(name)164 return rv165166 def fold(self, node, context):167 """Do constant folding."""
13 unmodified lines
modified:jinja2/parser.py+3 added
218 unmodified lines
219 def parse_call_block(self):220 node = nodes.CallBlock(lineno=self.stream.expect('call').lineno)221 if self.stream.current.type is 'lparen':222 self.parse_signature(node)223 else:224 node.args = []225 node.defaults = []226227 node.call = self.parse_expression()228 if not isinstance(node.call, nodes.Call):229 raise TemplateSyntaxError('expected call', node.lineno,
474 unmodified lines
modified:jinja2/runtime.py+38 added-22 removed
12 unmodified lines
13from jinja2.exceptions import UndefinedError141516# these variables are exported to the template runtime17__all__ = ['LoopContext', 'TemplateContext', 'Macro', 'Markup', 'missing',18 'concat']17__all__ = ['LoopContext', 'TemplateContext', 'TemplateReference', 'Macro',18 'Markup', 'missing', 'concat']192021# special singleton representing missing values for the runtime22missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()
7 unmodified lines
30 """Holds the variables of the local template or of the global one. It's31 not save to use this class outside of the compiled code. For example32 update and other methods will not work as they seem (they don't update33 the exported variables for example).3435 The context is immutable. Modifications on `parent` must not happen and36 modifications on `vars` are allowed from generated template code. However37 functions that are passed the template context may not modify the context38 in any way.39 """4041 def __init__(self, environment, parent, name, blocks):42 self.parent = parent
16 unmodified lines
59 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())6061 def super(self, name, current):62 """Render a parent block."""58 last = None59 for block in self.blocks[name]:60 if block is current:61 break62 last = block63 if last is None:63 try:64 blocks = self.blocks[name]65 pos = blocks.index(current) - 166 if pos < 0:67 raise IndexError()68 except LookupError:69 return self.environment.undefined('there is no parent block '65 'called %r.' % block)66 return SuperBlock(block, self, last)70 'called %r.' % name)71 render = lambda: Markup(concat(blocks[pos](self)))72 render.__name__ = render.name = name73 return render7475 def get(self, key, default=None):76 """For dict compatibility"""77 if key in self.vars:
3 unmodified lines
81 return default8283 def get_exported(self):84 """Get a new dict with the exported variables."""78 return dict((k, self.vars[k]) for k in self.exported_vars79 if not k.startswith('__'))85 return dict((k, self.vars[k]) for k in self.exported_vars)8687 def get_root(self):88 """Return a new dict with all the non local variables."""89 return dict(self.parent)
1 unmodified line
91 def get_all(self):92 """Return a copy of the complete context as dict."""93 return dict(self.parent, **self.vars)9495 def clone(self):96 """Return a copy of the context without the locals."""97 return self.__class__(self.environment, self.parent,98 self.name, self.blocks)99100 def __contains__(self, name):101 return name in self.vars or name in self.parent102103 def __getitem__(self, key):
10 unmodified lines
114 self.name115 )116117107class SuperBlock(object):108 """When called this renders a parent block."""118class TemplateReference(object):119 """The `self` in templates."""120110 def __init__(self, name, context, render_func):111 self.name = name112 self._context = context113 self._render_func = render_func121 def __init__(self, context):122 self.__context = context123115 def __call__(self):116 return Markup(concat(self._render_func(self._context)))124 def __getitem__(self, name):125 func = self.__context.blocks[name][-1]126 render = lambda: Markup(concat(func(self.__context)))127 render.__name__ = render.name = name128 return render129130 def __repr__(self):131 return '<%s %r>' % (132 self.__class__.__name__,121 self.name133 self._context.name134 )135136137class LoopContext(object):
41 unmodified lines
179 self._length = length180 return self._length181182 def __repr__(self):171 return 'LoopContext(%r)' % self.index0183 return '<%s %r/%r>' % (184 self.__class__.__name__,185 self.index,186 self.length187 )188189190class Macro(object):191 """Wraps a macro."""
145 unmodified lines
modified:tests/test_filters.py+9 added-7 removed
58 unmodified lines
59{{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''60XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,61'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''62SORT = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''63GROUPBY = '''{{ [{'foo': 1, 'bar': 2},63GROUPBY = '''{% for grouper, list in [{'foo': 1, 'bar': 2},64 {'foo': 2, 'bar': 3},65 {'foo': 1, 'bar': 1},66 {'foo': 3, 'bar': 4}]|groupby('foo') }}'''66 {'foo': 3, 'bar': 4}]|groupby('foo') -%}67{{ grouper }}: {{ list|join(', ') }}68{% endfor %}'''69FILTERTAG = '''{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}'''707172
207 unmodified lines
280281282def test_groupby(env):283 tmpl = env.from_string(GROUPBY)282 assert tmpl.render() == (283 "[{'list': [{'foo': 1, 'bar': 2}, {'foo': 1, 'bar': 1}], "284 "'grouper': 1}, {'list': [{'foo': 2, 'bar': 3}], 'grouper': 2}, "285 "{'list': [{'foo': 3, 'bar': 4}], 'grouper': 3}]"286 )284 assert tmpl.render().splitlines() == [285 "1: {'foo': 1, 'bar': 2}, {'foo': 1, 'bar': 1}",286 "2: {'foo': 2, 'bar': 3}",287 "3: {'foo': 3, 'bar': 4}"288 ]289290291def test_filtertag(env):292 tmpl = env.from_string(FILTERTAG)
1 unmodified line
modified:tests/test_macros.py+4 added-4 removed
33 unmodified lines
34{% call test() %}data{% endcall %}\35'''3637COMPLEXCALL = '''\38{% macro test() %}[[{{ caller(data='data') }}]]{% endmacro %}\39{% call test() %}{{ data }}{% endcall %}\38{% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\39{% call(data) test() %}{{ data }}{% endcall %}\40'''4142CALLERUNDEFINED = '''\43{% set caller = 42 %}\43{% caller = 42 %}\44{% macro test() %}{{ caller is not defined }}{% endmacro %}\45{{ test() }}\46'''47
35 unmodified lines
83 assert tmpl.render() == 'True'848586def test_include(env):87 tmpl = env.from_string('{% include "include" %}{{ test("foo") }}')87 tmpl = env.from_string('{% from "include" import test %}{{ test("foo") }}')88 assert tmpl.render() == '[foo]'