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
Provenance
- Commit
c9705c2- Tree
7186791- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
32a910f
10 files changed+294 added−232 removed
modified:examples/bench.py+3 added-1 removed
293 unmodified lines294 '=' * 80,295 __doc__,296 '-' * 80297 )) + '\n')298+299+298-for test in 'jinja', 'tenjin', 'mako', 'spitfire', 'django', 'genshi', 'cheetah':300+for 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 linesmodified:jinja2/compiler.py+168 added-126 removed
30 unmodified lines31 'in': 'in',32 'notin': 'not in'33 }34 35-35 try:36 exec '(0 if 0 else 0)'37 except SyntaxError:38 have_condexpr = False30 unmodified lines69 return True70 return False71 72 73+def 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.undeclared84+85+86 class Identifiers(object):87 """Tracks the status of identifiers in frames."""88 89 def __init__(self):14 unmodified lines104 105 # names that are declared by parameters106 self.declared_parameter = set()107 96- # filters/tests that are referenced97- self.filters = set()98- self.tests = set()99-108 def add_special(self, name):109 """Register a special name like `loop`."""110 self.undeclared.discard(name)111 self.declared.add(name)31 unmodified lines143 # is buffered this variable points to the name of the list used as144 # buffer.145 self.buffer = None146 139- # 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 = {}142-147 # the name of the block we're in, otherwise None.148 self.block = parent and parent.block or None149 150 # the parent of this frame9 unmodified lines160 parent.identifiers.undeclared -161 self.identifiers.declared162 )163 self.buffer = parent.buffer160- self.name_overrides = parent.name_overrides.copy()164 165 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 rv170 169- 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.173-174- 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)179 180 def inner(self):181 """Return an inner frame."""182 return Frame(self)7 unmodified lines190 rv.rootlevel = False191 return rv192 193 194+class VisitorExit(RuntimeError):195+ """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196+197+198+class DependencyFinderVisitor(NodeVisitor):199+ """A visitor that collects filter and test calls."""200+201+ def __init__(self):202+ self.filters = set()203+ self.tests = set()204+205+ def visit_Filter(self, node):206+ self.generic_visit(node)207+ self.filters.add(node.name)208+209+ def visit_Test(self, node):210+ self.generic_visit(node)211+ self.tests.add(node.name)212+213+ def visit_Block(self, node):214+ """Stop visiting at blocks."""215+216+217+class 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+ """222+223+ def __init__(self, names):224+ self.names = set(names)225+ self.undeclared = set()226+227+ 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)234+235+ def visit_Block(self, node):236+ """Stop visiting a blocks."""237+238+239 class FrameIdentifierVisitor(NodeVisitor):240 """A visitor for `Frame.inspect`."""241 242 def __init__(self, identifiers, hard_scope):243 self.identifiers = identifiers244 self.hard_scope = hard_scope245 204- 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)212-213- 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)217-218- 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)222-223- 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)253 227- 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)257 232- 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)261 241- 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)269+270+ 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)274 246- 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)280 256- 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)284 285+ def visit_FilterBlock(self, node):286+ self.visit(node.filter)287 288+ def visit_Block(self, node):289+ """Stop visiting at blocks."""290+291+292 class 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 lines353 def outdent(self, step=1):354 """Outdent by step."""355 self._indentation -= step356 328- 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()369 370 def write(self, x):371 """Write a string into the output stream."""372 if self._new_lines:72 unmodified lines445 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 lines458 touch_comma()459 self.write('**')460 self.visit(node.dyn_kwargs, frame)461 440- 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))466+467+ 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()476 477 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 assignments7 unmodified lines487 aliases[name] = ident = self.temporary_identifier()488 self.writeline('%s = l_%s' % (ident, name))489 return aliases490 470- 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 a3 unmodified lines499 that the argumetns are collected and callers are looked up.500 501 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)509 510 # 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 from22 unmodified lines535 func_frame.accesses_varargs = False536 func_frame.accesses_caller = False537 func_frame.arguments = args = ['l_' + x.name for x in node.args]538 514- if 'caller' in func_frame.identifiers.undeclared:539+ undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))540+541+ 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_frame19 unmodified lines573 self.blocks[block.name] = block574 575 # 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()577 578 # 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()592 593 # make sure that the parent root is called.594 if have_extends:9 unmodified lines604 605 # 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()625 626 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)627 for x in self.blocks),628 extra=1)13 unmodified lines642 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 lines703 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 lines719 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)725 726 def visit_FromImport(self, node, frame):727 """Visit named imports."""16 unmodified lines744 '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)750 751 def visit_For(self, node, frame):752 loop_frame = frame.inner()753 loop_frame.inspect(node.iter_child_nodes(exclude=('iter',)))2 unmodified lines756 if extended_loop:757 loop_frame.identifiers.add_special('loop')758 759 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')763 764 self.newline(node)20 unmodified lines785 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('))')792 793 else:10 unmodified lines804 self.indent()805 self.writeline('continue')806 self.outdent(2)807 808+ self.indent()809 self.blockvisit(node.body, loop_frame, force_generator=True)810+ self.outdent()811 812 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()818 819 # reset the aliases if there are any.820 for name, alias in aliases.iteritems():821 self.writeline('l_%s = %s' % (name, alias))2 unmodified lines824 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()836 837 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 lines864 macro_frame.accesses_caller and '1' or '0'865 ))866 867 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 lines901 filter_frame = frame.inner()902 filter_frame.inspect(node.iter_child_nodes())903 904 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()907 908 self.writeline('%s = []' % buf, node)909 for child in node.body:121 unmodified lines1031 # 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)1037 1038 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)1042 1043 def visit_Const(self, node, frame):1044 val = node.value160 unmodified linesmodified:jinja2/environment.py+26 added-10 removed
33 unmodified lines34 return Environment(*args)35 if env is not None:36 return env37 _spontaneous_environments[args] = env = Environment(*args)38+ env.shared = True39 return env40 41 42 def template_from_code(environment, code, globals, uptodate=None,33 unmodified lines76 #: the environment sandboxed though. For a real sandboxed environment77 #: have a look at jinja2.sandbox78 sandboxed = False79 80+ #: shared environments have this set to `True`. A shared environment81+ #: must not be modified82+ shared = False83+84 def __init__(self,85 block_start_string='{%',86 block_end_string='%}',87 variable_start_string='{{',257 unmodified lines345 except:346 exc_type, exc_value, tb = translate_exception(sys.exc_info())347 raise exc_type, exc_value, tb348 344- 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)365 349- 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)379 380 def get_corresponding_lineno(self, lineno):381 """Return the source line number of a line number in the105 unmodified linesmodified:jinja2/filters.py+4 added-2 removed
579 unmodified lines580 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)))585 586 587 class _GroupTuple(tuple):588 __slots__ = ()589 grouper = property(itemgetter(0))590 list = property(itemgetter(1))591 592+ def __new__(cls, (key, value)):593+ return tuple.__new__(cls, (key, list(value)))594 595+596 FILTERS = {597 'replace': do_replace,598 'upper': do_upper,599 'lower': do_lower,41 unmodified linesmodified:jinja2/nodes.py+1 added-1 removed
242 unmodified lines243 244 245 class CallBlock(Stmt):246 """A node that represents am extended macro call."""247- fields = ('call', 'body')247+ fields = ('call', 'args', 'defaults', 'body')248 249 250 class Set(Stmt):251 """Allows defining own variables."""368 unmodified linesmodified:jinja2/optimizer.py+38 added-59 removed
81 unmodified lines82 def __init__(self, environment):83 self.environment = environment84 85 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)90 88- 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_section98 96- 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()107 101- # 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()116 112- # 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()124 118- context.pop()119- const = nodes.Const(data, lineno=node.lineno)120- return nodes.Output([const], lineno=node.lineno)121-125 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 result138 139 def visit_Name(self, node, context):140 if node.ctx != 'load':141 # something overwrote the variable, we can no longer use6 unmodified lines148 environment=self.environment)149 except (KeyError, nodes.Impossible):150 return node151 144- 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 node150-151- 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')169-170- try:171- walk(target, value)172- except nodes.Impossible:173- return node174- return result175-152 def visit_Import(self, node, context):153 rv = self.generic_visit(node, context)154 context.undef(node.target)155 return rv156 157 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 rv165 166 def fold(self, node, context):167 """Do constant folding."""13 unmodified linesmodified:jinja2/parser.py+3 added
218 unmodified lines219 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 = []226 227 node.call = self.parse_expression()228 if not isinstance(node.call, nodes.Call):229 raise TemplateSyntaxError('expected call', node.lineno,474 unmodified linesmodified:jinja2/runtime.py+38 added-22 removed
12 unmodified lines13 from jinja2.exceptions import UndefinedError14 15 16 # 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']19 20 21 # special singleton representing missing values for the runtime22 missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()7 unmodified lines30 """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).34+35+ 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 """40 41 def __init__(self, environment, parent, name, blocks):42 self.parent = parent16 unmodified lines59 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())60 61 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 render74 75 def get(self, key, default=None):76 """For dict compatibility"""77 if key in self.vars:3 unmodified lines81 return default82 83 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)86 87 def get_root(self):88 """Return a new dict with all the non local variables."""89 return dict(self.parent)1 unmodified line91 def get_all(self):92 """Return a copy of the complete context as dict."""93 return dict(self.parent, **self.vars)94 95+ 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)99+100 def __contains__(self, name):101 return name in self.vars or name in self.parent102 103 def __getitem__(self, key):10 unmodified lines114 self.name115 )116 117 107-class SuperBlock(object):108- """When called this renders a parent block."""118+class TemplateReference(object):119+ """The `self` in templates."""120 110- 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 = context123 115- 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 render129 130 def __repr__(self):131 return '<%s %r>' % (132 self.__class__.__name__,121- self.name133+ self._context.name134 )135 136 137 class LoopContext(object):41 unmodified lines179 self._length = length180 return self._length181 182 def __repr__(self):171- return 'LoopContext(%r)' % self.index0183+ return '<%s %r/%r>' % (184+ self.__class__.__name__,185+ self.index,186+ self.length187+ )188 189 190 class Macro(object):191 """Wraps a macro."""145 unmodified linesmodified:tests/test_filters.py+9 added-7 removed
58 unmodified lines59 {{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''60 XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,61 'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''62 SORT = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''63-GROUPBY = '''{{ [{'foo': 1, 'bar': 2},63+GROUPBY = '''{% 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 %}'''69 FILTERTAG = '''{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}'''70 71 72 207 unmodified lines280 281 282 def 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+ ]289 290 291 def test_filtertag(env):292 tmpl = env.from_string(FILTERTAG)1 unmodified linemodified:tests/test_macros.py+4 added-4 removed
33 unmodified lines34 {% call test() %}data{% endcall %}\35 '''36 37 COMPLEXCALL = '''\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 '''41 42 CALLERUNDEFINED = '''\43-{% set caller = 42 %}\43+{% caller = 42 %}\44 {% macro test() %}{{ caller is not defined }}{% endmacro %}\45 {{ test() }}\46 '''47 35 unmodified lines83 assert tmpl.render() == 'True'84 85 86 def 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]'