Skip to content
Myr

simplified undefined behavior for better compile time processing

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 d1d2f3d · Browse files · 6 files+99 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

6 files+99 added−35 removed

  • other:+99 added−35 removed

6 files+99 added−35 removed

modified:jinja2/compiler.py+25 added-3 removed
12 unmodified lines
13from cStringIO import StringIO14from jinja2 import nodes15from jinja2.visitor import NodeVisitor, NodeTransformer16from jinja2.exceptions import TemplateAssertionError17from jinja2.runtime import StaticLoopContext181920operators = {21 'eq': '==',
14 unmodified lines
36 if stream is None:37 return generator.stream.getvalue()383940def has_safe_repr(value):41 """Does the node have a safe representation?"""42 if value is None:43 return True44 if isinstance(value, (int, long, float, basestring, StaticLoopContext)):45 return True46 if isinstance(value, (tuple, list)):47 for item in value:48 if not has_safe_repr(item):49 return False50 return True51 elif isinstance(value, dict):52 for key, value in value.iteritems():53 if not has_safe_repr(key):54 return False55 if not has_safe_repr(value):56 return False57 return True58 return False596061class Identifiers(object):62 """Tracks the status of identifiers in frames."""6364 def __init__(self):
191 unmodified lines
256 assert frame is None, 'no root frame allowed'257 self.writeline('from jinja2.runtime import *')258 self.writeline('filename = %r' % self.filename)259 self.writeline('template_context = TemplateContext(global_context, '238 'make_undefined, filename)')260 'filename)')261262 # generate the root render function.263 self.writeline('def root(context=template_context):', extra=1)264 self.indent()
153 unmodified lines
418 arg_tuple))419 for arg in node.defaults:420 self.visit(arg)421 self.write(', ')400 self.write('), %r, make_undefined)' % accesses_arguments)422 self.write('), %r)' % accesses_arguments)423424 def visit_ExprStmt(self, node, frame):425 self.newline(node)426 self.visit(node, frame)
148 unmodified lines
575 if have_const:576 self.write(repr(const))577 else:578 self.visit(node.arg, frame)557 self.write(', make_undefined)')579 self.write(')')580581 def visit_Slice(self, node, frame):582 if node.start is not None:583 self.visit(node.start, frame)
34 unmodified lines
modified:jinja2/environment.py+4 added
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja2.lexer import Lexer12from jinja2.parser import Parser13from jinja2.runtime import Undefined14from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE151617class Environment(object):
49 unmodified lines
67 self.filters = DEFAULT_FILTERS.copy()68 self.tests = DEFAULT_TESTS.copy()69 self.globals = DEFAULT_NAMESPACE.copy()7071 # the factory that creates the undefined object72 self.undefined_factory = Undefined7374 # create lexer75 self.lexer = Lexer(self)7677 def parse(self, source, filename=None):
20 unmodified lines
modified:jinja2/nodes.py+42 added-1 removed
14 unmodified lines
15import operator16from itertools import chain, izip17from collections import deque18from copy import copy19from jinja2.runtime import Undefined, subscribe202122_binop_to_func = {23 '*': operator.mul,
262 unmodified lines
286287 def as_const(self):288 return self.value289290 @classmethod291 def from_untrusted(cls, value, lineno=None, silent=False):292 """Return a const object if the value is representable as293 constant value in the generated code, otherwise it will raise294 an `Impossible` exception."""295 from compiler import has_safe_repr296 if not has_safe_repr(value):297 if silent:298 return299 raise Impossible()300 return cls(value, lineno=lineno)301302303class Tuple(Literal):304 """For loop unpacking and some other things like multiple arguments305 for subscripts.306 """
66 unmodified lines
373class Call(Expr):374 """{{ foo(bar) }}"""375 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')376377 def as_const(self):378 obj = self.node.as_const()379 args = [x.as_const() for x in self.args]380 kwargs = dict(x.as_const() for x in self.kwargs)381 if self.dyn_args is not None:382 try:383 args.extend(self.dyn_args.as_const())384 except:385 raise Impossible()386 if self.dyn_kwargs is not None:387 try:388 dyn_kwargs.update(self.dyn_kwargs.as_const())389 except:390 raise Impossible()391 try:392 return obj(*args, **kwargs)393 except:394 raise nodes.Impossible()395396397class Subscript(Expr):398 """{{ foo.bar }} and {{ foo['bar'] }} etc."""399 fields = ('node', 'arg', 'ctx')400401 def as_const(self):402 if self.ctx != 'load':403 raise Impossible()404 try:371 return self.node.as_const()[self.node.as_const()]405 return subscribe(self.node.as_const(), self.arg.as_const())406 except:407 raise Impossible()408409 def can_assign(self):
3 unmodified lines
413class Slice(Expr):414 """1:2:3 etc."""415 fields = ('start', 'stop', 'step')416417 def as_const(self):418 def const(obj):419 if obj is None:420 return obj421 return obj.as_const()422 return slice(const(self.start), const(self.stop), const(self.step))423424425class Concat(Expr):426 """For {{ foo ~ bar }}. Concatenates strings."""427 fields = ('nodes',)428
78 unmodified lines
modified:jinja2/optimizer.py+13 added-17 removed
76 unmodified lines
77 for filter in reversed(node.filters):78 # XXX: call filters with arguments79 x = self.environment.filters[filter.name](self.environment, x)80 # XXX: don't optimize context dependent filters81 return nodes.Const(x)81 try:82 return nodes.Const.from_untrusted(x, lineno=node.lineno)83 except nodes.Impossible:84 return self.generic_visit(node)8586 def visit_For(self, node, context):87 """Loop unrolling for iterable constant values."""88 try:
52 unmodified lines
141142 def visit_Name(self, node, context):143 if node.ctx == 'load':144 try:142 return nodes.Const(context[node.name], lineno=node.lineno)143 except KeyError:145 return nodes.Const.from_untrusted(context[node.name],146 lineno=node.lineno)147 except (KeyError, nodes.Impossible):148 pass149 return node150151 def visit_Assign(self, node, context):
6 unmodified lines
158 result = []159 lineno = node.lineno160 def walk(target, value):161 if isinstance(target, nodes.Name):158 const_value = nodes.Const(value, lineno=lineno)159 result.append(nodes.Assign(target, const_value, lineno=lineno))162 const = nodes.Const.from_untrusted(value, lineno=lineno)163 result.append(nodes.Assign(target, const, lineno=lineno))164 context[target.name] = value165 elif isinstance(target, nodes.Tuple):166 try:167 value = tuple(value)
15 unmodified lines
183 def fold(self, node, context):184 """Do constant folding."""185 node = self.generic_visit(node, context)186 try:183 return nodes.Const(node.as_const(), lineno=node.lineno)187 return nodes.Const.from_untrusted(node.as_const(),188 lineno=node.lineno)189 except nodes.Impossible:190 return node191 visit_Add = visit_Sub = visit_Mul = visit_Div = visit_FloorDiv = \192 visit_Pow = visit_Mod = visit_And = visit_Or = visit_Pos = visit_Neg = \188 visit_Not = visit_Compare = fold193 visit_Not = visit_Compare = visit_Subscribt = visit_Call = fold194 del fold195190 def visit_Subscript(self, node, context):191 if node.ctx == 'load':192 try:193 item = self.visit(node.node, context).as_const()194 arg = self.visit(node.arg, context).as_const()195 except nodes.Impossible:196 return self.generic_visit(node, context)197 return nodes.Const(subscribe(item, arg, 'load'))198 return self.generic_visit(node, context)196200197def optimize(node, environment, context_hint=None):198 """The context hint can be used to perform an static optimization199 based on the context given."""200 optimizer = Optimizer(environment)
1 unmodified line
modified:jinja2/runtime.py+14 added-14 removed
12 unmodified lines
13except ImportError:14 defaultdict = None151617# 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', 'StaticLoopContext',20 'TemplateContext', 'Macro']18 'TemplateContext', 'Macro', 'Undefined']192021def extends(template, namespace):22 """This loads a template (and evaluates it) and replaces the blocks."""232427def subscribe(obj, argument, undefined_factory):25def subscribe(obj, argument):26 """Get an item or attribute of an object."""27 try:28 return getattr(obj, str(argument))29 except (AttributeError, UnicodeError):30 try:31 return obj[argument]32 except LookupError:35 return undefined_factory(attr=argument)33 return Undefined(obj, argument)343536class TemplateContext(dict):37 """
2 unmodified lines
40 update and other methods will not work as they seem (they don't update41 the exported variables for example).42 """4346 def __init__(self, globals, undefined_factory, filename):44 def __init__(self, globals, filename):45 dict.__init__(self, globals)46 self.exported = set()49 self.undefined_factory = undefined_factory47 self.filename = filename48 self.filters = {}49 self.tests = {}50
16 unmodified lines
67 if defaultdict is None:68 def __getitem__(self, name):69 if name in self:70 return self[name]74 return self.undefined_factory(name)71 return Undefined(name)72 else:73 def __missing__(self, key):77 return self.undefined_factory(key)74 return Undefined(key)757677class LoopContextBase(object):78 """Helper for extended iteration."""
45 unmodified lines
124 return self._length125126127class StaticLoopContext(LoopContextBase):128 """The static loop context is used in the optimizer to "freeze" the129 status of an iteration. The only reason for this object is if the130 loop object is accessed in a non static way (eg: becomes part of a131 function call)."""132133 def __init__(self, index0, length, parent):134 self.index0 = index0135 self.parent = parent136 self._length = length137138 def __repr__(self):139 """The repr is used by the optimizer to dump the object."""140 return 'StaticLoopContext(%r, %r, %r)' % (141 self.index0,142 self._length,143 self.parent
7 unmodified lines
151 """152 Wraps a macor153 """154153 def __init__(self, func, name, arguments, defaults, catch_all, \154 undefined_factory):155 def __init__(self, func, name, arguments, defaults, catch_all):156 self.func = func157 self.name = name158 self.arguments = arguments159 self.defaults = defaults160 self.catch_all = catch_all160 self.undefined_factory = undefined_factory161162 def __call__(self, *args, **kwargs):163 arg_count = len(self.arguments)164 if len(args) > arg_count:
9 unmodified lines
174 except KeyError:175 try:176 value = self.defaults[idx - arg_count]177 except IndexError:178 value = self.undefined_factory(name)178 value = Undefined(name)179 arguments['l_' + name] = arg180 if self.catch_all:181 arguments['l_arguments'] = kwargs182 return u''.join(self.func(**arguments))183184185class Undefined(object):186 """The default undefined behavior."""186 """The object for undefined values."""187188 def __init__(self, name=None, attr=None):189 if attr is None:190 self._undefined_hint = '%r is undefined' % attr
24 unmodified lines
modified:test_optimizer.py+1 added
20 unmodified lines
21 <ul>22 {% for key, value in navigation %}23 <li>{{ test(loop) }}: <a href="{{ key|e }}">{{ value|e }}</a></li>24 {% endfor %}25 {{ "Hello World".upper() }}26 </ul>27""")28print ast29print
6 unmodified lines