improved debugging for syntax errors
[jinja2.git] / jinja2 / environment.py
1 # -*- coding: utf-8 -*-
2 """
3     jinja2.environment
4     ~~~~~~~~~~~~~~~~~~
5
6     Provides a class that holds runtime and parsing time options.
7
8     :copyright: 2008 by Armin Ronacher.
9     :license: BSD, see LICENSE for more details.
10 """
11 import sys
12 from jinja2.defaults import *
13 from jinja2.lexer import Lexer
14 from jinja2.parser import Parser
15 from jinja2.optimizer import optimize
16 from jinja2.compiler import generate
17 from jinja2.runtime import Undefined, Context, concat
18 from jinja2.debug import translate_exception, translate_syntax_error
19 from jinja2.exceptions import TemplateSyntaxError
20 from jinja2.utils import import_string, LRUCache, Markup, missing
21
22
23 # for direct template usage we have up to ten living environments
24 _spontaneous_environments = LRUCache(10)
25
26
27 def get_spontaneous_environment(*args):
28     """Return a new spontaneus environment.  A spontaneus environment is an
29     unnamed and unaccessable (in theory) environment that is used for
30     template generated from a string and not from the file system.
31     """
32     try:
33         env = _spontaneous_environments.get(args)
34     except TypeError:
35         return Environment(*args)
36     if env is not None:
37         return env
38     _spontaneous_environments[args] = env = Environment(*args)
39     env.shared = True
40     return env
41
42
43 def create_cache(size):
44     """Return the cache class for the given size."""
45     if size == 0:
46         return None
47     if size < 0:
48         return {}
49     return LRUCache(size)
50
51
52 def load_extensions(environment, extensions):
53     """Load the extensions from the list and bind it to the environment.
54     Returns a new list of instanciated environments.
55     """
56     result = []
57     for extension in extensions:
58         if isinstance(extension, basestring):
59             extension = import_string(extension)
60         result.append(extension(environment))
61     return result
62
63
64 def _environment_sanity_check(environment):
65     """Perform a sanity check on the environment."""
66     assert issubclass(environment.undefined, Undefined), 'undefined must ' \
67            'be a subclass of undefined because filters depend on it.'
68     assert environment.block_start_string != \
69            environment.variable_start_string != \
70            environment.comment_start_string, 'block, variable and comment ' \
71            'start strings must be different'
72     return environment
73
74
75 class Environment(object):
76     """The core component of Jinja is the `Environment`.  It contains
77     important shared variables like configuration, filters, tests,
78     globals and others.  Instances of this class may be modified if
79     they are not shared and if no template was loaded so far.
80     Modifications on environments after the first template was loaded
81     will lead to surprising effects and undefined behavior.
82
83     Here the possible initialization parameters:
84
85     `block_start_string`
86         The string marking the begin of a block.  Defaults to ``'{%'``.
87
88     `block_end_string`
89         The string marking the end of a block.  Defaults to ``'%}'``.
90
91     `variable_start_string`
92         The string marking the begin of a print statement.
93         Defaults to ``'{{'``.
94
95     `comment_start_string`
96         The string marking the begin of a comment.  Defaults to ``'{#'``.
97
98     `comment_end_string`
99         The string marking the end of a comment.  Defaults to ``'#}'``.
100
101     `line_statement_prefix`
102         If given and a string, this will be used as prefix for line based
103         statements.
104
105     `trim_blocks`
106         If this is set to ``True`` the first newline after a block is
107         removed (block, not variable tag!).  Defaults to `False`.
108
109     `extensions`
110         List of Jinja extensions to use.  This can either be import paths
111         as strings or extension classes.
112
113     `optimized`
114         should the optimizer be enabled?  Default is `True`.
115
116     `undefined`
117         :class:`Undefined` or a subclass of it that is used to represent
118         undefined values in the template.
119
120     `finalize`
121         A callable that finalizes the variable.  Per default no finalizing
122         is applied.
123
124     `autoescape`
125         If set to true the XML/HTML autoescaping feature is enabled.
126
127     `loader`
128         The template loader for this environment.
129
130     `cache_size`
131         The size of the cache.  Per default this is ``50`` which means that if
132         more than 50 templates are loaded the loader will clean out the least
133         recently used template.  If the cache size is set to ``0`` templates are
134         recompiled all the time, if the cache size is ``-1`` the cache will not
135         be cleaned.
136
137     `auto_reload`
138         Some loaders load templates from locations where the template sources
139         may change (ie: file system or database).  If `auto_reload` is set to
140         `True` (default) every time a template is requested the loader checks
141         if the source changed and if yes, it will reload the template.  For
142         higher performance it's possible to disable that.
143     """
144
145     #: if this environment is sandboxed.  Modifying this variable won't make
146     #: the environment sandboxed though.  For a real sandboxed environment
147     #: have a look at jinja2.sandbox
148     sandboxed = False
149
150     #: True if the environment is just an overlay
151     overlay = False
152
153     #: the environment this environment is linked to if it is an overlay
154     linked_to = None
155
156     #: shared environments have this set to `True`.  A shared environment
157     #: must not be modified
158     shared = False
159
160     def __init__(self,
161                  block_start_string=BLOCK_START_STRING,
162                  block_end_string=BLOCK_END_STRING,
163                  variable_start_string=VARIABLE_START_STRING,
164                  variable_end_string=VARIABLE_END_STRING,
165                  comment_start_string=COMMENT_START_STRING,
166                  comment_end_string=COMMENT_END_STRING,
167                  line_statement_prefix=LINE_STATEMENT_PREFIX,
168                  trim_blocks=False,
169                  extensions=(),
170                  optimized=True,
171                  undefined=Undefined,
172                  finalize=None,
173                  autoescape=False,
174                  loader=None,
175                  cache_size=50,
176                  auto_reload=True):
177         # !!Important notice!!
178         #   The constructor accepts quite a few arguments that should be
179         #   passed by keyword rather than position.  However it's important to
180         #   not change the order of arguments because it's used at least
181         #   internally in those cases:
182         #       -   spontaneus environments (i18n extension and Template)
183         #       -   unittests
184         #   If parameter changes are required only add parameters at the end
185         #   and don't change the arguments (or the defaults!) of the arguments
186         #   existing already.
187
188         # lexer / parser information
189         self.block_start_string = block_start_string
190         self.block_end_string = block_end_string
191         self.variable_start_string = variable_start_string
192         self.variable_end_string = variable_end_string
193         self.comment_start_string = comment_start_string
194         self.comment_end_string = comment_end_string
195         self.line_statement_prefix = line_statement_prefix
196         self.trim_blocks = trim_blocks
197
198         # runtime information
199         self.undefined = undefined
200         self.optimized = optimized
201         self.finalize = finalize
202         self.autoescape = autoescape
203
204         # defaults
205         self.filters = DEFAULT_FILTERS.copy()
206         self.tests = DEFAULT_TESTS.copy()
207         self.globals = DEFAULT_NAMESPACE.copy()
208
209         # set the loader provided
210         self.loader = loader
211         self.cache = create_cache(cache_size)
212         self.auto_reload = auto_reload
213
214         # load extensions
215         self.extensions = load_extensions(self, extensions)
216
217         _environment_sanity_check(self)
218
219     def overlay(self, block_start_string=missing, block_end_string=missing,
220                 variable_start_string=missing, variable_end_string=missing,
221                 comment_start_string=missing, comment_end_string=missing,
222                 line_statement_prefix=missing, trim_blocks=missing,
223                 extensions=missing, optimized=missing, undefined=missing,
224                 finalize=missing, autoescape=missing, loader=missing,
225                 cache_size=missing, auto_reload=missing):
226         """Create a new overlay environment that shares all the data with the
227         current environment except of cache and the overriden attributes.
228         Extensions cannot be removed for a overlayed environment.  A overlayed
229         environment automatically gets all the extensions of the environment it
230         is linked to plus optional extra extensions.
231
232         Creating overlays should happen after the initial environment was set
233         up completely.  Not all attributes are truly linked, some are just
234         copied over so modifications on the original environment may not shine
235         through.
236         """
237         args = dict(locals())
238         del args['self'], args['cache_size'], args['extensions']
239
240         rv = object.__new__(self.__class__)
241         rv.__dict__.update(self.__dict__)
242         rv.overlay = True
243         rv.linked_to = self
244
245         for key, value in args.iteritems():
246             if value is not missing:
247                 setattr(rv, key, value)
248
249         if cache_size is not missing:
250             rv.cache = create_cache(cache_size)
251
252         rv.extensions = []
253         for extension in self.extensions:
254             rv.extensions.append(extension.bind(self))
255         if extensions is not missing:
256             rv.extensions.extend(load_extensions(extensions))
257
258         return _environment_sanity_check(rv)
259
260     @property
261     def lexer(self):
262         """Return a fresh lexer for the environment."""
263         return Lexer(self)
264
265     def subscribe(self, obj, argument):
266         """Get an item or attribute of an object."""
267         try:
268             return getattr(obj, str(argument))
269         except (AttributeError, UnicodeError):
270             try:
271                 return obj[argument]
272             except (TypeError, LookupError):
273                 return self.undefined(obj=obj, name=argument)
274
275     def parse(self, source, filename=None):
276         """Parse the sourcecode and return the abstract syntax tree.  This
277         tree of nodes is used by the compiler to convert the template into
278         executable source- or bytecode.  This is useful for debugging or to
279         extract information from templates.
280         """
281         try:
282             return Parser(self, source, filename).parse()
283         except TemplateSyntaxError, e:
284             exc_type, exc_value, tb = translate_syntax_error(e)
285             raise exc_type, exc_value, tb
286
287     def lex(self, source, name=None):
288         """Lex the given sourcecode and return a generator that yields
289         tokens as tuples in the form ``(lineno, token_type, value)``.
290         """
291         return self.lexer.tokeniter(source, name)
292
293     def compile(self, source, name=None, filename=None, globals=None,
294                 raw=False):
295         """Compile a node or template source code.  The `name` parameter is
296         the load name of the template after it was joined using
297         :meth:`join_path` if necessary, not the filename on the file system.
298         the `filename` parameter is the estimated filename of the template on
299         the file system.  If the template came from a database or memory this
300         can be omitted.  The `globals` parameter can be used to provide extra
301         variables at compile time for the template.  In the future the
302         optimizer will be able to evaluate parts of the template at compile
303         time based on those variables.
304
305         The return value of this method is a python code object.  If the `raw`
306         parameter is `True` the return value will be a string with python
307         code equivalent to the bytecode returned otherwise.  This method is
308         mainly used internally.
309         """
310         if isinstance(source, basestring):
311             source = self.parse(source, filename)
312         if self.optimized:
313             node = optimize(source, self, globals or {})
314         source = generate(node, self, name, filename)
315         if raw:
316             return source
317         if filename is None:
318             filename = '<template>'
319         elif isinstance(filename, unicode):
320             filename = filename.encode('utf-8')
321         return compile(source, filename, 'exec')
322
323     def join_path(self, template, parent):
324         """Join a template with the parent.  By default all the lookups are
325         relative to the loader root so this method returns the `template`
326         parameter unchanged, but if the paths should be relative to the
327         parent template, this function can be used to calculate the real
328         template name.
329
330         Subclasses may override this method and implement template path
331         joining here.
332         """
333         return template
334
335     def get_template(self, name, parent=None, globals=None):
336         """Load a template from the loader.  If a loader is configured this
337         method ask the loader for the template and returns a :class:`Template`.
338         If the `parent` parameter is not `None`, :meth:`join_path` is called
339         to get the real template name before loading.
340
341         The `globals` parameter can be used to provide compile-time globals.
342         In the future this will allow the optimizer to render parts of the
343         templates at compile-time.
344
345         If the template does not exist a :exc:`TemplateNotFound` exception is
346         raised.
347         """
348         if self.loader is None:
349             raise TypeError('no loader for this environment specified')
350         if parent is not None:
351             name = self.join_path(name, parent)
352
353         if self.cache is not None:
354             template = self.cache.get(name)
355             if template is not None and (not self.auto_reload or \
356                                          template.is_up_to_date):
357                 return template
358
359         template = self.loader.load(self, name, self.make_globals(globals))
360         if self.cache is not None:
361             self.cache[name] = template
362         return template
363
364     def from_string(self, source, globals=None, template_class=None):
365         """Load a template from a string.  This parses the source given and
366         returns a :class:`Template` object.
367         """
368         globals = self.make_globals(globals)
369         cls = template_class or self.template_class
370         return cls.from_code(self, self.compile(source, globals=globals),
371                              globals, None)
372
373     def make_globals(self, d):
374         """Return a dict for the globals."""
375         if d is None:
376             return self.globals
377         return dict(self.globals, **d)
378
379
380 class Template(object):
381     """The central template object.  This class represents a compiled template
382     and is used to evaluate it.
383
384     Normally the template object is generated from an :class:`Environment` but
385     it also has a constructor that makes it possible to create a template
386     instance directly using the constructor.  It takes the same arguments as
387     the environment constructor but it's not possible to specify a loader.
388
389     Every template object has a few methods and members that are guaranteed
390     to exist.  However it's important that a template object should be
391     considered immutable.  Modifications on the object are not supported.
392
393     Template objects created from the constructor rather than an environment
394     do have an `environment` attribute that points to a temporary environment
395     that is probably shared with other templates created with the constructor
396     and compatible settings.
397
398     >>> template = Template('Hello {{ name }}!')
399     >>> template.render(name='John Doe')
400     u'Hello John Doe!'
401
402     >>> stream = template.stream(name='John Doe')
403     >>> stream.next()
404     u'Hello John Doe!'
405     >>> stream.next()
406     Traceback (most recent call last):
407         ...
408     StopIteration
409     """
410
411     def __new__(cls, source,
412                 block_start_string='{%',
413                 block_end_string='%}',
414                 variable_start_string='{{',
415                 variable_end_string='}}',
416                 comment_start_string='{#',
417                 comment_end_string='#}',
418                 line_statement_prefix=None,
419                 trim_blocks=False,
420                 extensions=(),
421                 optimized=True,
422                 undefined=Undefined,
423                 finalize=None,
424                 autoescape=False):
425         env = get_spontaneous_environment(
426             block_start_string, block_end_string, variable_start_string,
427             variable_end_string, comment_start_string, comment_end_string,
428             line_statement_prefix, trim_blocks, tuple(extensions), optimized,
429             undefined, finalize, autoescape, None, 0, False)
430         return env.from_string(source, template_class=cls)
431
432     @classmethod
433     def from_code(cls, environment, code, globals, uptodate=None):
434         """Creates a template object from compiled code and the globals.  This
435         is used by the loaders and environment to create a template object.
436         """
437         t = object.__new__(cls)
438         namespace = {
439             'environment':          environment,
440             '__jinja_template__':   t
441         }
442         exec code in namespace
443         t.environment = environment
444         t.name = namespace['name']
445         t.filename = code.co_filename
446         t.root_render_func = namespace['root']
447         t.blocks = namespace['blocks']
448         t.globals = globals
449
450         # debug and loader helpers
451         t._debug_info = namespace['debug_info']
452         t._uptodate = uptodate
453
454         return t
455
456     def render(self, *args, **kwargs):
457         """This method accepts the same arguments as the `dict` constructor:
458         A dict, a dict subclass or some keyword arguments.  If no arguments
459         are given the context will be empty.  These two calls do the same::
460
461             template.render(knights='that say nih')
462             template.render({'knights': 'that say nih'})
463
464         This will return the rendered template as unicode string.
465         """
466         try:
467             return concat(self._generate(*args, **kwargs))
468         except:
469             exc_type, exc_value, tb = translate_exception(sys.exc_info())
470             raise exc_type, exc_value, tb
471
472     def stream(self, *args, **kwargs):
473         """Works exactly like :meth:`generate` but returns a
474         :class:`TemplateStream`.
475         """
476         return TemplateStream(self.generate(*args, **kwargs))
477
478     def generate(self, *args, **kwargs):
479         """For very large templates it can be useful to not render the whole
480         template at once but evaluate each statement after another and yield
481         piece for piece.  This method basically does exactly that and returns
482         a generator that yields one item after another as unicode strings.
483
484         It accepts the same arguments as :meth:`render`.
485         """
486         try:
487             for item in self._generate(*args, **kwargs):
488                 yield item
489         except:
490             exc_type, exc_value, tb = translate_exception(sys.exc_info())
491             raise exc_type, exc_value, tb
492
493     def _generate(self, *args, **kwargs):
494         # assemble the context
495         context = dict(*args, **kwargs)
496
497         # if the environment is using the optimizer locals may never
498         # override globals as optimizations might have happened
499         # depending on values of certain globals.  This assertion goes
500         # away if the python interpreter is started with -O
501         if __debug__ and self.environment.optimized:
502             overrides = set(context) & set(self.globals)
503             if overrides:
504                 plural = len(overrides) != 1 and 's' or ''
505                 raise AssertionError('the per template variable%s %s '
506                                      'override%s global variable%s. '
507                                      'With an enabled optimizer this '
508                                      'will lead to unexpected results.' %
509                     (plural, ', '.join(overrides), plural or ' a', plural))
510
511         return self.root_render_func(self.new_context(context))
512
513     def new_context(self, vars=None, shared=False):
514         """Create a new template context for this template.  The vars
515         provided will be passed to the template.  Per default the globals
516         are added to the context, if shared is set to `True` the data
517         provided is used as parent namespace.  This is used to share the
518         same globals in multiple contexts without consuming more memory.
519         (This works because the context does not modify the parent dict)
520         """
521         if vars is None:
522             vars = {}
523         if shared:
524             parent = vars
525         else:
526             parent = dict(self.globals, **vars)
527         return Context(self.environment, parent, self.name, self.blocks)
528
529     @property
530     def module(self):
531         """The template as module.  This is used for imports in the
532         template runtime but is also useful if one wants to access
533         exported template variables from the Python layer:
534
535         >>> t = Template('{% macro foo() %}42{% endmacro %}23')
536         >>> unicode(t.module)
537         u'23'
538         >>> t.module.foo()
539         u'42'
540         """
541         if hasattr(self, '_module'):
542             return self._module
543         self._module = rv = TemplateModule(self, self.new_context())
544         return rv
545
546     def get_corresponding_lineno(self, lineno):
547         """Return the source line number of a line number in the
548         generated bytecode as they are not in sync.
549         """
550         for template_line, code_line in reversed(self.debug_info):
551             if code_line <= lineno:
552                 return template_line
553         return 1
554
555     @property
556     def is_up_to_date(self):
557         """If this variable is `False` there is a newer version available."""
558         if self._uptodate is None:
559             return True
560         return self._uptodate()
561
562     @property
563     def debug_info(self):
564         """The debug info mapping."""
565         return [tuple(map(int, x.split('='))) for x in
566                 self._debug_info.split('&')]
567
568     def __repr__(self):
569         if self.name is None:
570             name = 'memory:%x' % id(self)
571         else:
572             name = repr(self.name)
573         return '<%s %s>' % (self.__class__.__name__, name)
574
575
576 class TemplateModule(object):
577     """Represents an imported template.  All the exported names of the
578     template are available as attributes on this object.  Additionally
579     converting it into an unicode- or bytestrings renders the contents.
580     """
581
582     def __init__(self, template, context):
583         self.__body_stream = tuple(template.root_render_func(context))
584         self.__dict__.update(context.get_exported())
585         self.__name__ = template.name
586
587     __html__ = lambda x: Markup(concat(x.__body_stream))
588     __unicode__ = lambda x: unicode(concat(x.__body_stream))
589
590     def __str__(self):
591         return unicode(self).encode('utf-8')
592
593     def __repr__(self):
594         if self.__name__ is None:
595             name = 'memory:%x' % id(self)
596         else:
597             name = repr(self.name)
598         return '<%s %s>' % (self.__class__.__name__, name)
599
600
601 class TemplateStream(object):
602     """A template stream works pretty much like an ordinary python generator
603     but it can buffer multiple items to reduce the number of total iterations.
604     Per default the output is unbuffered which means that for every unbuffered
605     instruction in the template one unicode string is yielded.
606
607     If buffering is enabled with a buffer size of 5, five items are combined
608     into a new unicode string.  This is mainly useful if you are streaming
609     big templates to a client via WSGI which flushes after each iteration.
610     """
611
612     def __init__(self, gen):
613         self._gen = gen
614         self._next = gen.next
615         self.buffered = False
616
617     def disable_buffering(self):
618         """Disable the output buffering."""
619         self._next = self._gen.next
620         self.buffered = False
621
622     def enable_buffering(self, size=5):
623         """Enable buffering.  Buffer `size` items before yielding them."""
624         if size <= 1:
625             raise ValueError('buffer size too small')
626
627         def generator():
628             buf = []
629             c_size = 0
630             push = buf.append
631             next = self._gen.next
632
633             while 1:
634                 try:
635                     while c_size < size:
636                         push(next())
637                         c_size += 1
638                 except StopIteration:
639                     if not c_size:
640                         return
641                 yield concat(buf)
642                 del buf[:]
643                 c_size = 0
644
645         self.buffered = True
646         self._next = generator().next
647
648     def __iter__(self):
649         return self
650
651     def next(self):
652         return self._next()
653
654
655 # hook in default template class.  if anyone reads this comment: ignore that
656 # it's possible to use custom templates ;-)
657 Environment.template_class = Template