Added first version of IR importer/exporter
[libfirm] / scripts / 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 import nodes
13 from jinja2.defaults import *
14 from jinja2.lexer import get_lexer, TokenStream
15 from jinja2.parser import Parser
16 from jinja2.optimizer import optimize
17 from jinja2.compiler import generate
18 from jinja2.runtime import Undefined, Context
19 from jinja2.exceptions import TemplateSyntaxError
20 from jinja2.utils import import_string, LRUCache, Markup, missing, \
21      concat, consume
22
23
24 # for direct template usage we have up to ten living environments
25 _spontaneous_environments = LRUCache(10)
26
27
28 def get_spontaneous_environment(*args):
29     """Return a new spontaneous environment.  A spontaneous environment is an
30     unnamed and unaccessible (in theory) environment that is used for
31     templates generated from a string and not from the file system.
32     """
33     try:
34         env = _spontaneous_environments.get(args)
35     except TypeError:
36         return Environment(*args)
37     if env is not None:
38         return env
39     _spontaneous_environments[args] = env = Environment(*args)
40     env.shared = True
41     return env
42
43
44 def create_cache(size):
45     """Return the cache class for the given size."""
46     if size == 0:
47         return None
48     if size < 0:
49         return {}
50     return LRUCache(size)
51
52
53 def copy_cache(cache):
54     """Create an empty copy of the given cache."""
55     if cache is None:
56         return Noe
57     elif type(cache) is dict:
58         return {}
59     return LRUCache(cache.capacity)
60
61
62 def load_extensions(environment, extensions):
63     """Load the extensions from the list and bind it to the environment.
64     Returns a dict of instanciated environments.
65     """
66     result = {}
67     for extension in extensions:
68         if isinstance(extension, basestring):
69             extension = import_string(extension)
70         result[extension.identifier] = extension(environment)
71     return result
72
73
74 def _environment_sanity_check(environment):
75     """Perform a sanity check on the environment."""
76     assert issubclass(environment.undefined, Undefined), 'undefined must ' \
77            'be a subclass of undefined because filters depend on it.'
78     assert environment.block_start_string != \
79            environment.variable_start_string != \
80            environment.comment_start_string, 'block, variable and comment ' \
81            'start strings must be different'
82     assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
83            'newline_sequence set to unknown line ending string.'
84     return environment
85
86
87 class Environment(object):
88     r"""The core component of Jinja is the `Environment`.  It contains
89     important shared variables like configuration, filters, tests,
90     globals and others.  Instances of this class may be modified if
91     they are not shared and if no template was loaded so far.
92     Modifications on environments after the first template was loaded
93     will lead to surprising effects and undefined behavior.
94
95     Here the possible initialization parameters:
96
97         `block_start_string`
98             The string marking the begin of a block.  Defaults to ``'{%'``.
99
100         `block_end_string`
101             The string marking the end of a block.  Defaults to ``'%}'``.
102
103         `variable_start_string`
104             The string marking the begin of a print statement.
105             Defaults to ``'{{'``.
106
107         `variable_end_string`
108             The string marking the end of a print statement.  Defaults to
109             ``'}}'``.
110
111         `comment_start_string`
112             The string marking the begin of a comment.  Defaults to ``'{#'``.
113
114         `comment_end_string`
115             The string marking the end of a comment.  Defaults to ``'#}'``.
116
117         `line_statement_prefix`
118             If given and a string, this will be used as prefix for line based
119             statements.  See also :ref:`line-statements`.
120
121         `trim_blocks`
122             If this is set to ``True`` the first newline after a block is
123             removed (block, not variable tag!).  Defaults to `False`.
124
125         `newline_sequence`
126             The sequence that starts a newline.  Must be one of ``'\r'``,
127             ``'\n'`` or ``'\r\n'``.  The default is ``'\n'`` which is a
128             useful default for Linux and OS X systems as well as web
129             applications.
130
131         `extensions`
132             List of Jinja extensions to use.  This can either be import paths
133             as strings or extension classes.  For more information have a
134             look at :ref:`the extensions documentation <jinja-extensions>`.
135
136         `optimized`
137             should the optimizer be enabled?  Default is `True`.
138
139         `undefined`
140             :class:`Undefined` or a subclass of it that is used to represent
141             undefined values in the template.
142
143         `finalize`
144             A callable that finalizes the variable.  Per default no finalizing
145             is applied.
146
147         `autoescape`
148             If set to true the XML/HTML autoescaping feature is enabled.
149             For more details about auto escaping see
150             :class:`~jinja2.utils.Markup`.
151
152         `loader`
153             The template loader for this environment.
154
155         `cache_size`
156             The size of the cache.  Per default this is ``50`` which means
157             that if more than 50 templates are loaded the loader will clean
158             out the least recently used template.  If the cache size is set to
159             ``0`` templates are recompiled all the time, if the cache size is
160             ``-1`` the cache will not be cleaned.
161
162         `auto_reload`
163             Some loaders load templates from locations where the template
164             sources may change (ie: file system or database).  If
165             `auto_reload` is set to `True` (default) every time a template is
166             requested the loader checks if the source changed and if yes, it
167             will reload the template.  For higher performance it's possible to
168             disable that.
169
170         `bytecode_cache`
171             If set to a bytecode cache object, this object will provide a
172             cache for the internal Jinja bytecode so that templates don't
173             have to be parsed if they were not changed.
174
175             See :ref:`bytecode-cache` for more information.
176     """
177
178     #: if this environment is sandboxed.  Modifying this variable won't make
179     #: the environment sandboxed though.  For a real sandboxed environment
180     #: have a look at jinja2.sandbox
181     sandboxed = False
182
183     #: True if the environment is just an overlay
184     overlay = False
185
186     #: the environment this environment is linked to if it is an overlay
187     linked_to = None
188
189     #: shared environments have this set to `True`.  A shared environment
190     #: must not be modified
191     shared = False
192
193     def __init__(self,
194                  block_start_string=BLOCK_START_STRING,
195                  block_end_string=BLOCK_END_STRING,
196                  variable_start_string=VARIABLE_START_STRING,
197                  variable_end_string=VARIABLE_END_STRING,
198                  comment_start_string=COMMENT_START_STRING,
199                  comment_end_string=COMMENT_END_STRING,
200                  line_statement_prefix=LINE_STATEMENT_PREFIX,
201                  trim_blocks=TRIM_BLOCKS,
202                  newline_sequence=NEWLINE_SEQUENCE,
203                  extensions=(),
204                  optimized=True,
205                  undefined=Undefined,
206                  finalize=None,
207                  autoescape=False,
208                  loader=None,
209                  cache_size=50,
210                  auto_reload=True,
211                  bytecode_cache=None):
212         # !!Important notice!!
213         #   The constructor accepts quite a few arguments that should be
214         #   passed by keyword rather than position.  However it's important to
215         #   not change the order of arguments because it's used at least
216         #   internally in those cases:
217         #       -   spontaneus environments (i18n extension and Template)
218         #       -   unittests
219         #   If parameter changes are required only add parameters at the end
220         #   and don't change the arguments (or the defaults!) of the arguments
221         #   existing already.
222
223         # lexer / parser information
224         self.block_start_string = block_start_string
225         self.block_end_string = block_end_string
226         self.variable_start_string = variable_start_string
227         self.variable_end_string = variable_end_string
228         self.comment_start_string = comment_start_string
229         self.comment_end_string = comment_end_string
230         self.line_statement_prefix = line_statement_prefix
231         self.trim_blocks = trim_blocks
232         self.newline_sequence = newline_sequence
233
234         # runtime information
235         self.undefined = undefined
236         self.optimized = optimized
237         self.finalize = finalize
238         self.autoescape = autoescape
239
240         # defaults
241         self.filters = DEFAULT_FILTERS.copy()
242         self.tests = DEFAULT_TESTS.copy()
243         self.globals = DEFAULT_NAMESPACE.copy()
244
245         # set the loader provided
246         self.loader = loader
247         self.bytecode_cache = None
248         self.cache = create_cache(cache_size)
249         self.bytecode_cache = bytecode_cache
250         self.auto_reload = auto_reload
251
252         # load extensions
253         self.extensions = load_extensions(self, extensions)
254
255         _environment_sanity_check(self)
256
257     def extend(self, **attributes):
258         """Add the items to the instance of the environment if they do not exist
259         yet.  This is used by :ref:`extensions <writing-extensions>` to register
260         callbacks and configuration values without breaking inheritance.
261         """
262         for key, value in attributes.iteritems():
263             if not hasattr(self, key):
264                 setattr(self, key, value)
265
266     def overlay(self, block_start_string=missing, block_end_string=missing,
267                 variable_start_string=missing, variable_end_string=missing,
268                 comment_start_string=missing, comment_end_string=missing,
269                 line_statement_prefix=missing, trim_blocks=missing,
270                 extensions=missing, optimized=missing, undefined=missing,
271                 finalize=missing, autoescape=missing, loader=missing,
272                 cache_size=missing, auto_reload=missing,
273                 bytecode_cache=missing):
274         """Create a new overlay environment that shares all the data with the
275         current environment except of cache and the overriden attributes.
276         Extensions cannot be removed for a overlayed environment.  A overlayed
277         environment automatically gets all the extensions of the environment it
278         is linked to plus optional extra extensions.
279
280         Creating overlays should happen after the initial environment was set
281         up completely.  Not all attributes are truly linked, some are just
282         copied over so modifications on the original environment may not shine
283         through.
284         """
285         args = dict(locals())
286         del args['self'], args['cache_size'], args['extensions']
287
288         rv = object.__new__(self.__class__)
289         rv.__dict__.update(self.__dict__)
290         rv.overlay = True
291         rv.linked_to = self
292
293         for key, value in args.iteritems():
294             if value is not missing:
295                 setattr(rv, key, value)
296
297         if cache_size is not missing:
298             rv.cache = create_cache(cache_size)
299         else:
300             rv.cache = copy_cache(self.cache)
301
302         rv.extensions = {}
303         for key, value in self.extensions.iteritems():
304             rv.extensions[key] = value.bind(rv)
305         if extensions is not missing:
306             rv.extensions.update(load_extensions(extensions))
307
308         return _environment_sanity_check(rv)
309
310     lexer = property(get_lexer, doc="The lexer for this environment.")
311
312     def getitem(self, obj, argument):
313         """Get an item or attribute of an object but prefer the item."""
314         try:
315             return obj[argument]
316         except (TypeError, LookupError):
317             if isinstance(argument, basestring):
318                 try:
319                     attr = str(argument)
320                 except:
321                     pass
322                 else:
323                     try:
324                         return getattr(obj, attr)
325                     except AttributeError:
326                         pass
327             return self.undefined(obj=obj, name=argument)
328
329     def getattr(self, obj, attribute):
330         """Get an item or attribute of an object but prefer the attribute.
331         Unlike :meth:`getitem` the attribute *must* be a bytestring.
332         """
333         try:
334             return getattr(obj, attribute)
335         except AttributeError:
336             pass
337         try:
338             return obj[attribute]
339         except (TypeError, LookupError, AttributeError):
340             return self.undefined(obj=obj, name=attribute)
341
342     def parse(self, source, name=None, filename=None):
343         """Parse the sourcecode and return the abstract syntax tree.  This
344         tree of nodes is used by the compiler to convert the template into
345         executable source- or bytecode.  This is useful for debugging or to
346         extract information from templates.
347
348         If you are :ref:`developing Jinja2 extensions <writing-extensions>`
349         this gives you a good overview of the node tree generated.
350         """
351         if isinstance(filename, unicode):
352             filename = filename.encode('utf-8')
353         try:
354             return Parser(self, source, name, filename).parse()
355         except TemplateSyntaxError, e:
356             e.source = source
357             raise e
358
359     def lex(self, source, name=None, filename=None):
360         """Lex the given sourcecode and return a generator that yields
361         tokens as tuples in the form ``(lineno, token_type, value)``.
362         This can be useful for :ref:`extension development <writing-extensions>`
363         and debugging templates.
364
365         This does not perform preprocessing.  If you want the preprocessing
366         of the extensions to be applied you have to filter source through
367         the :meth:`preprocess` method.
368         """
369         source = unicode(source)
370         try:
371             return self.lexer.tokeniter(source, name, filename)
372         except TemplateSyntaxError, e:
373             e.source = source
374             raise e
375
376     def preprocess(self, source, name=None, filename=None):
377         """Preprocesses the source with all extensions.  This is automatically
378         called for all parsing and compiling methods but *not* for :meth:`lex`
379         because there you usually only want the actual source tokenized.
380         """
381         return reduce(lambda s, e: e.preprocess(s, name, filename),
382                       self.extensions.itervalues(), unicode(source))
383
384     def _tokenize(self, source, name, filename=None, state=None):
385         """Called by the parser to do the preprocessing and filtering
386         for all the extensions.  Returns a :class:`~jinja2.lexer.TokenStream`.
387         """
388         source = self.preprocess(source, name, filename)
389         stream = self.lexer.tokenize(source, name, filename, state)
390         for ext in self.extensions.itervalues():
391             stream = ext.filter_stream(stream)
392             if not isinstance(stream, TokenStream):
393                 stream = TokenStream(stream, name, filename)
394         return stream
395
396     def compile(self, source, name=None, filename=None, raw=False):
397         """Compile a node or template source code.  The `name` parameter is
398         the load name of the template after it was joined using
399         :meth:`join_path` if necessary, not the filename on the file system.
400         the `filename` parameter is the estimated filename of the template on
401         the file system.  If the template came from a database or memory this
402         can be omitted.
403
404         The return value of this method is a python code object.  If the `raw`
405         parameter is `True` the return value will be a string with python
406         code equivalent to the bytecode returned otherwise.  This method is
407         mainly used internally.
408         """
409         if isinstance(source, basestring):
410             source = self.parse(source, name, filename)
411         if self.optimized:
412             source = optimize(source, self)
413         source = generate(source, self, name, filename)
414         if raw:
415             return source
416         if filename is None:
417             filename = '<template>'
418         elif isinstance(filename, unicode):
419             filename = filename.encode('utf-8')
420         return compile(source, filename, 'exec')
421
422     def compile_expression(self, source, undefined_to_none=True):
423         """A handy helper method that returns a callable that accepts keyword
424         arguments that appear as variables in the expression.  If called it
425         returns the result of the expression.
426
427         This is useful if applications want to use the same rules as Jinja
428         in template "configuration files" or similar situations.
429
430         Example usage:
431
432         >>> env = Environment()
433         >>> expr = env.compile_expression('foo == 42')
434         >>> expr(foo=23)
435         False
436         >>> expr(foo=42)
437         True
438
439         Per default the return value is converted to `None` if the
440         expression returns an undefined value.  This can be changed
441         by setting `undefined_to_none` to `False`.
442
443         >>> env.compile_expression('var')() is None
444         True
445         >>> env.compile_expression('var', undefined_to_none=False)()
446         Undefined
447
448         **new in Jinja 2.1**
449         """
450         parser = Parser(self, source, state='variable')
451         try:
452             expr = parser.parse_expression()
453             if not parser.stream.eos:
454                 raise TemplateSyntaxError('chunk after expression',
455                                           parser.stream.current.lineno,
456                                           None, None)
457         except TemplateSyntaxError, e:
458             e.source = source
459             raise e
460         body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
461         template = self.from_string(nodes.Template(body, lineno=1))
462         return TemplateExpression(template, undefined_to_none)
463
464     def join_path(self, template, parent):
465         """Join a template with the parent.  By default all the lookups are
466         relative to the loader root so this method returns the `template`
467         parameter unchanged, but if the paths should be relative to the
468         parent template, this function can be used to calculate the real
469         template name.
470
471         Subclasses may override this method and implement template path
472         joining here.
473         """
474         return template
475
476     def get_template(self, name, parent=None, globals=None):
477         """Load a template from the loader.  If a loader is configured this
478         method ask the loader for the template and returns a :class:`Template`.
479         If the `parent` parameter is not `None`, :meth:`join_path` is called
480         to get the real template name before loading.
481
482         The `globals` parameter can be used to provide template wide globals.
483         These variables are available in the context at render time.
484
485         If the template does not exist a :exc:`TemplateNotFound` exception is
486         raised.
487         """
488         if self.loader is None:
489             raise TypeError('no loader for this environment specified')
490         if parent is not None:
491             name = self.join_path(name, parent)
492
493         if self.cache is not None:
494             template = self.cache.get(name)
495             if template is not None and (not self.auto_reload or \
496                                          template.is_up_to_date):
497                 return template
498
499         template = self.loader.load(self, name, self.make_globals(globals))
500         if self.cache is not None:
501             self.cache[name] = template
502         return template
503
504     def from_string(self, source, globals=None, template_class=None):
505         """Load a template from a string.  This parses the source given and
506         returns a :class:`Template` object.
507         """
508         globals = self.make_globals(globals)
509         cls = template_class or self.template_class
510         return cls.from_code(self, self.compile(source), globals, None)
511
512     def make_globals(self, d):
513         """Return a dict for the globals."""
514         if not d:
515             return self.globals
516         return dict(self.globals, **d)
517
518
519 class Template(object):
520     """The central template object.  This class represents a compiled template
521     and is used to evaluate it.
522
523     Normally the template object is generated from an :class:`Environment` but
524     it also has a constructor that makes it possible to create a template
525     instance directly using the constructor.  It takes the same arguments as
526     the environment constructor but it's not possible to specify a loader.
527
528     Every template object has a few methods and members that are guaranteed
529     to exist.  However it's important that a template object should be
530     considered immutable.  Modifications on the object are not supported.
531
532     Template objects created from the constructor rather than an environment
533     do have an `environment` attribute that points to a temporary environment
534     that is probably shared with other templates created with the constructor
535     and compatible settings.
536
537     >>> template = Template('Hello {{ name }}!')
538     >>> template.render(name='John Doe')
539     u'Hello John Doe!'
540
541     >>> stream = template.stream(name='John Doe')
542     >>> stream.next()
543     u'Hello John Doe!'
544     >>> stream.next()
545     Traceback (most recent call last):
546         ...
547     StopIteration
548     """
549
550     def __new__(cls, source,
551                 block_start_string=BLOCK_START_STRING,
552                 block_end_string=BLOCK_END_STRING,
553                 variable_start_string=VARIABLE_START_STRING,
554                 variable_end_string=VARIABLE_END_STRING,
555                 comment_start_string=COMMENT_START_STRING,
556                 comment_end_string=COMMENT_END_STRING,
557                 line_statement_prefix=LINE_STATEMENT_PREFIX,
558                 trim_blocks=TRIM_BLOCKS,
559                 newline_sequence=NEWLINE_SEQUENCE,
560                 extensions=(),
561                 optimized=True,
562                 undefined=Undefined,
563                 finalize=None,
564                 autoescape=False):
565         env = get_spontaneous_environment(
566             block_start_string, block_end_string, variable_start_string,
567             variable_end_string, comment_start_string, comment_end_string,
568             line_statement_prefix, trim_blocks, newline_sequence,
569             frozenset(extensions), optimized, undefined, finalize,
570             autoescape, None, 0, False, None)
571         return env.from_string(source, template_class=cls)
572
573     @classmethod
574     def from_code(cls, environment, code, globals, uptodate=None):
575         """Creates a template object from compiled code and the globals.  This
576         is used by the loaders and environment to create a template object.
577         """
578         t = object.__new__(cls)
579         namespace = {
580             'environment':          environment,
581             '__jinja_template__':   t
582         }
583         exec code in namespace
584         t.environment = environment
585         t.globals = globals
586         t.name = namespace['name']
587         t.filename = code.co_filename
588         t.blocks = namespace['blocks']
589
590         # render function and module
591         t.root_render_func = namespace['root']
592         t._module = None
593
594         # debug and loader helpers
595         t._debug_info = namespace['debug_info']
596         t._uptodate = uptodate
597
598         return t
599
600     def render(self, *args, **kwargs):
601         """This method accepts the same arguments as the `dict` constructor:
602         A dict, a dict subclass or some keyword arguments.  If no arguments
603         are given the context will be empty.  These two calls do the same::
604
605             template.render(knights='that say nih')
606             template.render({'knights': 'that say nih'})
607
608         This will return the rendered template as unicode string.
609         """
610         vars = dict(*args, **kwargs)
611         try:
612             return concat(self.root_render_func(self.new_context(vars)))
613         except:
614             from jinja2.debug import translate_exception
615             exc_type, exc_value, tb = translate_exception(sys.exc_info())
616             raise exc_type, exc_value, tb
617
618     def stream(self, *args, **kwargs):
619         """Works exactly like :meth:`generate` but returns a
620         :class:`TemplateStream`.
621         """
622         return TemplateStream(self.generate(*args, **kwargs))
623
624     def generate(self, *args, **kwargs):
625         """For very large templates it can be useful to not render the whole
626         template at once but evaluate each statement after another and yield
627         piece for piece.  This method basically does exactly that and returns
628         a generator that yields one item after another as unicode strings.
629
630         It accepts the same arguments as :meth:`render`.
631         """
632         vars = dict(*args, **kwargs)
633         try:
634             for event in self.root_render_func(self.new_context(vars)):
635                 yield event
636         except:
637             from jinja2.debug import translate_exception
638             exc_type, exc_value, tb = translate_exception(sys.exc_info())
639             raise exc_type, exc_value, tb
640
641     def new_context(self, vars=None, shared=False, locals=None):
642         """Create a new :class:`Context` for this template.  The vars
643         provided will be passed to the template.  Per default the globals
644         are added to the context.  If shared is set to `True` the data
645         is passed as it to the context without adding the globals.
646
647         `locals` can be a dict of local variables for internal usage.
648         """
649         if vars is None:
650             vars = {}
651         if shared:
652             parent = vars
653         else:
654             parent = dict(self.globals, **vars)
655         if locals:
656             # if the parent is shared a copy should be created because
657             # we don't want to modify the dict passed
658             if shared:
659                 parent = dict(parent)
660             for key, value in locals.iteritems():
661                 if key[:2] == 'l_' and value is not missing:
662                     parent[key[2:]] = value
663         return Context(self.environment, parent, self.name, self.blocks)
664
665     def make_module(self, vars=None, shared=False, locals=None):
666         """This method works like the :attr:`module` attribute when called
667         without arguments but it will evaluate the template every call
668         rather then caching the template.  It's also possible to provide
669         a dict which is then used as context.  The arguments are the same
670         as for the :meth:`new_context` method.
671         """
672         return TemplateModule(self, self.new_context(vars, shared, locals))
673
674     @property
675     def module(self):
676         """The template as module.  This is used for imports in the
677         template runtime but is also useful if one wants to access
678         exported template variables from the Python layer:
679
680         >>> t = Template('{% macro foo() %}42{% endmacro %}23')
681         >>> unicode(t.module)
682         u'23'
683         >>> t.module.foo()
684         u'42'
685         """
686         if self._module is not None:
687             return self._module
688         self._module = rv = self.make_module()
689         return rv
690
691     def get_corresponding_lineno(self, lineno):
692         """Return the source line number of a line number in the
693         generated bytecode as they are not in sync.
694         """
695         for template_line, code_line in reversed(self.debug_info):
696             if code_line <= lineno:
697                 return template_line
698         return 1
699
700     @property
701     def is_up_to_date(self):
702         """If this variable is `False` there is a newer version available."""
703         if self._uptodate is None:
704             return True
705         return self._uptodate()
706
707     @property
708     def debug_info(self):
709         """The debug info mapping."""
710         return [tuple(map(int, x.split('='))) for x in
711                 self._debug_info.split('&')]
712
713     def __repr__(self):
714         if self.name is None:
715             name = 'memory:%x' % id(self)
716         else:
717             name = repr(self.name)
718         return '<%s %s>' % (self.__class__.__name__, name)
719
720
721 class TemplateModule(object):
722     """Represents an imported template.  All the exported names of the
723     template are available as attributes on this object.  Additionally
724     converting it into an unicode- or bytestrings renders the contents.
725     """
726
727     def __init__(self, template, context):
728         self._body_stream = list(template.root_render_func(context))
729         self.__dict__.update(context.get_exported())
730         self.__name__ = template.name
731
732     __unicode__ = lambda x: concat(x._body_stream)
733     __html__ = lambda x: Markup(concat(x._body_stream))
734
735     def __str__(self):
736         return unicode(self).encode('utf-8')
737
738     def __repr__(self):
739         if self.__name__ is None:
740             name = 'memory:%x' % id(self)
741         else:
742             name = repr(self.__name__)
743         return '<%s %s>' % (self.__class__.__name__, name)
744
745
746 class TemplateExpression(object):
747     """The :meth:`jinja2.Environment.compile_expression` method returns an
748     instance of this object.  It encapsulates the expression-like access
749     to the template with an expression it wraps.
750     """
751
752     def __init__(self, template, undefined_to_none):
753         self._template = template
754         self._undefined_to_none = undefined_to_none
755
756     def __call__(self, *args, **kwargs):
757         context = self._template.new_context(dict(*args, **kwargs))
758         consume(self._template.root_render_func(context))
759         rv = context.vars['result']
760         if self._undefined_to_none and isinstance(rv, Undefined):
761             rv = None
762         return rv
763
764
765 class TemplateStream(object):
766     """A template stream works pretty much like an ordinary python generator
767     but it can buffer multiple items to reduce the number of total iterations.
768     Per default the output is unbuffered which means that for every unbuffered
769     instruction in the template one unicode string is yielded.
770
771     If buffering is enabled with a buffer size of 5, five items are combined
772     into a new unicode string.  This is mainly useful if you are streaming
773     big templates to a client via WSGI which flushes after each iteration.
774     """
775
776     def __init__(self, gen):
777         self._gen = gen
778         self.disable_buffering()
779
780     def dump(self, fp, encoding=None, errors='strict'):
781         """Dump the complete stream into a file or file-like object.
782         Per default unicode strings are written, if you want to encode
783         before writing specifiy an `encoding`.
784
785         Example usage::
786
787             Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
788         """
789         close = False
790         if isinstance(fp, basestring):
791             fp = file(fp, 'w')
792             close = True
793         try:
794             if encoding is not None:
795                 iterable = (x.encode(encoding, errors) for x in self)
796             else:
797                 iterable = self
798             if hasattr(fp, 'writelines'):
799                 fp.writelines(iterable)
800             else:
801                 for item in iterable:
802                     fp.write(item)
803         finally:
804             if close:
805                 fp.close()
806
807     def disable_buffering(self):
808         """Disable the output buffering."""
809         self._next = self._gen.next
810         self.buffered = False
811
812     def enable_buffering(self, size=5):
813         """Enable buffering.  Buffer `size` items before yielding them."""
814         if size <= 1:
815             raise ValueError('buffer size too small')
816
817         def generator(next):
818             buf = []
819             c_size = 0
820             push = buf.append
821
822             while 1:
823                 try:
824                     while c_size < size:
825                         c = next()
826                         push(c)
827                         if c:
828                             c_size += 1
829                 except StopIteration:
830                     if not c_size:
831                         return
832                 yield concat(buf)
833                 del buf[:]
834                 c_size = 0
835
836         self.buffered = True
837         self._next = generator(self._gen.next).next
838
839     def __iter__(self):
840         return self
841
842     def next(self):
843         return self._next()
844
845
846 # hook in default template class.  if anyone reads this comment: ignore that
847 # it's possible to use custom templates ;-)
848 Environment.template_class = Template