Skip to content
Myr

improved undefined behavior

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 814f6c2 · Browse files · 10 files+126 added−76 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+126 added−76 removed

  • other:+126 added−76 removed

10 files+126 added−76 removed

modified:jinja2/__init__.py+2 added-1 removed
55 unmodified lines
56 :copyright: 2008 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58"""59from jinja2.environment import Environment60from jinja2.loaders import BaseLoader, FileSystemLoader, DictLoader60from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \61 DictLoader62from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined63from jinja2.utils import Markup, escape
modified:jinja2/compiler.py+1 added-6 removed
936 unmodified lines
937938 def uaop(operator):939 def visitor(self, node, frame):940 self.write('(' + operator)941 self.visit(node.node)941 self.visit(node.node, frame)942 self.write(')')943 return visitor944945 visit_Add = binop('+')
30 unmodified lines
976 const = node.arg.as_const()977 have_const = True978 except nodes.Impossible:979 have_const = False980 if have_const:981 if isinstance(const, (int, long, float)):982 self.visit(node.node, frame)983 self.write('[%s]' % const)984 return980 self.write('environment.subscribe(')981 self.visit(node.node, frame)982 self.write(', ')983 if have_const:
69 unmodified lines
modified:jinja2/defaults.py+1 added-1 removed
7 unmodified lines
8 :copyright: 2007-2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja2.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS12from jinja2.tests import TESTS as DEFAULT_TESTS131415DEFAULT_NAMESPACE = {16 'range': xrange,
5 unmodified lines
modified:jinja2/environment.py+6 added-3 removed
108 unmodified lines
109 except (AttributeError, UnicodeError):110 try:111 return obj[argument]112 except (TypeError, LookupError):113 return self.undefined(obj, argument)113 return self.undefined(obj=obj, name=argument)114115 def parse(self, source, name=None):116 """Parse the sourcecode and return the abstract syntax tree. This tree117 of nodes is used by the compiler to convert the template into118 executable source- or bytecode.119 """120 parser = Parser(self, source, name)121 return parser.parse()120 return Parser(self, source, name).parse()121122 def lex(self, source, name=None):123 """Lex the given sourcecode and return a generator that yields tokens.124 The stream returned is not usable for Jinja but can be used if
71 unmodified lines
196 self._uptodate = uptodate197 namespace['__jinja_template__'] = self198199 def render(self, *args, **kwargs):200 """Render the template into a string."""201 return u''.join(self.generate(*args, **kwargs))202203 def stream(self, *args, **kwargs):204 """Return a `TemplateStream` that generates the template."""205 return TemplateStream(self.generate(*args, **kwargs))206207 def generate(self, *args, **kwargs):208 """Return a generator that generates the template."""209 # assemble the context210 context = dict(*args, **kwargs)211212 # if the environment is using the optimizer locals may never
28 unmodified lines
241 if code_line <= lineno:242 return template_line243 return 1244245 @property246 def is_up_to_date(self):247 """Check if the template is still up to date."""248 if self._uptodate is None:249 return True
54 unmodified lines
modified:jinja2/exceptions.py+12 added-9 removed
9 unmodified lines
10"""111213class TemplateError(Exception):14 pass14 """Baseclass for all template errors."""151617class UndefinedError(TemplateError):18 """Raised if a template tries to operate on `Undefined`."""192021class TemplateNotFound(IOError, LookupError, TemplateError):18 """19 Raised if a template does not exist.20 """22 """Raised if a template does not exist."""2324 def __init__(self, name):25 IOError.__init__(self, name)26 self.name = name272829class TemplateSyntaxError(TemplateError):28 """29 Raised to tell the user that there is a problem with the template.30 """30 """Raised to tell the user that there is a problem with the template."""3132 def __init__(self, message, lineno, name):33 TEmplateError.__init__(self, '%s (line %s)' % (message, lineno))34 self.message = message
1 unmodified line
36 self.name = name373839class TemplateAssertionError(AssertionError, TemplateSyntaxError):40 """Like a template syntax error, but covers cases where something in the41 template caused an error at compile time that wasn't necessarily caused42 by a syntax error.43 """4445 def __init__(self, message, lineno, name):46 AssertionError.__init__(self, message)47 TemplateSyntaxError.__init__(self, message, lineno, name)484950class TemplateRuntimeError(TemplateError):47 """48 Raised by the template engine if a tag encountered an error when51 """Raised by the template engine if a tag encountered an error when52 rendering.53 """
modified:jinja2/filters.py+3 added-6 removed
235 unmodified lines
236 """Return the frist item of a sequence."""237 try:238 return iter(seq).next()239 except StopIteration:240 return environment.undefined('seq|first',241 extra='the sequence was empty')240 return environment.undefined('No first item, sequence was empty.')241242243@environmentfilter244def do_last(environment, seq):245 """Return the last item of a sequence."""246 try:247 return iter(reversed(seq)).next()248 except StopIteration:250 return environment.undefined('seq|last',251 extra='the sequence was empty')249 return environment.undefined('No last item, sequence was empty.')250251252@environmentfilter253def do_random(environment, seq):254 """Return a random item from the sequence."""255 try:256 return choice(seq)257 except IndexError:260 return environment.undefined('seq|random',261 extra='the sequence was empty')258 return environment.undefined('No random item, sequence was empty.')259260261def do_filesizeformat(value):262 """Format the value like a 'human-readable' file size (i.e. 13 KB,
354 unmodified lines
modified:jinja2/loaders.py+44 added-18 removed
7 unmodified lines
8 :copyright: 2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from os import path12from time import time12from jinja2.exceptions import TemplateNotFound13from jinja2.environment import Template14from jinja2.utils import LRUCache151617def split_template_path(template):18 """Split a path into segments and perform a sanity check. If it detects19 '..' in the path it will raise a `TemplateNotFound` error.20 """21 pieces = []22 for piece in template.split('/'):23 if path.sep in piece \24 or (path.altsep and path.altsep in piece) or \25 piece == path.pardir:26 raise TemplateNotFound(template)27 elif piece != '.':28 pieces.append(piece)29 return pieces303132class BaseLoader(object):33 """34 Baseclass for all loaders. Subclass this and override `get_source` to35 implement a custom loading mechanism.
38 unmodified lines
7475 if self.cache is not None:76 template = self.cache.get(name)77 if template is not None and (not self.auto_reload or \64 template.is_up_to_date()):78 template.is_up_to_date):79 return template8081 source, filename, uptodate = self.get_source(environment, name)82 code = environment.compile(source, name, filename, globals)
14 unmodified lines
97 self.searchpath = searchpath98 self.encoding = encoding99100 def get_source(self, environment, template):87 pieces = []88 for piece in template.split('/'):89 if piece == '..':90 raise TemplateNotFound(template)91 elif piece != '.':92 pieces.append(piece)101 pieces = split_template_path(template)102 for searchpath in self.searchpath:103 filename = path.join(searchpath, *pieces)95 if path.isfile(filename):96 f = file(filename)97 try:98 contents = f.read().decode(self.encoding)99 finally:100 f.close()101 mtime = path.getmtime(filename)102 def uptodate():103 return path.getmtime(filename) != mtime104 return contents, filename, uptodate104 if not path.isfile(filename):105 continue106 f = file(filename)107 try:108 contents = f.read().decode(self.encoding)109 finally:110 f.close()111 old = path.getmtime(filename)112 return contents, filename, lambda: path.getmtime(filename) != old113 raise TemplateNotFound(template)114115116class PackageLoader(BaseLoader):117 """Load templates from python eggs."""118119 def __init__(self, package_name, package_path, charset='utf-8',120 cache_size=50, auto_reload=True):121 BaseLoader.__init__(self, cache_size, auto_reload)122 import pkg_resources123 self._pkg = pkg_resources124 self.package_name = package_name125 self.package_path = package_path126127 def get_source(self, environment, template):128 path = '/'.join(split_template_path(template))129 if not self._pkg.resource_exists(self.package_name, path):130 raise TemplateNotFound(template)131 return self._pkg.resource_string(self.package_name, path), None, None132133134class DictLoader(BaseLoader):135 """Loads a template from a python dict. Used for unittests mostly."""136137 def __init__(self, mapping):
6 unmodified lines
modified:jinja2/parser.py+1 added-1 removed
637 unmodified lines
638 dyn_args = dyn_kwargs = None639 node = nodes.Test(node, name, args, kwargs, dyn_args,640 dyn_kwargs, lineno=token.lineno)641 if negated:642 node = nodes.NotExpression(node, lineno=token.lineno)642 node = nodes.Not(node, lineno=token.lineno)643 return node644645 def subparse(self, end_tokens=None):646 body = []
44 unmodified lines
modified:jinja2/runtime.py+37 added-22 removed
11 unmodified lines
12 from collections import defaultdict13except ImportError:14 defaultdict = None15from jinja2.utils import Markup16from jinja2.exceptions import UndefinedError171819__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',20 'Macro', 'IncludedTemplate', 'Markup']
25 unmodified lines
46 """Render a parent block."""47 try:48 func = self.blocks[block][-2]49 except LookupError:49 return self.environment.undefined('super',50 extra='there is probably no parent block with this name')50 return self.environment.undefined('there is no parent block '51 'called %r.' % block)52 return SuperBlock(block, self, func)5354 def __setitem__(self, key, value):55 """If we set items to the dict we track the variables set so
9 unmodified lines
65 if defaultdict is None:66 def __getitem__(self, name):67 if name in self:68 return self[name]68 return self.environment.undefined(name)69 return self.environment.undefined(name=name)70 else:70 def __missing__(self, key):71 return self.environment.undefined(key)71 def __missing__(self, name):72 return self.environment.undefined(name=name)7374 def __repr__(self):75 return '<%s %s of %r>' % (76 self.__class__.__name__,
164 unmodified lines
241 except KeyError:242 try:243 value = self.defaults[idx - arg_count]244 except IndexError:244 value = self._environment.undefined(name,245 extra='parameter not provided')245 value = self._environment.undefined(246 'parameter %r was not provided' % name)247 arguments['l_' + name] = value248 if self.caller:249 caller = kwargs.pop('caller', None)250 if caller is None:250 caller = self._environment.undefined('caller',251 extra='The macro was called from an expression and not '252 'a call block.')251 caller = self._environment.undefined('No caller defined')252 arguments['l_caller'] = caller253 if self.catch_all:254 arguments['l_arguments'] = kwargs255 return self._func(**arguments)
10 unmodified lines
266 can be printed and iterated over, but every other access will raise a267 `NameError`. Custom undefined classes must subclass this.268 """269271 def __init__(self, name=None, attr=None, extra=None):272 if attr is None:273 self._undefined_hint = '%r is undefined' % name274 self._error_class = NameError275 else:276 self._undefined_hint = '%r has no attribute named %r' \277 % (name, attr)278 self._error_class = AttributeError279 if extra is not None:280 self._undefined_hint += ' (' + extra + ')'270 def __init__(self, hint=None, obj=None, name=None):271 self._undefined_hint = hint272 self._undefined_obj = obj273 self._undefined_name = name274275 def _fail_with_error(self, *args, **kwargs):283 raise self._error_class(self._undefined_hint)276 if self._undefined_hint is None:277 if self._undefined_obj is None:278 hint = '%r is undefined' % self._undefined_name279 elif not isinstance(self._undefined_name, basestring):280 hint = '%r object has no element %r' % (281 self._undefined_obj.__class__.__name__,282 self._undefined_name283 )284 else:285 hint = '%r object has no attribute %s' % (286 self._undefined_obj.__class__.__name__,287 self._undefined_name288 )289 else:290 hint = self._undefined_hint291 raise UndefinedError(hint)292 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \293 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \294 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \295 __getattr__ = __getitem__ = _fail_with_error
21 unmodified lines
317class DebugUndefined(Undefined):318 """An undefined that returns the debug info when printed."""319320 def __unicode__(self):321 if self._undefined_hint is None:322 if self._undefined_obj is None:313 return u'{{ %s }}' % self._undefined_hint323 return u'{{ %s }}' % self._undefined_name324 return '{{ no such element: %s[%r] }}' % (325 self._undefined_obj.__class__.__name__,326 self._undefined_name327 )328 return u'{{ undefined value printed: %s }}' % self._undefined_hint329330331class StrictUndefined(Undefined):332 """An undefined that barks on print and iteration."""
2 unmodified lines
modified:jinja2/sandbox.py+19 added-9 removed
42 unmodified lines
43 def __init__(self, *args, **kwargs):44 Environment.__init__(self, *args, **kwargs)45 self.globals['range'] = safe_range4647 def is_safe_attribute(self, obj, attr):47 def is_safe_attribute(self, obj, attr, value):48 """The sandboxed environment will call this method to check if the49 attribute of an object is safe to access. Per default all attributes50 starting with an underscore are considered private as well as the51 special attributes of functions and methods.
13 unmodified lines
65 affect the `unsafe` decorator from this module.66 """67 return not getattr(obj, 'unsafe_callable', False)6869 def subscribe(self, obj, arg):69 def subscribe(self, obj, argument):70 """Subscribe an object from sandboxed code."""71 is_unsafe = False72 try:73 value = getattr(obj, str(argument))74 except (AttributeError, UnicodeError):75 pass76 else:77 if self.is_safe_attribute(obj, argument, value):78 return value79 is_unsafe = True80 try:72 return obj[arg]81 return obj[argument]82 except (TypeError, LookupError):74 if not self.is_safe_attribute(obj, arg):75 return Undefined(obj, arg, extra='attribute unsafe')76 try:77 return getattr(obj, str(arg))78 except (AttributeError, UnicodeError):79 return Undefined(obj, arg)83 if is_unsafe:84 return self.undefined('access to attribute %r of %r object is'85 ' unsafe.' % (86 argument,87 obj.__class__.__name__88 ))89 return self.undefined(obj=obj, name=argument)9091 def call(__self, __obj, *args, **kwargs):92 """Call an object from sandboxed code."""93 # the double prefixes are to avoid double keyword argument
4 unmodified lines