Automated merge with ssh://team@pocoo.org/jinja2-main
[jinja2.git] / jinja2 / runtime.py
1 # -*- coding: utf-8 -*-
2 """
3     jinja2.runtime
4     ~~~~~~~~~~~~~~
5
6     Runtime helpers.
7
8     :copyright: Copyright 2008 by Armin Ronacher.
9     :license: GNU GPL.
10 """
11 import sys
12 from types import FunctionType
13 from itertools import chain, imap
14 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat
15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError
16
17
18 # these variables are exported to the template runtime
19 __all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
20            'TemplateRuntimeError', 'missing', 'concat', 'escape',
21            'markup_join', 'unicode_join']
22
23
24 def markup_join(seq):
25     """Concatenation that escapes if necessary and converts to unicode."""
26     buf = []
27     iterator = imap(soft_unicode, seq)
28     for arg in iterator:
29         buf.append(arg)
30         if hasattr(arg, '__html__'):
31             return Markup(u'').join(chain(buf, iterator))
32     return concat(buf)
33
34
35 def unicode_join(seq):
36     """Simple args to unicode conversion and concatenation."""
37     return concat(imap(unicode, seq))
38
39
40 class Context(object):
41     """The template context holds the variables of a template.  It stores the
42     values passed to the template and also the names the template exports.
43     Creating instances is neither supported nor useful as it's created
44     automatically at various stages of the template evaluation and should not
45     be created by hand.
46
47     The context is immutable.  Modifications on :attr:`parent` **must not**
48     happen and modifications on :attr:`vars` are allowed from generated
49     template code only.  Template filters and global functions marked as
50     :func:`contextfunction`\s get the active context passed as first argument
51     and are allowed to access the context read-only.
52
53     The template context supports read only dict operations (`get`,
54     `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
55     `__getitem__`, `__contains__`).  Additionally there is a :meth:`resolve`
56     method that doesn't fail with a `KeyError` but returns an
57     :class:`Undefined` object for missing variables.
58     """
59     __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',
60                  'blocks')
61
62     def __init__(self, environment, parent, name, blocks):
63         self.parent = parent
64         self.vars = vars = {}
65         self.environment = environment
66         self.exported_vars = set()
67         self.name = name
68
69         # create the initial mapping of blocks.  Whenever template inheritance
70         # takes place the runtime will update this mapping with the new blocks
71         # from the template.
72         self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
73
74     def super(self, name, current):
75         """Render a parent block."""
76         try:
77             blocks = self.blocks[name]
78             block = blocks[blocks.index(current) + 1]
79         except LookupError:
80             return self.environment.undefined('there is no parent block '
81                                               'called %r.' % name,
82                                               name='super')
83         wrap = self.environment.autoescape and Markup or (lambda x: x)
84         render = lambda: wrap(concat(block(self)))
85         render.__name__ = render.name = name
86         return render
87
88     def get(self, key, default=None):
89         """Returns an item from the template context, if it doesn't exist
90         `default` is returned.
91         """
92         try:
93             return self[key]
94         except KeyError:
95             return default
96
97     def resolve(self, key):
98         """Looks up a variable like `__getitem__` or `get` but returns an
99         :class:`Undefined` object with the name of the name looked up.
100         """
101         if key in self.vars:
102             return self.vars[key]
103         if key in self.parent:
104             return self.parent[key]
105         return self.environment.undefined(name=key)
106
107     def get_exported(self):
108         """Get a new dict with the exported variables."""
109         return dict((k, self.vars[k]) for k in self.exported_vars)
110
111     def get_all(self):
112         """Return a copy of the complete context as dict including the
113         exported variables.
114         """
115         return dict(self.parent, **self.vars)
116
117     def call(__self, __obj, *args, **kwargs):
118         """Called by the template code to inject the current context
119         or environment as first arguments.  Then forwards the call to
120         the object with the arguments and keyword arguments.
121         """
122         if getattr(__obj, 'contextfunction', 0):
123             args = (__self,) + args
124         elif getattr(__obj, 'environmentfunction', 0):
125             args = (__self.environment,) + args
126         return __obj(*args, **kwargs)
127
128     def _all(meth):
129         proxy = lambda self: getattr(self.get_all(), meth)()
130         proxy.__doc__ = getattr(dict, meth).__doc__
131         proxy.__name__ = meth
132         return proxy
133
134     keys = _all('keys')
135     values = _all('values')
136     items = _all('items')
137     iterkeys = _all('iterkeys')
138     itervalues = _all('itervalues')
139     iteritems = _all('iteritems')
140     del _all
141
142     def __contains__(self, name):
143         return name in self.vars or name in self.parent
144
145     def __getitem__(self, key):
146         """Lookup a variable or raise `KeyError` if the variable is
147         undefined.
148         """
149         item = self.resolve(key)
150         if isinstance(item, Undefined):
151             raise KeyError(key)
152         return item
153
154     def __repr__(self):
155         return '<%s %s of %r>' % (
156             self.__class__.__name__,
157             repr(self.get_all()),
158             self.name
159         )
160
161
162 class TemplateReference(object):
163     """The `self` in templates."""
164
165     def __init__(self, context):
166         self.__context = context
167
168     def __getitem__(self, name):
169         func = self.__context.blocks[name][0]
170         wrap = self.__context.environment.autoescape and \
171                Markup or (lambda x: x)
172         render = lambda: wrap(concat(func(self.__context)))
173         render.__name__ = render.name = name
174         return render
175
176     def __repr__(self):
177         return '<%s %r>' % (
178             self.__class__.__name__,
179             self._context.name
180         )
181
182
183 class LoopContext(object):
184     """A loop context for dynamic iteration."""
185
186     def __init__(self, iterable, enforce_length=False, recurse=None):
187         self._iterable = iterable
188         self._next = iter(iterable).next
189         self._length = None
190         self._recurse = recurse
191         self.index0 = -1
192         if enforce_length:
193             len(self)
194
195     def cycle(self, *args):
196         """Cycles among the arguments with the current loop index."""
197         if not args:
198             raise TypeError('no items for cycling given')
199         return args[self.index0 % len(args)]
200
201     first = property(lambda x: x.index0 == 0)
202     last = property(lambda x: x.revindex0 == 0)
203     index = property(lambda x: x.index0 + 1)
204     revindex = property(lambda x: x.length - x.index0)
205     revindex0 = property(lambda x: x.length - x.index)
206
207     def __len__(self):
208         return self.length
209
210     def __iter__(self):
211         return LoopContextIterator(self)
212
213     def loop(self, iterable):
214         if self._recurse is None:
215             raise TypeError('Tried to call non recursive loop.  Maybe you '
216                             "forgot the 'recursive' modifier.")
217         return self._recurse(iterable, self._recurse)
218
219     # a nifty trick to enhance the error message if someone tried to call
220     # the the loop without or with too many arguments.
221     __call__ = loop; del loop
222
223     @property
224     def length(self):
225         if self._length is None:
226             try:
227                 # first try to get the length from the iterable (if the
228                 # iterable is a sequence)
229                 length = len(self._iterable)
230             except TypeError:
231                 # if that's not possible (ie: iterating over a generator)
232                 # we have to convert the iterable into a sequence and
233                 # use the length of that.
234                 self._iterable = tuple(self._iterable)
235                 self._next = iter(self._iterable).next
236                 length = len(tuple(self._iterable)) + self.index0 + 1
237             self._length = length
238         return self._length
239
240     def __repr__(self):
241         return '<%s %r/%r>' % (
242             self.__class__.__name__,
243             self.index,
244             self.length
245         )
246
247
248 class LoopContextIterator(object):
249     """The iterator for a loop context."""
250     __slots__ = ('context',)
251
252     def __init__(self, context):
253         self.context = context
254
255     def __iter__(self):
256         return self
257
258     def next(self):
259         ctx = self.context
260         ctx.index0 += 1
261         return ctx._next(), ctx
262
263
264 class Macro(object):
265     """Wraps a macro."""
266
267     def __init__(self, environment, func, name, arguments, defaults,
268                  catch_kwargs, catch_varargs, caller):
269         self._environment = environment
270         self._func = func
271         self._argument_count = len(arguments)
272         self.name = name
273         self.arguments = arguments
274         self.defaults = defaults
275         self.catch_kwargs = catch_kwargs
276         self.catch_varargs = catch_varargs
277         self.caller = caller
278
279     def __call__(self, *args, **kwargs):
280         arguments = []
281         for idx, name in enumerate(self.arguments):
282             try:
283                 value = args[idx]
284             except:
285                 try:
286                     value = kwargs.pop(name)
287                 except:
288                     try:
289                         value = self.defaults[idx - self._argument_count]
290                     except:
291                         value = self._environment.undefined(
292                             'parameter %r was not provided' % name, name=name)
293             arguments.append(value)
294
295         # it's important that the order of these arguments does not change
296         # if not also changed in the compiler's `function_scoping` method.
297         # the order is caller, keyword arguments, positional arguments!
298         if self.caller:
299             caller = kwargs.pop('caller', None)
300             if caller is None:
301                 caller = self._environment.undefined('No caller defined',
302                                                      name='caller')
303             arguments.append(caller)
304         if self.catch_kwargs:
305             arguments.append(kwargs)
306         elif kwargs:
307             raise TypeError('macro %r takes no keyword argument %r' %
308                             (self.name, iter(kwargs).next()))
309         if self.catch_varargs:
310             arguments.append(args[self._argument_count:])
311         elif len(args) > self._argument_count:
312             raise TypeError('macro %r takes not more than %d argument(s)' %
313                             (self.name, len(self.arguments)))
314         return self._func(*arguments)
315
316     def __repr__(self):
317         return '<%s %s>' % (
318             self.__class__.__name__,
319             self.name is None and 'anonymous' or repr(self.name)
320         )
321
322
323 def fail_with_undefined_error(self, *args, **kwargs):
324     """Regular callback function for undefined objects that raises an
325     `UndefinedError` on call.
326     """
327     if self._undefined_hint is None:
328         if self._undefined_obj is None:
329             hint = '%r is undefined' % self._undefined_name
330         elif not isinstance(self._undefined_name, basestring):
331             hint = '%r object has no element %r' % (
332                 self._undefined_obj.__class__.__name__,
333                 self._undefined_name
334             )
335         else:
336             hint = '%r object has no attribute %r' % (
337                 self._undefined_obj.__class__.__name__,
338                 self._undefined_name
339             )
340     else:
341         hint = self._undefined_hint
342     raise self._undefined_exception(hint)
343
344
345 class Undefined(object):
346     """The default undefined type.  This undefined type can be printed and
347     iterated over, but every other access will raise an :exc:`UndefinedError`:
348
349     >>> foo = Undefined(name='foo')
350     >>> str(foo)
351     ''
352     >>> not foo
353     True
354     >>> foo + 42
355     Traceback (most recent call last):
356       ...
357     jinja2.exceptions.UndefinedError: 'foo' is undefined
358     """
359     __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
360                  '_undefined_exception')
361
362     def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
363         self._undefined_hint = hint
364         self._undefined_obj = obj
365         self._undefined_name = name
366         self._undefined_exception = exc
367
368     __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
369     __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
370     __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
371     __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
372         fail_with_undefined_error
373
374     def __str__(self):
375         return self.__unicode__().encode('utf-8')
376
377     def __repr__(self):
378         return 'Undefined'
379
380     def __unicode__(self):
381         return u''
382
383     def __len__(self):
384         return 0
385
386     def __iter__(self):
387         if 0:
388             yield None
389
390     def __nonzero__(self):
391         return False
392
393
394 class DebugUndefined(Undefined):
395     """An undefined that returns the debug info when printed.
396
397     >>> foo = DebugUndefined(name='foo')
398     >>> str(foo)
399     '{{ foo }}'
400     >>> not foo
401     True
402     >>> foo + 42
403     Traceback (most recent call last):
404       ...
405     jinja2.exceptions.UndefinedError: 'foo' is undefined
406     """
407     __slots__ = ()
408
409     def __unicode__(self):
410         if self._undefined_hint is None:
411             if self._undefined_obj is None:
412                 return u'{{ %s }}' % self._undefined_name
413             return '{{ no such element: %s[%r] }}' % (
414                 self._undefined_obj.__class__.__name__,
415                 self._undefined_name
416             )
417         return u'{{ undefined value printed: %s }}' % self._undefined_hint
418
419
420 class StrictUndefined(Undefined):
421     """An undefined that barks on print and iteration as well as boolean
422     tests and all kinds of comparisons.  In other words: you can do nothing
423     with it except checking if it's defined using the `defined` test.
424
425     >>> foo = StrictUndefined(name='foo')
426     >>> str(foo)
427     Traceback (most recent call last):
428       ...
429     jinja2.exceptions.UndefinedError: 'foo' is undefined
430     >>> not foo
431     Traceback (most recent call last):
432       ...
433     jinja2.exceptions.UndefinedError: 'foo' is undefined
434     >>> foo + 42
435     Traceback (most recent call last):
436       ...
437     jinja2.exceptions.UndefinedError: 'foo' is undefined
438     """
439     __slots__ = ()
440     __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
441         fail_with_undefined_error
442
443
444 # remove remaining slots attributes, after the metaclass did the magic they
445 # are unneeded and irritating as they contain wrong data for the subclasses.
446 del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__