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
Provenance
- Commit
4dfc975- Tree
a5442ba- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d1d2f3d
6 files changed+99 added−35 removed
modified:jinja2/compiler.py+25 added-3 removed
12 unmodified lines13 from cStringIO import StringIO14 from jinja2 import nodes15 from jinja2.visitor import NodeVisitor, NodeTransformer16 from jinja2.exceptions import TemplateAssertionError17+from jinja2.runtime import StaticLoopContext18 19 20 operators = {21 'eq': '==',14 unmodified lines36 if stream is None:37 return generator.stream.getvalue()38 39 40+def 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 False59+60+61 class Identifiers(object):62 """Tracks the status of identifiers in frames."""63 64 def __init__(self):191 unmodified lines256 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)')261 262 # generate the root render function.263 self.writeline('def root(context=template_context):', extra=1)264 self.indent()153 unmodified lines418 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)423 424 def visit_ExprStmt(self, node, frame):425 self.newline(node)426 self.visit(node, frame)148 unmodified lines575 if have_const:576 self.write(repr(const))577 else:578 self.visit(node.arg, frame)557- self.write(', make_undefined)')579+ self.write(')')580 581 def visit_Slice(self, node, frame):582 if node.start is not None:583 self.visit(node.start, frame)34 unmodified linesmodified:jinja2/environment.py+4 added
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja2.lexer import Lexer12 from jinja2.parser import Parser13+from jinja2.runtime import Undefined14 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE15 16 17 class Environment(object):49 unmodified lines67 self.filters = DEFAULT_FILTERS.copy()68 self.tests = DEFAULT_TESTS.copy()69 self.globals = DEFAULT_NAMESPACE.copy()70 71+ # the factory that creates the undefined object72+ self.undefined_factory = Undefined73+74 # create lexer75 self.lexer = Lexer(self)76 77 def parse(self, source, filename=None):20 unmodified linesmodified:jinja2/nodes.py+42 added-1 removed
14 unmodified lines15 import operator16 from itertools import chain, izip17 from collections import deque18 from copy import copy19+from jinja2.runtime import Undefined, subscribe20 21 22 _binop_to_func = {23 '*': operator.mul,262 unmodified lines286 287 def as_const(self):288 return self.value289 290+ @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)301 302+303 class Tuple(Literal):304 """For loop unpacking and some other things like multiple arguments305 for subscripts.306 """66 unmodified lines373 class Call(Expr):374 """{{ foo(bar) }}"""375 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')376 377+ 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()395 396+397 class Subscript(Expr):398 """{{ foo.bar }} and {{ foo['bar'] }} etc."""399 fields = ('node', 'arg', 'ctx')400 401 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()408 409 def can_assign(self):3 unmodified lines413 class Slice(Expr):414 """1:2:3 etc."""415 fields = ('start', 'stop', 'step')416 417+ 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))423 424+425 class Concat(Expr):426 """For {{ foo ~ bar }}. Concatenates strings."""427 fields = ('nodes',)428 78 unmodified linesmodified:jinja2/optimizer.py+13 added-17 removed
76 unmodified lines77 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)85 86 def visit_For(self, node, context):87 """Loop unrolling for iterable constant values."""88 try:52 unmodified lines141 142 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 node150 151 def visit_Assign(self, node, context):6 unmodified lines158 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 lines183 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 fold195 190- 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)196 200-197 def 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 linemodified:jinja2/runtime.py+14 added-14 removed
12 unmodified lines13 except ImportError:14 defaultdict = None15 16 17-# 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']19 20 21 def extends(template, namespace):22 """This loads a template (and evaluates it) and replaces the blocks."""23 24 27-def subscribe(obj, argument, undefined_factory):25+def 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)34 35 36 class TemplateContext(dict):37 """2 unmodified lines40 update and other methods will not work as they seem (they don't update41 the exported variables for example).42 """43 46- 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 lines67 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)75 76 77 class LoopContextBase(object):78 """Helper for extended iteration."""45 unmodified lines124 return self._length125 126 127 class 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)."""132 133 def __init__(self, index0, length, parent):134 self.index0 = index0135 self.parent = parent136 self._length = length137 138 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.parent7 unmodified lines151 """152 Wraps a macor153 """154 153- 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_factory161 162 def __call__(self, *args, **kwargs):163 arg_count = len(self.arguments)164 if len(args) > arg_count:9 unmodified lines174 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))183 184 185 class Undefined(object):186- """The default undefined behavior."""186+ """The object for undefined values."""187 188 def __init__(self, name=None, attr=None):189 if attr is None:190 self._undefined_hint = '%r is undefined' % attr24 unmodified linesmodified:test_optimizer.py+1 added
20 unmodified lines21 <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 """)28 print ast29 print6 unmodified lines