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