[svn] merged newparser into trunk
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent 630dfb7 · Browse files · 33 files·+2946 added−1307 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
33 files+2946 added−1307 removed
- tests:+209 added−26 removed
- other:+2737 added−1281 removed
Provenance
- Commit
1cc232c- Tree
1032c22- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
630dfb7
33 files changed+2946 added−1307 removed
modified:docs/src/builtins.txt+19 added-3 removed
25 unmodified lines26 [[list_of_filters]]27 28 .. admonition:: note29 30- The filter operator has a pretty low priority. If you want to add fitered31- values you have to put them into parentheses. The same applies if you want32- to access attributes or return values:30+ *Jinja 1.0 and 1.1 notice*31 32+ The filter operator has a pretty low priority in Jinja 1.0 and 1.1. If you33+ want to add fitered values you have to put them into parentheses. The same34+ applies if you want to access attributes or return values:35+36 .. sourcecode:: jinja37 38 correct:39 {{ (foo|filter) + (bar|filter) }}4 unmodified lines44 {{ (foo|filter).attribute }}45 wrong:46 {{ foo|filter.attribute }}47 48+ This changed in Jinja 1.2, from that version one the filter operator has49+ the highest priority so you can do ``foo|filter + bar|filter``.50+51 *new in Jinja 1.1*:52 53 Because the application can provide additional filters you can get a documentation54 of all the provided filters by calling ``debug.filters()``:33 unmodified lines88 89 {{ debug.tests(False) }}90 -> same as above but without the builtin ones.91 92+*new in Jinja 1.2*:93 94+If a test function expects one or no argument you can leave out the parentheses.95+Previously this was only possible for text functions without arguments:96+97+.. sourcecode:: jinja98+99+ {{ foo is matching @/\s+/ }}100+ is the same as101+ {{ foo is matching(@/\s+/) }}102+103+104 Global Functions105 ================106 107 Test functions and filter functions live in their own namespace. Global121 unmodified linesmodified:docs/src/designerdoc.txt+28 added-8 removed
192 unmodified lines193 you don't have to create such complex constructs in the template code. However194 in some situations it might be a good thing to have the abilities to create195 them.196 197+Literals198+========199+200+For most of the builtin python types, literals exist in Jinja. The following201+table shows which syntax elements are supported:202+203+ ======================= ===================================================204+ ``"text" / 'text'`` work like python's unicode literals (u'text').205+ ``42`` integer literls.206+ ``42.0`` float literals (exponents are not supported and207+ before and after the dot digits must be present)208+ ``[1, 'two', none]`` list literal209+ ``(), (1,), (1, 2)`` tuple literals. (tuples work like lists but consume210+ less memory and are not modifyable.)211+ ``{'foo': 'bar'}`` dictionary literal212+ ``@/expr/flags`` regular expression literals. ``@/expr/flags`` is213+ equivalent to ``re.compile('(?flags)expr')`` in214+ python.215+ ``@(1, 2, 3)`` set literal. ``@(1, 2, 3)`` in Jinja is is equal to216+ ``set([1, 2, 3])`` in python.217+ ``true / false`` corresponds to `True` and `False` in python.218+ ``none`` corresponds to `None` in python.219+ ``undefined`` special Jinja undefined singleton.220+ ======================= ===================================================221+222 Operators223 =========224 225 Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can89 unmodified lines315 .. sourcecode:: html+jinja316 317 {% macro show_user user %}318 <h1>{{ user.name|e }}</h1>294- <div class="test">319+ <div class="text">320 {{ user.description }}321 </div>322 {% endmacro %}323 11 unmodified lines335 336 {% macro show_dialog title, text %}337 <div class="dialog">338 <h1>{{ title|e }}</h1>314- <div class="test">{{ text|e }}</div>339+ <div class="text">{{ text|e }}</div>340 </div>341 {% endmacro %}342 343 {{ show_dialog('Warning', 'something went wrong i guess') }}171 unmodified lines515 516 `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`,517 `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`,518 `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`,494- `print`, `raw`, `recursive`, `set`, `trans`, `call` +, `endcall` +519+ `print`, `raw`, `recursive`, `set`, `trans`, `call`, `endcall`520 496-keywords marked with a plus sign can be used until Jinja 1.3 as497-identifiers because they were introduced after the Jinja 1.0 release and498-can cause backwards compatiblity problems otherwise. You should not use499-them any more.500-521 If you want to use such a name you have to prefix or suffix it or use522 alternative names:523 524 .. sourcecode:: jinja9 unmodified linesmodified:docs/src/scopes.txt+23 added
157 unmodified lines158 comes with Jinja is the `ComplainingUndefined` object.159 160 It raises exceptions as soon as you either render it or want to iterate161 over it or try to access attributes etc.162+163+164+Overriding Variables Of Outer Scopes165+====================================166+167+*New in Jinja 1.2*168+169+Normally you cannot override a variable from an outer scope, you can just hide170+it. There is however a way to override a variable from an outer scope using the171+`set` tag, postfixed with a bang (!):172+173+.. source:: jinja174+175+ {% set last_item = none %}176+ {% for item in seq %}177+ {% set last_item = item! %}178+ {% endfor %}179+180+After the iteration `last_item` will point to the item of the last iteration.181+182+If `last_item` was not defined in the outer scope it wouldn't exist now because183+in that situation `set`, even with a postfixed bang just behaves like setting a184+scope variable.added:jinja/contrib/__init__.py+11 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.contrib4+ ~~~~~~~~~~~~~5+6+ This module collections various third-party helper functions and classes7+ that are useful for frameworks etc.8+9+ :copyright: 2007 by Armin Ronacher.10+ :license: BSD, see LICENSE for more details.11+"""added:jinja/contrib/_djangosupport.py+208 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.contrib._djangosupport4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Django suport layer. This module is a metamodule, do never import it7+ directly or access any of the functions defined here.8+9+ The public interface is `jinja.contrib.djangosupport` and10+ `django.contrib.jinja`. See the docstring of `jinja.contrib.djangosupport`11+ for more details.12+13+ :copyright: 2007 by Armin Ronacher, Bryan McLemore.14+ :license: BSD, see LICENSE for more details.15+"""16+import sys17+import new18+from django.conf import settings19+from django.template.context import get_standard_processors20+from django.http import HttpResponse21+from django import contrib22+23+from jinja import Environment, FileSystemLoader, ChoiceLoader24+from jinja.loaders import MemcachedFileSystemLoader25+26+27+exported = ['render_to_response', 'render_to_string', 'convert_django_filter']28+29+30+#: used environment31+env = None32+33+34+#: default filters35+DEFAULT_FILTERS = [36+ 'django.template.defaultfilters.date',37+ 'django.template.defaultfilters.timesince',38+ 'django.template.defaultfilters.linebreaks',39+ 'django.contrib.humanize.templatetags.humanize.intcomma'40+]41+42+43+def configure(convert_filters=DEFAULT_FILTERS, loader=None, **options):44+ """45+ Initialize the system.46+ """47+ global env48+49+ if env is not None:50+ raise RuntimeError('jinja already configured')51+52+ # setup environment53+ if loader is None:54+ loaders = [FileSystemLoader(l) for l in settings.TEMPLATE_DIRS]55+ if not loaders:56+ loader = None57+ elif len(loaders) == 1:58+ loader = loaders[0]59+ else:60+ loader = ChoiceLoader(loaders)61+ env = Environment(loader=loader, **options)62+63+ # convert requested filters64+ for name in convert_filters:65+ env.filters[name] = convert_django_filter(name)66+67+ # import templatetags of installed apps68+ for app in settings.INSTALLED_APPS:69+ try:70+ __import__(app + '.templatetags')71+ except ImportError:72+ pass73+74+ # setup the django.contrib.jinja module75+ setup_django_module()76+77+78+def setup_django_module():79+ """80+ create a new Jinja module for django.81+ """82+ from jinja.contrib import djangosupport83+ module = contrib.jinja = sys.modules['django.contrib.jinja'] = \84+ new.module('django.contrib.jinja')85+ module.env = env86+ module.__doc__ = djangosupport.__doc__87+ module.register = Library()88+ public_names = module.__all__ = ['register', 'env']89+ get_name = globals().get90+ for name in exported:91+ setattr(module, name, get_name(name))92+ public_names.append(name)93+94+95+def render_to_response(template, context={}, request=None,96+ mimetype=None):97+ """This function will take a few variables and spit out a full webpage."""98+ content = render_to_string(template, context, request)99+ if mimetype is None:100+ mimetype = settings.DEFUALT_CONTENT_TYPE101+ return HttpResponse(content, content_type)102+103+104+def render_to_string(template, context={}, request=None):105+ """Render a template to a string."""106+ assert env is not None, 'Jinja not configured for django'107+ if request is not None:108+ context['request'] = request109+ for processor in get_standard_processors():110+ context.update(processor(request))111+ template = env.get_template(template)112+ return template.render(context)113+114+115+def convert_django_filter(f):116+ """Convert a django filter into a Jinja filter."""117+ if isinstance(f, str):118+ p = f.split('.')119+ f = getattr(__import__('.'.join(p[:-1]), None, None, ['']), p[-1])120+ def filter_factory(*args):121+ def wrapped(env, ctx, value):122+ return f(value, *args)123+ return wrapped124+ try:125+ filter_factory.__name__ = f.__name__126+ filter_factory.__doc__ = f.__doc__127+ except:128+ pass129+ return filter_factory130+131+132+class Library(object):133+ """134+ Continues a general feel of wrapping all the registration135+ methods for easy importing.136+137+ This is available in `django.contrib.jinja` as `register`.138+139+ For more details see the docstring of the `django.contrib.jinja` module.140+ """141+ __slots__ = ()142+143+ def object(obj, name=None):144+ """Register a new global."""145+ if name is None:146+ name = getattr(obj, '__name__')147+ env.globals[name] = obj148+ return func149+150+ def filter(func, name=None):151+ """Register a new filter function."""152+ if name is None:153+ name = func.__name__154+ env.filters[name] = func155+ return func156+157+ def test(func, name):158+ """Register a new test function."""159+ if name is None:160+ name = func.__name__161+ env.tests[name] = func162+ return func163+164+ def context_inclusion(func, template, name=None):165+ """166+ Similar to the inclusion tag from django this one expects func to be a167+ function with a similar argument list to func(context, *args, **kwargs)168+169+ It passed in the current context allowing the function to edit it or read170+ from it. the function must return a dict with which to pass into the171+ renderer. Normally expected is an altered dictionary.172+173+ Note processors are NOT ran on this context.174+ """175+ def wrapper(env, context, *args, **kwargs):176+ context = func(context.to_dict(), *args, **kwargs)177+ return render_to_string(template, context)178+ wrapper.jinja_context_callable = True179+ if name is None:180+ name = func.__name__181+ try:182+ wrapper.__name__ = func.__name__183+ wrapper.__doc__ = func.__doc__184+ except:185+ pass186+ env.globals[name] = wrapper187+188+ def clean_inclusion(func, template, name=None, run_processors=False):189+ """190+ Similar to above however it won't pass the context into func().191+ Also the returned context will have the context processors run upon it.192+ """193+ def wrapper(env, context, *args, **kwargs):194+ if run_processors:195+ request = context['request']196+ else:197+ request = None198+ context = func({}, *args, **kwargs)199+ return render_to_string(template, context, request)200+ wrapper.jinja_context_callable = True201+ if name is None:202+ name = func.__name__203+ try:204+ wrapper.__name__ = func.__name__205+ wrapper.__doc__ = func.__doc__206+ except:207+ pass208+ env.globals[name] = wrapperadded:jinja/contrib/djangosupport.py+124 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.contrib.djangosupport4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Support for the django framework. This module is quite magical because it7+ just exports one single function, the `configure` function which is used8+ to create a new Jinja environment and setup a special module called9+ `django.contrib.jinja` which exports a couple of functions useful for Jinja.10+11+ Quickstart12+ ==========13+14+ To get started execute the following code at the bottom of your settings.py15+ or in some general application file such as urls.py or a central module. The16+ only thing that matters is that it's executed right *after* the settings17+ were set up and *before* `django.contrib.jinja` is imported::18+19+ from jinja.contrib import djangosupport20+ djangosupport.configure()21+22+ What this does is setting up a Jinja environment for this django instance23+ with loaders for `TEMPLATE_DIRS` etc. It also converts a couple of default24+ django filters such as `date` and `timesince` which are not available in25+ Jinja per default. If you want to change the list you can provide others26+ by passing a list with filter import names as `convert_filters` keyword27+ argument.28+29+ All other keyword arguments are forwarded to the environment. If you want30+ to provide a loader yourself pass it a loader keyword argument.31+32+ Rendering Templates33+ ===================34+35+ To render a template you can use the functions `render_to_string` or36+ `render_to_response` from the `django.contrib.jinja` module::37+38+ from django.contrib.jinja import render_to_response39+ resp = render_to_response('Hello {{ username }}!', {40+ 'username': req.session['username']41+ }, req)42+43+ `render_to_string` and `render_to_response` take at least the name of44+ the template as argument, then the optional dict which will become the45+ context. If you also provide a request object as third argument the46+ context processors will be applied.47+48+ `render_to_response` also takes a forth parameter which can be the49+ content type which defaults to `DEFAULT_CONTENT_TYPE`.50+51+ Converting Filters52+ ==================53+54+ One of the useful objects provided by `django.contrib.jinja` is the55+ `register` object which can be used to register filters, tests and56+ global objects. You can also convert any filter django provides in57+ a Jinja filter using `convert_django_filter`::58+59+ from django.contrib.jinja import register, convert_django_filter60+ from django.template.defaultfilters import floatformat61+62+ register.filter(convert_django_filter(floatformat), 'floatformat')63+64+ Available methods on the `register` object:65+66+ ``object (obj[, name])``67+ Register a new global as name or with the object's name.68+ Returns the function object unchanged so that you can use69+ it as decorator if no name is provided.70+71+ ``filter (func[, name])``72+ Register a function as filter with the name provided or73+ the object's name as filtername.74+ Returns the function object unchanged so that you can use75+ it as decorator if no name is provided.76+77+ ``test (func[, name])``78+ Register a function as test with the name provided or the79+ object's name as testname.80+ Returns the function object unchanged so that you can use81+ it as decorator if no name is provided.82+83+ ``context_inclusion (func, template[, name])``84+ Register a function with a name provided or the func object's85+ name in the global namespace that acts as subrender function.86+87+ func is called with the callers context as dict and the88+ arguments and keywords argument of the inclusion function.89+ The function should then process the context and return a90+ new context or the same context object. Afterwards the91+ template is rendered with this context.92+93+ Example::94+95+ def add_author(context, author=None):96+ if author is not None:97+ author = Author.objects.get(name=author)98+ context['author'] = author99+ return context100+101+ register.context_inclusion(add_author, 'author_details.html',102+ 'render_author_details')103+104+ You can use it in the template like this then::105+106+ {{ render_author_details('John Doe') }}107+108+ ``clean_inclusion (func, template[, name[, run_processors]]) ``109+ Works like `context_inclusion` but doesn't use the calles110+ context but an empty context. If `run_processors` is `True`111+ it will lookup the context for a `request` object and pass112+ it to the render function to apply context processors.113+114+ :copyright: 2007 by Armin Ronacher, Bryan McLemore.115+ :license: BSD, see LICENSE for more details.116+"""117+try:118+ __import__('django')119+except ImportError:120+ raise ImportError('installed django required for djangosupport')121+else:122+ from jinja.contrib._djangosupport import configure123+124+__all__ = ['configure']modified:jinja/translators/__init__.py+1 added-1 removed
13 unmodified lines14 """15 Base class of all translators.16 """17 18- def process(environment, tree):18+ def process(environment, tree, source=None):19 """20 Process the given ast with the rules defined in21 environment and return a translated version of it.22 The translated object can be anything. The python7 unmodified linesmodified:jinja/translators/python.py+276 added-320 removed
17 unmodified lines18 19 Implementation Details20 ======================21 22- Some of the semantics are handled directly in the translator in order23- to speed up the parsing process. For example the semantics for the24- `is` operator are handled here, changing this would require and25- additional traversing of the node tree in the parser. Thus the actual26- translation process can raise a `TemplateSyntaxError` too.27-22 It might sound strange but the translator tries to keep the generated23 code readable as much as possible. This simplifies debugging the Jinja24 core a lot. The additional processing overhead is just relevant for25 the translation process, the additional comments and whitespace won't3 unmodified lines29 :license: BSD, see LICENSE for more details.30 """31 import re32 import sys39-from compiler import ast33 from jinja import nodes34 from jinja.nodes import get_nodes35 from jinja.parser import Parser36 from jinja.exceptions import TemplateSyntaxError29 unmodified lines66 def __init__(self, environment, code):67 self.environment = environment68 self.code = code69 self.generate_func = None77- #: holds debug information78- self._debug_info = None79- #: unused in loader environments but used when a template80- #: is loaded from a string in order to be able to debug those too81- self._source = None70 71 def dump(self, stream=None):72 """Dump the template into python bytecode."""73 if stream is not None:15 unmodified lines89 load = staticmethod(load)90 91 def render(self, *args, **kwargs):92 """Render a template."""93+ __traceback_hide__ = True94 ctx = self._prepare(*args, **kwargs)95 try:96 return capture_generator(self.generate_func(ctx))97 except:20 unmodified lines118 if self.generate_func is None:119 ns = {'environment': env}120 exec self.code in ns121 self.generate_func = ns['generate']133- self._debug_info = ns['debug_info']122 return env.context_class(env, *args, **kwargs)123 124 def _debug(self, ctx, exc_type, exc_value, traceback):125 """Debugging Helper"""15 unmodified lines141 """142 Pass this translator a ast tree to get valid python code.143 """144 157- def __init__(self, environment, node):145+ def __init__(self, environment, node, source):146 self.environment = environment147 self.node = node148+ self.source = source149+ self.closed = False150 161- #: mapping to constants in the environment that are not162- #: converted to context lookups. this should improve163- #: performance and avoid accidentally screwing things up164- #: by rebinding essential constants.165- self.constants = {166- 'true': 'True',167- 'false': 'False',168- 'none': 'None',169- 'undefined': 'undefined_singleton'170- }151+ #: current level of indention152+ self.indention = 0153+ #: each {% cycle %} tag has a unique ID which increments154+ #: automatically for each tag.155+ self.last_cycle_id = 0156+ #: set of used shortcuts jinja has to make local automatically157+ self.used_shortcuts = set(['undefined_singleton'])158+ #: set of used datastructures jinja has to import159+ self.used_data_structures = set()160+ #: set of used utils jinja has to import161+ self.used_utils = set()162+ #: flags for runtime error163+ self.require_runtime_error = False164+ #: do wee need a "set" object?165+ self.need_set_import = False166+ #: flag for regular expressions167+ self.compiled_regular_expressions = {}168 169 #: bind the nodes to the callback functions. There are170 #: some missing! A few are specified in the `unhandled`171 #: mapping in order to disallow their usage, some of them172 #: will not appear in the jinja parser output because173 #: they are filtered out.174 self.handlers = {178- # jinja nodes179- nodes.Template: self.handle_template,180- nodes.Text: self.handle_template_text,181- nodes.DynamicText: self.handle_dynamic_text,182- nodes.NodeList: self.handle_node_list,183- nodes.ForLoop: self.handle_for_loop,184- nodes.IfCondition: self.handle_if_condition,185- nodes.Cycle: self.handle_cycle,186- nodes.Print: self.handle_print,187- nodes.Macro: self.handle_macro,188- nodes.Call: self.handle_call,189- nodes.Set: self.handle_set,190- nodes.Filter: self.handle_filter,191- nodes.Block: self.handle_block,192- nodes.Include: self.handle_include,193- nodes.Trans: self.handle_trans,194- # python nodes195- ast.Name: self.handle_name,196- ast.AssName: self.handle_assign_name,197- ast.Compare: self.handle_compare,198- ast.Const: self.handle_const,199- ast.Subscript: self.handle_subscript,200- ast.Getattr: self.handle_getattr,201- ast.AssTuple: self.handle_ass_tuple,202- ast.Bitor: self.handle_bitor,203- ast.CallFunc: self.handle_call_func,204- ast.Add: self.handle_add,205- ast.Sub: self.handle_sub,206- ast.Div: self.handle_div,207- ast.FloorDiv: self.handle_floor_div,208- ast.Mul: self.handle_mul,209- ast.Mod: self.handle_mod,210- ast.UnaryAdd: self.handle_unary_add,211- ast.UnarySub: self.handle_unary_sub,212- ast.Power: self.handle_power,213- ast.Dict: self.handle_dict,214- ast.List: self.handle_list,215- ast.Tuple: self.handle_list,216- ast.And: self.handle_and,217- ast.Or: self.handle_or,218- ast.Not: self.handle_not,219- ast.Slice: self.handle_slice,220- ast.Sliceobj: self.handle_sliceobj175+ # block nodes176+ nodes.Template: self.handle_template,177+ nodes.Text: self.handle_template_text,178+ nodes.NodeList: self.handle_node_list,179+ nodes.ForLoop: self.handle_for_loop,180+ nodes.IfCondition: self.handle_if_condition,181+ nodes.Cycle: self.handle_cycle,182+ nodes.Print: self.handle_print,183+ nodes.Macro: self.handle_macro,184+ nodes.Call: self.handle_call,185+ nodes.Set: self.handle_set,186+ nodes.Filter: self.handle_filter,187+ nodes.Block: self.handle_block,188+ nodes.Include: self.handle_include,189+ nodes.Trans: self.handle_trans,190+191+ # expression nodes192+ nodes.NameExpression: self.handle_name,193+ nodes.CompareExpression: self.handle_compare,194+ nodes.TestExpression: self.handle_test,195+ nodes.ConstantExpression: self.handle_const,196+ nodes.RegexExpression: self.handle_regex,197+ nodes.SubscriptExpression: self.handle_subscript,198+ nodes.FilterExpression: self.handle_filter_expr,199+ nodes.CallExpression: self.handle_call_expr,200+ nodes.AddExpression: self.handle_add,201+ nodes.SubExpression: self.handle_sub,202+ nodes.ConcatExpression: self.handle_concat,203+ nodes.DivExpression: self.handle_div,204+ nodes.FloorDivExpression: self.handle_floor_div,205+ nodes.MulExpression: self.handle_mul,206+ nodes.ModExpression: self.handle_mod,207+ nodes.PosExpression: self.handle_pos,208+ nodes.NegExpression: self.handle_neg,209+ nodes.PowExpression: self.handle_pow,210+ nodes.DictExpression: self.handle_dict,211+ nodes.SetExpression: self.handle_set_expr,212+ nodes.ListExpression: self.handle_list,213+ nodes.TupleExpression: self.handle_tuple,214+ nodes.UndefinedExpression: self.handle_undefined,215+ nodes.AndExpression: self.handle_and,216+ nodes.OrExpression: self.handle_or,217+ nodes.NotExpression: self.handle_not,218+ nodes.SliceExpression: self.handle_slice,219+ nodes.ConditionalExpression: self.handle_conditional_expr220 }221 223- #: mapping of unsupported syntax elements.224- #: the value represents the feature name that appears225- #: in the exception.226- self.unsupported = {ast.ListComp: 'list comprehension'}227-228- #: because of python2.3 compatibility add generator229- #: expressions only to the list of unused features230- #: if it exists.231- if hasattr(ast, 'GenExpr'):232- self.unsupported[ast.GenExpr] = 'generator expression'233-234- #: if expressions are unsupported too (so far)235- if hasattr(ast, 'IfExp'):236- self.unsupported[ast.IfExp] = 'inline if expression'237-222 # -- public methods223 240- def process(environment, node):224+ def process(environment, node, source=None):225 """226 The only public method. Creates a translator instance,227 translates the code and returns it in form of an228 `Template` instance.229 """246- translator = PythonTranslator(environment, node)230+ translator = PythonTranslator(environment, node, source)231 filename = node.filename or '<template>'232 source = translator.translate()233 return Template(environment, compile(source, filename, 'exec'))234 process = staticmethod(process)25 unmodified lines260 node.filename or '',261 node.lineno262 )263 280- def filter(self, s, filter_nodes):281- """282- Apply a filter on an object that already is a python expression.283- Used to avoid redundant code in bitor and the filter directive.284- """285- filters = []286- for n in filter_nodes:287- if n.__class__ is ast.CallFunc:288- if n.node.__class__ is not ast.Name:289- raise TemplateSyntaxError('invalid filter. filter must '290- 'be a hardcoded function name '291- 'from the filter namespace',292- n.lineno,293- n.filename)294- args = []295- for arg in n.args:296- if arg.__class__ is ast.Keyword:297- raise TemplateSyntaxError('keyword arguments for '298- 'filters are not supported.',299- n.lineno,300- n.filename)301- args.append(self.handle_node(arg))302- if n.star_args is not None or n.dstar_args is not None:303- raise TemplateSyntaxError('*args / **kwargs is not supported '304- 'for filters', n.lineno,305- n.filename)306- filters.append('(%r, %s)' % (307- n.node.name,308- self.to_tuple(args)309- ))310- elif n.__class__ is ast.Name:311- filters.append('(%r, ())' % n.name)312- else:313- raise TemplateSyntaxError('invalid filter. filter must be a '314- 'hardcoded function name from the '315- 'filter namespace',316- n.lineno, n.filename)317- self.used_shortcuts.add('apply_filters')318- return 'apply_filters(%s, context, %s)' % (s, self.to_tuple(filters))319-264 def handle_node(self, node):265 """266 Handle one node. Resolves the correct callback functions defined323- in the callback mapping. This also raises the `TemplateSyntaxError`324- for unsupported syntax elements such as list comprehensions.267+ in the callback mapping.268 """269+ if self.closed:270+ raise RuntimeError('translator is closed')271 if node.__class__ in self.handlers:272 out = self.handlers[node.__class__](node)328- elif node.__class__ in self.unsupported:329- raise TemplateSyntaxError('unsupported syntax element %r found.'330- % self.unsupported[node.__class__],331- node.lineno, node.filename)273 else:274 raise AssertionError('unhandled node %r' % node.__class__)275 return out276 336- def reset(self):277+ def close(self):278 """338- Reset translation variables such as indention or cycle id279+ Clean up stuff.280 """340- #: current level of indention341- self.indention = 0342- #: each {% cycle %} tag has a unique ID which increments343- #: automatically for each tag.344- self.last_cycle_id = 0345- #: set of used shortcuts jinja has to make local automatically346- self.used_shortcuts = set(['undefined_singleton'])347- #: set of used datastructures jinja has to import348- self.used_data_structures = set()349- #: set of used utils jinja has to import350- self.used_utils = set()351- #: flags for runtime error352- self.require_runtime_error = False281+ self.closed = True282+ self.handlers = self.node = self.environment = None283 284 def translate(self):285 """356- Translate the node defined in the constructor after357- resetting the translator.286+ Translate the node defined in the constructor.287 """359- self.reset()360- return self.handle_node(self.node)288+ try:289+ return self.handle_node(self.node)290+ finally:291+ self.close()292 293 # -- jinja nodes294 295 def handle_template(self, node):25 unmodified lines321 # are processed as template globals, thus executed *before*322 # the master layout template is loaded. This can be used323 # for further processing. The output of those nodes does324 # not appear in the final template.394- requirements += [child for child in node.getChildNodes()325+ requirements += [child for child in node.get_child_nodes()326 if child.__class__ not in (nodes.Text,396- nodes.Block, nodes.Extends)]327+ nodes.Block)]328 329 # load the template we inherit from and add not known blocks399- parent = self.environment.loader.parse(node.extends.template,330+ parent = self.environment.loader.parse(node.extends,331 node.filename)332 # look up all block nodes in the current template and333 # add them to the override dict.334 for n in get_nodes(nodes.Block, node):2 unmodified lines337 for n in get_nodes(nodes.Block, parent):338 # an overwritten block for the parent template. handle that339 # override in the template and register it in the deferred340 # block dict.410- if n.name in overwrites and not n in already_registered_block:341+ if n.name in overwrites and n not in already_registered_block:342 blocks.setdefault(n.name, []).append(n.clone())343 n.replace(overwrites[n.name])344 already_registered_block.add(n)345 # make the parent node the new node6 unmodified lines352 requirement_lines.append(self.handle_node(n))353 requirement_lines.append(' if 0: yield None\n')354 355 # handle body in order to get the used shortcuts425- body_lines = [self.handle_node(n) for n in node]356+ body_code = self.handle_node(node.body)357 358 # same for blocks in callables359 block_lines = []360 block_items = blocks.items()34 unmodified lines395 lines.append('from jinja.exceptions import TemplateRuntimeError')396 if self.used_data_structures:397 lines.append('from jinja.datastructure import %s' % ', '.398 join(self.used_data_structures))399+ if self.need_set_import:400+ lines.append('from jinja.utils import set')401+402+ # compile regular expressions403+ if self.compiled_regular_expressions:404+ lines.append('import re')405+ lines.append('\n# Compile used regular expressions')406+ for regex, name in self.compiled_regular_expressions.iteritems():407+ lines.append('%s = re.compile(%r)' % (name, regex))408+409 lines.append(410 '\n# Aliases for some speedup\n'411 '%s\n\n'412+ '# Marker for Jinja templates\n'413+ '__jinja_template__ = True\n\n'414 '# Name for disabled debugging\n'415 '__name__ = %r\n\n'416 'def generate(context):\n'417 ' assert environment is context.environment' % (418 '\n'.join([419 '%s = environment.%s' % (item, item) for item in477- ['get_attribute', 'perform_test', 'apply_filters',478- 'call_function', 'call_function_simple', 'finish_var',479- 'undefined_singleton'] if item in self.used_shortcuts420+ self.used_shortcuts421 ]),422 outer_filename423 )424 )425 426 # the template body427 if requirements:428 lines.append(' for item in bootstrap(context): pass')488- lines.extend(body_lines)429+ lines.append(body_code)430 lines.append(' if 0: yield None\n')431 432 # now write the bootstrapping (requirements) core if there is one433 if requirements:42 unmodified lines476 else:477 result.append(line)478 479 # now print file mapping and debug info480+ # the debug info:481+ # debug_info binds template line numbers to generated482+ # source lines. this information is always483+ # present and part of the bytecode.484+ # template_source only available if loaded from string to485+ # get debug source code. Because this is486+ # dumped too it's a bad idea to dump templates487+ # loaded from a string.488 result.append('\n# Debug Information')489 file_mapping = file_mapping.items()490 file_mapping.sort(lambda a, b: cmp(a[1], b[1]))491 for filename, file_id in file_mapping:492 result.append('%s = %r' % (file_id, filename))493 result.append('debug_info = %s' % self.to_tuple(debug_mapping))494+ result.append('template_source = %r' % self.source)495 return '\n'.join(result)496 497 def handle_template_text(self, node):498 """499 Handle data around nodes.500 """501+ # special case: no variables502+ if not node.variables:551- return self.indent(self.nodeinfo(node)) + '\n' +\552- self.indent('yield %r' % node.text)503+ return self.indent(self.nodeinfo(node)) + '\n' + \504+ self.indent('yield %r' % node.text.replace('%%', '%'))505 554- def handle_dynamic_text(self, node):555- """556- Like `handle_template_text` but for nodes of the type557- `DynamicText`.558- """506+ # special case: one variable, no text507+ self.used_shortcuts.add('finish_var')508+ if len(node.variables) == 1 and node.text == '%s':509+ return self.indent(self.nodeinfo(node)) + '\n' + \510+ self.indent('yield finish_var(%s, context)' %511+ self.handle_node(node.variables[0]))512+513+ # all other cases514 buf = []515 write = lambda x: buf.append(self.indent(x))561- self.used_shortcuts.add('finish_var')516 517 write(self.nodeinfo(node))564- write('yield %r %% (' % node.format_string)518+ write('yield %r %% (' % node.text)519 self.indention += 1520 for var in node.variables:521 write(self.nodeinfo(var))568- write('finish_var(%s, context)' % self.handle_node(var.variable) + ',')522+ write('finish_var(%s, context)' % self.handle_node(var) + ',')523 self.indention -= 1524 write(')')525 526 return '\n'.join(buf)106 unmodified lines633 634 write('if %r not in context.current:' % name)635 self.indention += 1636 write(self.nodeinfo(node))683- if node.seq.__class__ in (ast.Tuple, ast.List):637+ if node.seq.__class__ in (nodes.TupleExpression,638+ nodes.ListExpression):639 write('context.current[%r] = CycleContext(%s)' % (640 name,686- self.to_tuple([self.handle_node(n) for n in node.seq.nodes])641+ self.to_tuple([self.handle_node(n) for n in node.seq.items])642 ))643 hardcoded = True644 else:645 write('context.current[%r] = CycleContext()' % name)19 unmodified lines665 """666 self.used_shortcuts.add('finish_var')667 return self.indent(self.nodeinfo(node)) + '\n' +\668 self.indent('yield finish_var(%s, context)' %714- self.handle_node(node.variable))669+ self.handle_node(node.expr))670 671 def handle_macro(self, node):672 """673 Handle macro declarations.674 """720- # sanity check for name721- if node.name == '_' or \722- node.name in self.constants:723- raise TemplateSyntaxError('cannot override %r' % node.name,724- node.lineno, node.filename)725- if node.name in self.constants:726- raise TemplateSyntaxError('you cannot name a macro %r',727- node.lineno,728- node.filename)729-675 buf = []676 write = lambda x: buf.append(self.indent(x))677 678 write('def macro(*args, **kw):')80 unmodified lines759 buf.append(data)760 write('context.pop()')761 write('if 0: yield None')762 self.indention -= 1818- write('yield ' + self.handle_call_func(node.expr,763+ write('yield ' + self.handle_call_expr(node.expr,764 {'caller': 'buffereater(call)'}))765 self.used_utils.add('buffereater')766 767 return '\n'.join(buf)1 unmodified line769 def handle_set(self, node):770 """771 Handle variable assignments.772 """828- if node.name == '_' or node.name in self.constants:829- raise TemplateSyntaxError('cannot override %r' % node.name,830- node.lineno, node.filename)773+ if node.scope_local:774+ tmpl = 'context[%r] = %s'775+ else:776+ tmpl = 'context.set_nonlocal(%r, %s)'777 return self.indent(self.nodeinfo(node)) + '\n' + \832- self.indent('context[%r] = %s' % (778+ self.indent(tmpl % (779 node.name,780 self.handle_node(node.expr)781 ))782 12 unmodified lines795 buf.append(data)796 write('context.pop()')797 write('if 0: yield None')798 self.indention -= 1853- write('yield %s' % self.filter('buffereater(filtered)()',854- node.filters))799+ self.used_shortcuts.add('apply_filters')800+ write('yield apply_filters(buffereater(filtered)(), context, %s)' %801+ self.to_tuple(['(%r, %s)' % (802+ name,803+ self.to_tuple(map(self.handle_node, args))804+ ) for name, args in node.filters])805+ )806 self.used_utils.add('buffereater')807 return '\n'.join(buf)808 809 def handle_block(self, node, level=0):25 unmodified lines835 Include another template at the current position.836 """837 tmpl = self.environment.loader.parse(node.template,838 node.filename)888- return self.handle_node_list(tmpl)839+ return self.handle_node(tmpl.body)840 841 def handle_trans(self, node):842 """843 Handle translations.17 unmodified lines861 ))862 863 # -- python nodes864 914- def handle_assign_name(self, node):915- """916- Handle name assignments.917- """918- if node.name == '_' or \919- node.name in self.constants:920- raise TemplateSyntaxError('cannot override %r' % node.name,921- node.lineno, node.filename)922- return 'context[%r]' % node.name923-865 def handle_name(self, node):866 """867 Handle name assignments and name retreivement.868 """928- if node.name in self.constants:929- return self.constants[node.name]930- elif node.name == '_':869+ if node.name == '_':870 return 'context.translate_func'871 return 'context[%r]' % node.name872 873 def handle_compare(self, node):874 """875 Any sort of comparison876 """938- # the semantic for the is operator is different.939- # for jinja the is operator performs tests and must940- # be the only operator941- if node.ops[0][0] in ('is', 'is not'):942- if len(node.ops) > 1:943- raise TemplateSyntaxError('is operator must not be chained',944- node.lineno,945- node.filename)946- elif node.ops[0][1].__class__ is ast.Name:947- args = []948- name = node.ops[0][1].name949- elif node.ops[0][1].__class__ is ast.CallFunc:950- n = node.ops[0][1]951- if n.node.__class__ is not ast.Name:952- raise TemplateSyntaxError('invalid test. test must '953- 'be a hardcoded function name '954- 'from the test namespace',955- n.lineno,956- n.filename)957- name = n.node.name958- args = []959- for arg in n.args:960- if arg.__class__ is ast.Keyword:961- raise TemplateSyntaxError('keyword arguments for '962- 'tests are not supported.',963- n.lineno,964- n.filename)965- args.append(self.handle_node(arg))966- if n.star_args is not None or n.dstar_args is not None:967- raise TemplateSyntaxError('*args / **kwargs is not supported '968- 'for tests', n.lineno,969- n.filename)970- else:971- raise TemplateSyntaxError('is operator requires a test name'972- ' as operand', node.lineno,973- node.filename)974- self.used_shortcuts.add('perform_test')975- return 'perform_test(context, %r, %s, %s, %s)' % (976- name,977- self.to_tuple(args),978- self.handle_node(node.expr),979- node.ops[0][0] == 'is not'980- )981-982- # normal operators877+ ops = {878+ 'eq': '==',879+ 'ne': '!=',880+ 'lt': '<',881+ 'lteq': '<=',882+ 'gt': '>',883+ 'gteq': '>=',884+ 'in': 'in',885+ 'not in': 'not in'886+ }887 buf = []888 buf.append(self.handle_node(node.expr))889 for op, n in node.ops:986- if op in ('is', 'is not'):987- raise TemplateSyntaxError('is operator must not be chained',988- node.lineno, node.filename)989- buf.append(op)890+ buf.append(ops[op])891 buf.append(self.handle_node(n))892 return ' '.join(buf)893 894+ def handle_test(self, node):895+ """896+ Handle test calls.897+ """898+ self.used_shortcuts.add('perform_test')899+ return 'perform_test(context, %r, %s, %s)' % (900+ node.name,901+ self.to_tuple([self.handle_node(n) for n in node.args]),902+ self.handle_node(node.node)903+ )904+905 def handle_const(self, node):906 """907 Constant values in expressions.908 """909 return repr(node.value)910 911+ def handle_regex(self, node):912+ """913+ Regular expression literals.914+ """915+ if self.environment.disable_regexps:916+ raise TemplateSyntaxError('regular expressions disabled.')917+ if node.value in self.compiled_regular_expressions:918+ return self.compiled_regular_expressions[node.value]919+ name = 'regex_%d' % len(self.compiled_regular_expressions)920+ self.compiled_regular_expressions[node.value] = name921+ return name922+923 def handle_subscript(self, node):924 """925 Handle variable based attribute access foo['bar'].926 """1003- if len(node.subs) != 1:1004- raise TemplateSyntaxError('attribute access requires one '1005- 'argument', node.lineno,1006- node.filename)1007- assert node.flags != 'OP_DELETE', 'wtf? do we support that?'1008- if node.subs[0].__class__ is ast.Sliceobj:1009- return '%s%s' % (1010- self.handle_node(node.expr),1011- self.handle_node(node.subs[0])1012- )927 self.used_shortcuts.add('get_attribute')928+ if node.arg.__class__ is nodes.SliceExpression:929+ rv = self.handle_slice(node.arg, getslice_test=True)930+ if rv is not None:931+ return self.handle_node(node.node) + rv932 return 'get_attribute(%s, %s)' % (1015- self.handle_node(node.expr),1016- self.handle_node(node.subs[0])933+ self.handle_node(node.node),934+ self.handle_node(node.arg)935 )936 1019- def handle_getattr(self, node):937+ def handle_tuple(self, node):938 """1021- Handle hardcoded attribute access.1022- """1023- self.used_shortcuts.add('get_attribute')1024- return 'get_attribute(%s, %r)' % (1025- self.handle_node(node.expr),1026- node.attrname1027- )1028-1029- def handle_ass_tuple(self, node):1030- """939 Tuple unpacking loops.940 """1033- return self.to_tuple([self.handle_node(n) for n in node.nodes])941+ return self.to_tuple([self.handle_node(n) for n in node.items])942 1035- def handle_bitor(self, node):943+ def handle_filter_expr(self, node):944 """945 We use the pipe operator for filtering.946 """1039- return self.filter(self.handle_node(node.nodes[0]), node.nodes[1:])947+ self.used_shortcuts.add('apply_filters')948+ return 'apply_filters(%s, context, %s)' % (949+ self.handle_node(node.node),950+ self.to_tuple(['(%r, %s)' % (951+ name,952+ self.to_tuple(map(self.handle_node, args))953+ ) for name, args in node.filters])954+ )955 1041- def handle_call_func(self, node, extra_kwargs=None):956+ def handle_call_expr(self, node, extra_kwargs=None):957 """958 Handle function calls.959 """960 args = []961 kwargs = {}1047- star_args = dstar_args = None1048- if node.star_args is not None:1049- star_args = self.handle_node(node.star_args)1050- if node.dstar_args is not None:1051- dstar_args = self.handle_node(node.dstar_args)962+ dyn_args = dyn_kwargs = None963+ if node.dyn_args is not None:964+ dyn_args = self.handle_node(node.dyn_args)965+ if node.dyn_kwargs is not None:966+ dyn_kwargs = self.handle_node(node.dyn_kwargs)967 for arg in node.args:1053- if arg.__class__ is ast.Keyword:1054- kwargs[arg.name] = self.handle_node(arg.expr)1055- else:1056- args.append(self.handle_node(arg))968+ args.append(self.handle_node(arg))969+ for name, arg in node.kwargs:970+ kwargs[name] = self.handle_node(arg)971 if extra_kwargs:972 kwargs.update(extra_kwargs)1059- if not (args or kwargs or star_args or dstar_args or extra_kwargs):973+ if not (args or kwargs or dyn_args or dyn_kwargs):974 self.used_shortcuts.add('call_function_simple')975 return 'call_function_simple(%s, context)' % \976 self.handle_node(node.node)977 self.used_shortcuts.add('call_function')978 return 'call_function(%s, context, %s, {%s}, %s, %s)' % (979 self.handle_node(node.node),980 self.to_tuple(args),981 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),1068- star_args,1069- dstar_args982+ dyn_args,983+ dyn_kwargs984 )985 986 def handle_add(self, node):987 """12 unmodified lines1000 self.handle_node(node.left),1001 self.handle_node(node.right)1002 )1003 1004+ def handle_concat(self, node):1005+ """1006+ Convert some objects to unicode and concatenate them.1007+ """1008+ self.used_shortcuts.add('to_unicode')1009+ return "u''.join(%s)" % self.to_tuple([1010+ 'to_unicode(%s)' % self.handle_node(arg)1011+ for arg in node.args1012+ ])1013+1014 def handle_div(self, node):1015 """1016 Divide two items.1017 """28 unmodified lines1046 self.handle_node(node.left),1047 self.handle_node(node.right)1048 )1049 1126- def handle_unary_add(self, node):1050+ def handle_pos(self, node):1051 """1052 One of the more or less unused nodes.1053 """1130- return '(+%s)' % self.handle_node(node.expr)1054+ return '(+%s)' % self.handle_node(node.node)1055 1132- def handle_unary_sub(self, node):1056+ def handle_neg(self, node):1057 """1058 Make a number negative.1059 """1136- return '(-%s)' % self.handle_node(node.expr)1060+ return '(-%s)' % self.handle_node(node.node)1061 1138- def handle_power(self, node):1062+ def handle_pow(self, node):1063 """1064 handle foo**bar1065 """1066 return '(%s**%s)' % (11 unmodified lines1078 self.handle_node(value)1079 ) for key, value in node.items1080 ])1081 1082+ def handle_set_expr(self, node):1083+ """1084+ Set constructor syntax.1085+ """1086+ self.need_set_import = True1087+ return 'set([%s])' % ', '.join([self.handle_node(n)1088+ for n in node.items])1089+1090 def handle_list(self, node):1091 """1092 We don't know tuples, tuples are lists for jinja.1093 """1094 return '[%s]' % ', '.join([1163- self.handle_node(n) for n in node.nodes1095+ self.handle_node(n) for n in node.items1096 ])1097 1098+ def handle_undefined(self, node):1099+ """1100+ Return the current undefined literal.1101+ """1102+ return 'undefined_singleton'1103+1104 def handle_and(self, node):1105 """1106 Handle foo and bar.1107 """1170- return ' and '.join([1171- self.handle_node(n) for n in node.nodes1172- ])1108+ return '(%s and %s)' % (1109+ self.handle_node(node.left),1110+ self.handle_node(node.right)1111+ )1112 1113 def handle_or(self, node):1114 """1115 handle foo or bar.1116 """1178- return ' or '.join([1179- self.handle_node(n) for n in node.nodes1180- ])1117+ return '(%s or %s)' % (1118+ self.handle_node(node.left),1119+ self.handle_node(node.right)1120+ )1121 1122 def handle_not(self, node):1123 """1124 handle not operator.1125 """1186- return 'not %s' % self.handle_node(node.expr)1126+ return '(not %s)' % self.handle_node(node.node)1127 1188- def handle_slice(self, node):1128+ def handle_slice(self, node, getslice_test=False):1129 """1190- Slice access.1130+ Slice access. Because of backwards compatibilty to python's1131+ `__getslice__` this function takes a second parameter that lets this1132+ method return a regular slice bracket call. If a regular slice bracket1133+ call that is compatible to __getslice__ is not possible the return1134+ value will be `None` so that a regular `get_attribute` wrapping can1135+ happen.1136 """1192- if node.lower is None:1193- lower = ''1137+ if node.start is None:1138+ start = not getslice_test and 'None' or ''1139 else:1195- lower = self.handle_node(node.lower)1196- if node.upper is None:1197- upper = ''1140+ start = self.handle_node(node.start)1141+ if node.stop is None:1142+ stop = not getslice_test and 'None' or ''1143 else:1199- upper = self.handle_node(node.upper)1200- assert node.flags != 'OP_DELETE', 'wtf? shouldn\'t happen'1201- return '%s[%s:%s]' % (1202- self.handle_node(node.expr),1203- lower,1204- upper1205- )1144+ stop = self.handle_node(node.stop)1145+ if node.step is None:1146+ step = 'None'1147+ else:1148+ if getslice_test:1149+ return1150+ step = self.handle_node(node.step)1151+ if getslice_test:1152+ return '[%s:%s]' % (start, stop)1153+ return 'slice(%s, %s, %s)' % (start, stop, step)1154 1207- def handle_sliceobj(self, node):1155+ def handle_conditional_expr(self, node):1156 """1209- Extended Slice access.1157+ Handle conditional expressions.1158 """1211- return '[%s]' % ':'.join([self.handle_node(n) for n in node.nodes])1159+ if have_conditional_expr:1160+ tmpl = '%(expr1)s if %(test)s else %(expr2)s'1161+ else:1162+ tmpl = '(%(test)s and (%(expr1)s,) or (%(expr2)s,))[0]'1163+ return tmpl % {1164+ 'test': self.handle_node(node.test),1165+ 'expr1': self.handle_node(node.expr1),1166+ 'expr2': self.handle_node(node.expr2)1167+ }modified:jinja/__init__.py+4 added-4 removed
57 unmodified lines58 """59 60 from jinja.environment import Environment61 from jinja.datastructure import Markup62-from jinja.utils import from_string62 from jinja.plugin import jinja_plugin_factory as template_plugin_factory63 from jinja.loaders import FileSystemLoader, PackageLoader, DictLoader, \65- ChoiceLoader, FunctionLoader64+ ChoiceLoader, FunctionLoader, MemcachedFileSystemLoader65+from jinja.utils import from_string66 67 68 __all__ = ['Environment', 'Markup', 'FileSystemLoader', 'PackageLoader',69- 'DictLoader', 'ChoiceLoader', 'FunctionLoader', 'from_string',70- 'template_plugin_factory']69+ 'DictLoader', 'ChoiceLoader', 'FunctionLoader',70+ 'MemcachedFileSystemLoader', 'from_string']modified:jinja/_debugger.c+5 added-5 removed
26 unmodified lines27 PyObject *next;28 29 if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))30 return NULL;31- if (next == Py_None) {31+ if (next == Py_None)32 next = NULL;33- } else if (!PyTraceBack_Check(next)) {33+ else if (!PyTraceBack_Check(next)) {34 PyErr_SetString(PyExc_TypeError,35 "tb_set_next arg 2 must be traceback or None");36 return NULL;37- } else {38- Py_INCREF(next);37 }38+ else39+ Py_INCREF(next);40 41 old = tb->tb_next;42- tb->tb_next = (PyTracebackObject *)next;42+ tb->tb_next = (PyTracebackObject*)next;43 Py_XDECREF(old);44 45 Py_INCREF(Py_None);46 return Py_None;19 unmodified linesmodified:jinja/datastructure.py+145 added-70 removed
9 unmodified lines10 """11 12 from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError13 14+_missing = object()15 16+17 def contextcallable(f):18 """19 Mark a function context callable.20 """242 unmodified lines263 continue264 result[key] = value265 return result266 267+ def set_nonlocal(self, name, value):268+ """269+ Set a value in an outer scope.270+ """271+ for layer in self.stack[:0:-1]:272+ if name in layer:273+ layer[name] = value274+ return275+ self.current[name] = value276+277 def translate_func(self):278 """279 The translation function for this context. It takes280 4 parameters. The singular string, the optional plural one,173 unmodified lines454 debugging in the parser. It also provides static helper455 functions that replace some lambda expressions456 """457 446- def __init__(self, func, error_message):458+ def __init__(self, func, msg):459 self.func = func448- self.error_message = error_message460+ self.msg = msg461 450- def __call__(self, p, t, d):451- return self.func(p, t, d)462+ def __call__(self, token):463+ return self.func(token)464 453- def expect_token(token_name, error_message=None):454- """Scans until a token types is found."""455- return StateTest(lambda p, t, d: t == token_name, 'expected ' +456- (error_message or token_name))465+ def expect_token(*types, **kw):466+ """Scans until one of the given tokens is found."""467+ msg = kw.pop('msg', None)468+ if kw:469+ raise TypeError('unexpected keyword argument %r' % iter(kw).next())470+ if len(types) == 1:471+ if msg is None:472+ msg = "expected '%s'" % types[0]473+ return StateTest(lambda t: t.type == types[0], msg)474+ if msg is None:475+ msg = 'expected one of %s' % ', '.join(["'%s'" % type476+ for type in types])477+ return StateTest(lambda t: t.type in types, msg)478 expect_token = staticmethod(expect_token)479 459- def expect_name(*names):460- """Scans until one of the given names is found."""461- if len(names) == 1:462- name = names[0]463- return StateTest(lambda p, t, d: t == 'name' and d == name,464- "expected '%s'" % name)465- else:466- return StateTest(lambda p, t, d: t == 'name' and d in names,467- 'expected one of %s' % ','.join(["'%s'" % name468- for name in names]))469- expect_name = staticmethod(expect_name)480 481+class Token(object):482+ """483+ Token class.484+ """485+ __slots__ = ('lineno', 'type', 'value')486 487+ def __init__(self, lineno, type, value):488+ self.lineno = lineno489+ self.type = intern(str(type))490+ self.value = value491+492+ def __str__(self):493+ from jinja.lexer import keywords, reverse_operators494+ if self.type in keywords:495+ return self.type496+ elif self.type in reverse_operators:497+ return reverse_operators[self.type]498+ return self.value499+500+ def __repr__(self):501+ return 'Token(%r, %r, %r)' % (502+ self.lineno,503+ self.type,504+ self.value505+ )506+507+508+class TokenStreamIterator(object):509+ """510+ The iterator for tokenstreams. Iterate over the stream511+ until the eof token is reached.512+ """513+514+ def __init__(self, stream):515+ self._stream = stream516+517+ def __iter__(self):518+ return self519+520+ def next(self):521+ token = self._stream.current522+ if token.type == 'eof':523+ raise StopIteration()524+ self._stream.next()525+ return token526+527+528 class TokenStream(object):529 """474- A token stream works like a normal generator just that475- it supports pushing tokens back to the stream.530+ A token stream wraps a generator and supports pushing tokens back.531+ It also provides some functions to expect tokens and similar stuff.532 """533 534 def __init__(self, generator, filename):535 self._next = generator.next536 self._pushed = []481- self.last = (1, 'initial', '')537+ self.current = Token(1, 'initial', '')538 self.filename = filename539+ self.next()540 541+ def __iter__(self):542+ return TokenStreamIterator(self)543+544 def bound(self):545 """Return True if the token stream is bound to a parser."""546 return self.parser is not None547 bound = property(bound, doc=bound.__doc__)548 489- def __iter__(self):490- """Return self in order to mark this is iterator."""491- return self549+ def lineno(self):550+ """The current line number."""551+ return self.current.lineno552+ lineno = property(lineno, doc=lineno.__doc__)553 554 def __nonzero__(self):555 """Are we at the end of the tokenstream?"""495- if self._pushed:496- return True497- try:498- self.push(self.next())499- except StopIteration:500- return False501- return True556+ return bool(self._pushed) or self.current.type != 'eof'557 558 eos = property(lambda x: not x.__nonzero__(), doc=__nonzero__.__doc__)559 505- def next(self):506- """Return the next token from the stream."""560+ def look(self):561+ """See what's the next token."""562 if self._pushed:508- rv = self._pushed.pop()509- else:510- rv = self._next()511- self.last = rv512- return rv563+ return self._pushed[-1]564+ old_token = self.current565+ self.next()566+ new_token = self.current567+ self.current = old_token568+ self.push(new_token)569+ return new_token570 514- def look(self):515- """Pop and push a token, return it."""516- token = self.next()517- self.push(*token)518- return token571+ def push(self, token):572+ """Push a token back to the stream."""573+ self._pushed.append(token)574 520- def fetch_until(self, test, drop_needle=False):521- """Fetch tokens until a function matches."""522- try:523- while True:524- token = self.next()525- if test(*token):526- if not drop_needle:527- self.push(*token)528- return529- else:530- yield token531- except StopIteration:532- if isinstance(test, StateTest):533- msg = ': ' + test.error_message534- else:535- msg = ''536- raise TemplateSyntaxError('end of stream' + msg,537- self.last[0], self.filename)575+ def skip(self, n):576+ """Got n tokens ahead."""577+ for x in xrange(n):578+ self.next()579 539- def drop_until(self, test, drop_needle=False):540- """Fetch tokens until a function matches and drop all541- tokens."""542- for token in self.fetch_until(test, drop_needle):543- pass580+ def next(self):581+ """Go one token ahead."""582+ if self._pushed:583+ self.current = self._pushed.pop()584+ elif self.current.type != 'eof':585+ try:586+ self.current = self._next()587+ except StopIteration:588+ self.close()589 545- def push(self, lineno, token, data):546- """Push an yielded token back to the stream."""547- self._pushed.append((lineno, token, data))590+ def read_whitespace(self):591+ """Read all the whitespace, up to the next tag."""592+ lineno = self.current.lineno593+ buf = []594+ while self.current.type == 'data' and not \595+ self.current.value.strip():596+ buf.append(self.current.value)597+ self.next()598+ if buf:599+ return Token(lineno, 'data', u''.join(buf))600 601+ def close(self):602+ """Close the stream."""603+ self.current = Token(self.current.lineno, 'eof', '')604+ self._next = None605 606+ def expect(self, token_type, token_value=_missing):607+ """Expect a given token type and return it"""608+ if self.current.type != token_type:609+ raise TemplateSyntaxError("expected token %r, got %r" %610+ (token_type, self.current.type),611+ self.current.lineno,612+ self.filename)613+ elif token_value is not _missing and \614+ self.current.value != token_value:615+ raise TemplateSyntaxError("expected %r, got %r" %616+ (token_value, self.current.value),617+ self.current.lineno,618+ self.filename)619+ try:620+ return self.current621+ finally:622+ self.next()623+624+625 class TemplateStream(object):626 """627 Wraps a genererator for outputing template streams.628 """48 unmodified linesmodified:jinja/debugger.py+36 added-19 removed
45 unmodified lines46 except ImportError:47 has_extended_debugger = False48 49 # we need the RUNTIME_EXCEPTION_OFFSET to skip the not used frames50-from jinja.utils import RUNTIME_EXCEPTION_OFFSET50+from jinja.utils import reversed, RUNTIME_EXCEPTION_OFFSET51 52 53-def fake_template_exception(exc_type, exc_value, traceback, filename, lineno,54- source, context_or_env):53+def fake_template_exception(exc_type, exc_value, tb, filename, lineno,54+ source, context_or_env, tb_back=None):55 """56 Raise an exception "in a template". Return a traceback57 object. This is used for runtime debugging, not compile time.58 """45 unmodified lines104 exc_info = sys.exc_info()105 106 # if we have an extended debugger we set the tb_next flag so that107 # we don't loose the higher stack items.108- if has_extended_debugger and traceback is not None:109- tb_set_next(exc_info[2].tb_next, traceback.tb_next)108+ if has_extended_debugger:109+ if tb_back is not None:110+ tb_set_next(tb_back, exc_info[2])111+ if tb is not None:112+ tb_set_next(exc_info[2].tb_next, tb.tb_next)113 114 # otherwise just return the exc_info from the simple debugger115 return exc_info116 117 115-def translate_exception(template, context, exc_type, exc_value, traceback):118+def translate_exception(template, context, exc_type, exc_value, tb):119 """120 Translate an exception and return the new traceback.121 """122 # depending on the python version we have to skip some frames to123 # step to get the frame of the current template. The frames before124 # are the toolchain used to render that thing.125 for x in xrange(RUNTIME_EXCEPTION_OFFSET):123- traceback = traceback.tb_next126+ tb = tb.tb_next127 125- # the next thing we do is matching the current error line against the126- # debugging table to get the correct source line. If we can't find the127- # filename and line number we return the traceback object unaltered.128- error_line = traceback.tb_lineno129- for code_line, tmpl_filename, tmpl_line in template._debug_info[::-1]:130- if code_line <= error_line:131- break132- else:133- return traceback128+ result_tb = prev_tb = None129+ initial_tb = tb130 135- return fake_template_exception(exc_type, exc_value, traceback,136- tmpl_filename, tmpl_line,137- template._source, context)131+ # translate all the jinja frames in this traceback132+ while tb is not None:133+ if tb.tb_frame.f_globals.get('__jinja_template__'):134+ debug_info = tb.tb_frame.f_globals['debug_info']135 136+ # the next thing we do is matching the current error line against the137+ # debugging table to get the correct source line. If we can't find the138+ # filename and line number we return the traceback object unaltered.139+ error_line = tb.tb_lineno140+ for code_line, tmpl_filename, tmpl_line in reversed(debug_info):141+ if code_line <= error_line:142+ source = tb.tb_frame.f_globals['template_source']143+ tb = fake_template_exception(exc_type, exc_value, tb,144+ tmpl_filename, tmpl_line,145+ source, context, prev_tb)[-1]146+ break147+ if result_tb is None:148+ result_tb = tb149+ prev_tb = tb150+ tb = tb.tb_next151 152+ # under some conditions we cannot translate any frame. in that153+ # situation just return the original traceback.154+ return (exc_type, exc_value, result_tb or intial_tb)155+156+157 def raise_syntax_error(exception, env, source=None):158 """159 This method raises an exception that includes more debugging160 informations so that debugging works better. Unlike53 unmodified linesmodified:jinja/defaults.py+1 added-11 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12 from jinja.tests import TESTS as DEFAULT_TESTS13-from jinja.utils import debug_helper, safe_range, generate_lorem_ipsum, \14- watch_changes, render_included13+from jinja.utils import NAMESPACE as DEFAULT_NAMESPACE14 15 16 __all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']18-19-20-DEFAULT_NAMESPACE = {21- 'range': safe_range,22- 'debug': debug_helper,23- 'lipsum': generate_lorem_ipsum,24- 'watchchanges': watch_changes,25- 'rendertemplate': render_included26-}modified:jinja/environment.py+9 added-11 removed
50 unmodified lines51 filters=None,52 tests=None,53 context_class=Context,54 undefined_singleton=SilentUndefined,55+ disable_regexps=False,56 friendly_traceback=True,57 translator_factory=None):58 """59 Here the possible initialization parameters:43 unmodified lines103 See the `Context` documentation for more104 details.105 `undefined_singleton` The singleton value that is used for missing106 variables. *new in Jinja 1.1*107+ `disable_regexps` Disable support for regular expresssions.108 `friendly_traceback` Set this to `False` to disable the developer109 friendly traceback rewriting. Whenever an110 runtime or syntax error occours jinja will111 try to make a developer friendly traceback32 unmodified lines144 self.tests = tests145 self.default_filters = default_filters or []146 self.context_class = context_class147 self.undefined_singleton = undefined_singleton148+ self.disable_regexps = disable_regexps149 self.friendly_traceback = friendly_traceback150 151 # global namespace152 if namespace is None:47 unmodified lines200 allows you to render it.201 """202 from jinja.translators.python import PythonTranslator203 try:201- rv = PythonTranslator.process(self, Parser(self, source).parse())204+ rv = PythonTranslator.process(self, Parser(self, source).parse(),205+ source)206 except TemplateSyntaxError, e:207 # on syntax errors rewrite the traceback if wanted208 if not self.friendly_traceback:209 raise210 from jinja.debugger import raise_syntax_error211+ if __debug__:207- __traceback_hide__ = True212+ __traceback_hide__ = True213 raise_syntax_error(e, self, source)214 else:210- # everything went well. attach the source and return it211- # the attached source is used by the traceback system for212- # debugging porposes213- rv._source = source215 return rv216 217 def get_template(self, filename):218 """66 unmodified lines285 cache[key] = func = self.filters[filtername](*args)286 value = func(self, context, value)287 return value288 288- def perform_test(self, context, testname, args, value, invert):289+ def perform_test(self, context, testname, args, value):290 """291 Perform a test on a variable.292 """293 # some traceback systems allow to skip frames. but allow7 unmodified lines301 else:302 if testname not in self.tests:303 raise TestNotFound(testname)304 context.cache[key] = func = self.tests[testname](*args)304- rv = func(self, context, value)305- if invert:306- return not rv307- return bool(rv)305+ return not not func(self, context, value)306 307 def get_attribute(self, obj, name):308 """309 Get one attribute from an object.86 unmodified linesmodified:jinja/filters.py+48 added-3 removed
10 unmodified lines11 import re12 from random import choice13 from operator import itemgetter14 from urllib import urlencode, quote15-from jinja.utils import urlize, escape, reversed, sorted, groupby15+from jinja.utils import urlize, escape, reversed, sorted, groupby, \16+ get_attribute17 from jinja.datastructure import TemplateData17-from jinja.exceptions import FilterArgumentError18+from jinja.exceptions import FilterArgumentError, SecurityException19 20 21 _striptags_re = re.compile(r'(<!--.*?-->|<[^>]+>)')22 863 unmodified lines886 key=itemgetter('grouper'))887 return wrapped888 889 890+def do_getattribute(attribute):891+ """892+ Get one attribute from an object. Normally you don't have to use this893+ filter because the attribute and subscript expressions try to either894+ get an attribute of an object or an item. In some situations it could895+ be that there is an item *and* an attribute with the same name. In that896+ situation only the item is returned, never the attribute.897+898+ .. sourcecode:: jinja899+900+ {{ foo.bar }} -> {{ foo|getattribute('bar') }}901+902+ *New in Jinja 1.2*903+ """904+ def wrapped(env, context, value):905+ try:906+ return get_attribute(value, attribute)907+ except (SecurityException, AttributeError):908+ return env.undefined_singleton909+ return wrapped910+911+912+def do_getitem(key):913+ """914+ This filter basically works like the normal subscript expression but915+ it doesn't fall back to attribute lookup. If an item does not exist for916+ an object undefined is returned.917+918+ .. sourcecode:: jinja919+920+ {{ foo.bar }} -> {{ foo|getitem('bar') }}921+922+ *New in Jinja 1.2*923+ """924+ def wrapped(env, context, value):925+ try:926+ return value[key]927+ except (TypeError, KeyError, IndexError, AttributeError):928+ return env.undefined_singleton929+ return wrapped930+931+932 FILTERS = {933 'replace': do_replace,934 'upper': do_upper,935 'lower': do_lower,39 unmodified lines975 'sum': do_sum,976 'abs': do_abs,977 'round': do_round,978 'sort': do_sort,936- 'groupby': do_groupby979+ 'groupby': do_groupby,980+ 'getattribute': do_getattribute,981+ 'getitem': do_getitem982 }modified:jinja/lexer.py+171 added-28 removed
21 unmodified lines22 :copyright: 2007 by Armin Ronacher.23 :license: BSD, see LICENSE for more details.24 """25 import re26+import unicodedata26-from jinja.datastructure import TokenStream27+from jinja.datastructure import TokenStream, Token28 from jinja.exceptions import TemplateSyntaxError28-from jinja.utils import set29+from jinja.utils import set, sorted30 from weakref import WeakValueDictionary31 32 33 __all__ = ['Lexer', 'Failure', 'keywords']8 unmodified lines42 whitespace_re = re.compile(r'\s+(?m)')43 name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')44 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"45 r'|"([^"\\]*(?:\\.[^"\\]*)*)")(?ms)')45-number_re = re.compile(r'\d+(\.\d+)*')46+integer_re = re.compile(r'\d+')47+float_re = re.compile(r'\d+\.\d+')48+regex_re = re.compile(r'@/([^/\\]*(?:\\.[^/\\]*)*)*/[a-z]*(?ms)')49 47-operator_re = re.compile('(%s)' % '|'.join([48- isinstance(x, unicode) and str(x) or re.escape(x) for x in [49- # math operators50- '+', '-', '**', '*', '//', '/', '%',51- # braces and parenthesis52- '[', ']', '(', ')', '{', '}',53- # attribute access and comparison / logical operators54- '.', ':', ',', '|', '==', '<=', '>=', '<', '>', '!=', '=',55- ur'or\b', ur'and\b', ur'not\b', ur'in\b', ur'is\b'56-]]))50 51 # set of used keywords52 keywords = set(['and', 'block', 'cycle', 'elif', 'else', 'endblock',53 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',54 'endtrans', 'extends', 'filter', 'for', 'if', 'in',55 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',63- 'recursive', 'set', 'trans', 'print'])56+ 'recursive', 'set', 'trans', 'print', 'call', 'endcall'])57 58+# bind operators to token types59+operators = {60+ '+': 'add',61+ '-': 'sub',62+ '/': 'div',63+ '//': 'floordiv',64+ '*': 'mul',65+ '%': 'mod',66+ '**': 'pow',67+ '~': 'tilde',68+ '!': 'bang',69+ '@': 'at',70+ '[': 'lbracket',71+ ']': 'rbracket',72+ '(': 'lparen',73+ ')': 'rparen',74+ '{': 'lbrace',75+ '}': 'rbrace',76+ '==': 'eq',77+ '!=': 'ne',78+ '>': 'gt',79+ '>=': 'gteq',80+ '<': 'lt',81+ '<=': 'lteq',82+ '=': 'assign',83+ '.': 'dot',84+ ':': 'colon',85+ '|': 'pipe',86+ ',': 'comma'87+}88 89+reverse_operators = dict([(v, k) for k, v in operators.iteritems()])90+assert len(operators) == len(reverse_operators), 'operators dropped'91+operator_re = re.compile('(%s)' % '|'.join([re.escape(x) for x in92+ sorted(operators, key=lambda x: -len(x))]))93+94+95+def unescape_string(lineno, filename, s):96+ r"""97+ Unescape a string. Supported escapes:98+ \a, \n, \r\, \f, \v, \\, \", \', \099+100+ \x00, \u0000, \U00000000, \N{...}101+102+ Not supported are \101 because imho redundant.103+ """104+ result = []105+ write = result.append106+ simple_escapes = {107+ 'a': '\a',108+ 'n': '\n',109+ 'r': '\r',110+ 'f': '\f',111+ 't': '\t',112+ 'v': '\v',113+ '\\': '\\',114+ '"': '"',115+ "'": "'",116+ '0': '\x00'117+ }118+ unicode_escapes = {119+ 'x': 2,120+ 'u': 4,121+ 'U': 8122+ }123+ chariter = iter(s)124+ next_char = chariter.next125+126+ try:127+ for char in chariter:128+ if char == '\\':129+ char = next_char()130+ if char in simple_escapes:131+ write(simple_escapes[char])132+ elif char in unicode_escapes:133+ seq = [next_char() for x in xrange(unicode_escapes[char])]134+ try:135+ write(unichr(int(''.join(seq), 16)))136+ except ValueError:137+ raise TemplateSyntaxError('invalid unicode codepoint',138+ lineno, filename)139+ elif char == 'N':140+ if next_char() != '{':141+ raise TemplateSyntaxError('no name for codepoint',142+ lineno, filename)143+ seq = []144+ while True:145+ char = next_char()146+ if char == '}':147+ break148+ seq.append(char)149+ try:150+ write(unicodedata.lookup(u''.join(seq)))151+ except KeyError:152+ raise TemplateSyntaxError('unknown character name',153+ lineno, filename)154+ else:155+ write('\\' + char)156+ else:157+ write(char)158+ except StopIteration:159+ raise TemplateSyntaxError('invalid string escape', lineno, filename)160+ return u''.join(result)161+162+163+def unescape_regex(s):164+ """165+ Unescape rules for regular expressions.166+ """167+ buffer = []168+ write = buffer.append169+ in_escape = False170+ for char in s:171+ if in_escape:172+ in_escape = False173+ if char not in safe_chars:174+ write('\\' + char)175+ continue176+ write(char)177+ return u''.join(buffer)178+179+180 class Failure(object):181 """182 Class that raises a `TemplateSyntaxError` if called.183 Used by the `Lexer` to specify known errors.50 unmodified lines234 235 # lexing rules for tags236 tag_rules = [237 (whitespace_re, None, None),124- (number_re, 'number', None),238+ (float_re, 'float', None),239+ (integer_re, 'integer', None),240 (name_re, 'name', None),126- (operator_re, 'operator', None),127- (string_re, 'string', None)241+ (string_re, 'string', None),242+ (regex_re, 'regex', None),243+ (operator_re, 'operator', None)244 ]245 246 #: if variables and blocks have the same delimiters we won't247 #: receive any variable blocks in the parser. This variable is `True`85 unmodified lines333 ] + tag_rules334 335 def tokenize(self, source, filename=None):336 """221- Simple tokenize function that yields ``(position, type, contents)``222- tuples. Wrap the generator returned by this function in a223- `TokenStream` to get real token instances and be able to push tokens224- back to the stream. That's for example done by the parser.225-226- Additionally non keywords are escaped.337+ Works like `tokeniter` but returns a tokenstream of tokens and not a338+ generator or token tuples. Additionally all token values are already339+ converted into types and postprocessed. For example keywords are340+ already keyword tokens, not named tokens, comments are removed,341+ integers and floats converted, strings unescaped etc.342 """343 def generate():344 for lineno, token, value in self.tokeniter(source, filename):230- if token == 'name' and value not in keywords:231- value += '_'232- yield lineno, token, value345+ if token in ('comment_begin', 'comment', 'comment_end'):346+ continue347+ elif token == 'data':348+ try:349+ value = str(value)350+ except UnicodeError:351+ pass352+ elif token == 'name':353+ value = str(value)354+ if value in keywords:355+ token = value356+ value = ''357+ elif token == 'string':358+ value = unescape_string(lineno, filename, value[1:-1])359+ try:360+ value = str(value)361+ except UnicodeError:362+ pass363+ elif token == 'regex':364+ args = value[value.rfind('/') + 1:]365+ value = unescape_regex(value[2:-(len(args) + 1)])366+ if args:367+ value = '(?%s)%s' % (args, value)368+ elif token == 'integer':369+ value = int(value)370+ elif token == 'float':371+ value = float(value)372+ elif token == 'operator':373+ token = operators[value]374+ value = ''375+ yield Token(lineno, token, value)376 return TokenStream(generate(), filename)377 378 def tokeniter(self, source, filename=None):379 """380 This method tokenizes the text and returns the tokens in a generator.381 Use this method if you just want to tokenize a template. The output382 you get is not compatible with the input the jinja parser wants. The240- parser uses the `tokenize` function with returns a `TokenStream` with241- some escaped tokens.383+ parser uses the `tokenize` function with returns a `TokenStream` and384+ keywords instead of just names.385 """386 source = '\n'.join(source.splitlines())387 pos = 0388 lineno = 1128 unmodified linesmodified:jinja/loaders.py+37 added-9 removed
40 unmodified lines41 sha.new('jinja(%s|%s)tmpl' %42 (name, salt or '')).hexdigest())43 44 45-45 def _loader_missing(*args, **kwargs):46 """Helper function for `LoaderWrapper`."""47 raise RuntimeError('no loader defined')48 49 51-50 class LoaderWrapper(object):51 """52 Wraps a loader so that it's bound to an environment.53 Also handles template syntax errors.419 unmodified lines473 and Microsoft Windows.474 475 It uses the `pkg_resources` libraries distributed with setuptools for476 retrieving the data from the packages. This works for eggs too so you479- don't have to mark your egg as non zip safe.477+ don't have to mark your egg as non zip safe. If pkg_resources is not478+ available it just falls back to path joining relative to the package.479 """480 482- def __init__(self, package_name, package_path):481+ def __init__(self, package_name, package_path, force_native=False):482 try:483 import pkg_resources484 except ImportError:485 raise RuntimeError('setuptools not installed')486 self.package_name = package_name487 self.package_path = package_path488+ self.force_native = force_native489 490- def get_source(self, environment, name, parent):491- from pkg_resources import resource_exists, resource_string492- path = '/'.join([self.package_path] + [p for p in name.split('/')490+ def _get_load_func(self):491+ if hasattr(self, '_load_func'):492+ return self._load_func493+ try:494+ from pkg_resources import resource_exists, resource_string495+ if self.force_native:496+ raise ImportError()497+ except ImportError:498+ basepath = path.dirname(__import__(self.package_name, None, None,499+ ['__file__']).__file__)500+ def load_func(name):501+ filename = path.join(basepath, *(502+ self.package_path.split('/') +503+ [p for p in name.split('/') if p != '..'])504+ )505+ if path.exists(filename):506+ f = file(filename)507+ try:508+ return f.read()509+ finally:510+ f.close()511+ else:512+ def load_func(name):513+ path = '/'.join([self.package_path] + [p for p in name.split('/')514 if p != '..'])494- if not resource_exists(self.package_name, path):515+ if resource_exists(self.package_name, path):516+ return resource_string(self.package_name, path)517+ self._load_func = load_func518+ return load_func519+520+ def get_source(self, environment, name, parent):521+ load_func = self._get_load_func()522+ contents = load_func(name)523+ if contents is None:524 raise TemplateNotFound(name)496- contents = resource_string(self.package_name, path)525 return contents.decode(environment.template_charset)526 527 528 class PackageLoader(CachedLoaderMixin, BasePackageLoader):234 unmodified linesmodified:jinja/nodes.py+499 added-128 removed
10 unmodified lines11 12 :copyright: 2007 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14 """15-from compiler import ast15+from itertools import chain16 from copy import copy17 18 19-def inc_lineno(offset, tree):20- """21- Increment the linenumbers of all nodes in tree with offset.22- """23- todo = [tree]24- while todo:25- node = todo.pop()26- if node.lineno:27- node.lineno += offset - 128- else:29- node.lineno = offset30- todo.extend(node.getChildNodes())31-32-19 def get_nodes(nodetype, tree, exclude_root=True):20 """21 Get all nodes from nodetype in the tree excluding the22 node passed if `exclude_root` is `True` (default).23 """24 if exclude_root:39- todo = tree.getChildNodes()25+ todo = tree.get_child_nodes()26 else:27 todo = [tree]28 while todo:29 node = todo.pop()30 if node.__class__ is nodetype:31 yield node46- todo.extend(node.getChildNodes())32+ todo.extend(node.get_child_nodes())33 34 49-def get_nodes_parentinfo(nodetype, tree):35+class NotPossible(NotImplementedError):36 """51- Like `get_nodes` but it yields tuples in the form ``(parent, node)``.52- If a node is a direct ancestor of `tree` parent will be `None`.53-54- Always excludes the root node.37+ If a given node cannot do something.38 """56- todo = [tree]57- while todo:58- node = todo.pop()59- if node is tree:60- parent = None61- else:62- parent = node63- for child in node.getChildNodes():64- if child.__class__ is nodetype:65- yield parent, child66- todo.append(child)39 40 69-class Node(ast.Node):41+class Node(object):42 """43 Jinja node.44 """45 46+ def __init__(self, lineno=None, filename=None):47+ self.lineno = lineno48+ self.filename = filename49+50 def get_items(self):51 return []52 77- def getChildren(self):78- return self.get_items()53+ def get_child_nodes(self):54+ return [x for x in self.get_items() if isinstance(x, Node)]55 80- def getChildNodes(self):81- return [x for x in self.get_items() if isinstance(x, ast.Node)]56+ def allows_assignments(self):57+ return False58 59+ def __repr__(self):60+ return 'Node()'61 62+63 class Text(Node):64 """65 Node that represents normal text.66 """67 89- def __init__(self, lineno, text):90- self.lineno = lineno68+ def __init__(self, text, variables, lineno=None, filename=None):69+ Node.__init__(self, lineno, filename)70 self.text = text92-93- def get_items(self):94- return [self.text]95-96- def __repr__(self):97- return 'Text(%r)' % (self.text,)98-99-100-class DynamicText(Node):101- """102- Note that represents normal text with string formattings.103- Those are used for texts that contain variables. The attribute104- `variables` contains a list of Print tags and nothing else.105- """106-107- def __init__(self, lineno, format_string, variables):108- self.lineno = lineno109- self.format_string = format_string71 self.variables = variables72 73 def get_items(self):113- return [self.format_string] + list(self.variables)74+ return [self.text] + list(self.variables)75 76 def __repr__(self):116- return 'DynamicText(%r, %r)' % (117- self.format_string,77+ return 'Text(%r, %r)' % (78+ self.text,79 self.variables80 )81 82 1 unmodified line84 """85 A node that stores multiple childnodes.86 """87 127- def __init__(self, lineno, data=None):128- self.lineno = lineno129- list.__init__(self, data or ())88+ def __init__(self, data, lineno=None, filename=None):89+ Node.__init__(self, lineno, filename)90+ list.__init__(self, data)91 131- getChildren = getChildNodes = lambda s: list(s) + s.get_items()92+ def get_items(self):93+ return list(self)94 95 def __repr__(self):96 return 'NodeList(%s)' % list.__repr__(self)97 98 137-class Template(NodeList):99+class Template(Node):100 """101 Node that represents a template.102 """103 142- def __init__(self, filename, body, extends):143- if body.__class__ is not NodeList:144- body = (body,)145- NodeList.__init__(self, 1, body)104+ def __init__(self, extends, body, lineno=None, filename=None):105+ Node.__init__(self, lineno, filename)106 self.extends = extends147- self.filename = filename107+ self.body = body108 109 def get_items(self):150- return self.extends is not None and [self.extends] or []110+ return [self.extends, self.body]111 112 def __repr__(self):153- return 'Template(%r, %r, %s)' % (154- self.filename,113+ return 'Template(%r, %r)' % (114 self.extends,156- list.__repr__(self)115+ self.body116 )117 118 119 class ForLoop(Node):120 """121 A node that represents a for loop122 """123 165- def __init__(self, lineno, item, seq, body, else_, recursive):166- self.lineno = lineno124+ def __init__(self, item, seq, body, else_, recursive, lineno=None,125+ filename=None):126+ Node.__init__(self, lineno, filename)127 self.item = item128 self.seq = seq129 self.body = body130 self.else_ = else_16 unmodified lines147 """148 A node that represents an if condition.149 """150 191- def __init__(self, lineno, tests, else_):192- self.lineno = lineno151+ def __init__(self, tests, else_, lineno=None, filename=None):152+ Node.__init__(self, lineno, filename)153 self.tests = tests154 self.else_ = else_155 156 def get_items(self):14 unmodified lines171 """172 A node that represents the cycle statement.173 """174 215- def __init__(self, lineno, seq):216- self.lineno = lineno175+ def __init__(self, seq, lineno=None, filename=None):176+ Node.__init__(self, lineno, filename)177 self.seq = seq178 179 def get_items(self):180 return [self.seq]6 unmodified lines187 """188 A node that represents variable tags and print calls.189 """190 231- def __init__(self, lineno, variable):232- self.lineno = lineno233- self.variable = variable191+ def __init__(self, expr, lineno=None, filename=None):192+ Node.__init__(self, lineno, filename)193+ self.expr = expr194 195 def get_items(self):236- return [self.variable]196+ return [self.expr]197 198 def __repr__(self):239- return 'Print(%r)' % (self.variable,)199+ return 'Print(%r)' % (self.expr,)200 201 202 class Macro(Node):203 """204 A node that represents a macro.205 """206 247- def __init__(self, lineno, name, arguments, body):248- self.lineno = lineno207+ def __init__(self, name, arguments, body, lineno=None, filename=None):208+ Node.__init__(self, lineno, filename)209 self.name = name210 self.arguments = arguments211 self.body = body212 213 def get_items(self):254- result = [self.name]255- if self.arguments:256- for item in self.arguments:257- result.extend(item)258- result.append(self.body)259- return result214+ return [self.name] + list(chain(*self.arguments)) + [self.body]215 216 def __repr__(self):217 return 'Macro(%r, %r, %r)' % (218 self.name,6 unmodified lines225 """226 A node that represents am extended macro call.227 """228 274- def __init__(self, lineno, expr, body):275- self.lineno = lineno229+ def __init__(self, expr, body, lineno=None, filename=None):230+ Node.__init__(self, lineno, filename)231 self.expr = expr232 self.body = body233 234 def get_items(self):7 unmodified lines242 243 244 class Set(Node):245 """291- Allow defining own variables.246+ Allows defining own variables.247 """248 294- def __init__(self, lineno, name, expr):295- self.lineno = lineno249+ def __init__(self, name, expr, scope_local, lineno=None, filename=None):250+ Node.__init__(self, lineno, filename)251 self.name = name252 self.expr = expr253+ self.scope_local = scope_local254 255 def get_items(self):300- return [self.name, self.expr]256+ return [self.name, self.expr, self.scope_local]257 258 def __repr__(self):303- return 'Set(%r, %r)' % (259+ return 'Set(%r, %r, %r)' % (260 self.name,305- self.expr261+ self.expr,262+ self.scope_local263 )264 265 266 class Filter(Node):267 """268 Node for filter sections.269 """270 314- def __init__(self, lineno, body, filters):315- self.lineno = lineno271+ def __init__(self, body, filters, lineno=None, filename=None):272+ Node.__init__(self, lineno, filename)273 self.body = body274 self.filters = filters275 276 def get_items(self):10 unmodified lines287 """288 A node that represents a block.289 """290 334- def __init__(self, lineno, name, body):335- self.lineno = lineno291+ def __init__(self, name, body, lineno=None, filename=None):292+ Node.__init__(self, lineno, filename)293 self.name = name294 self.body = body295 296 def replace(self, node):297 """341- Replace the current data with the data of another block node.298+ Replace the current data with the copied data of another block299+ node.300 """301 assert node.__class__ is Block344- self.__dict__.update(node.__dict__)302+ self.lineno = node.lineno303+ self.filename = node.filename304+ self.name = node.name305+ self.body = copy(node.body)306 307 def clone(self):308 """309 Create an independent clone of this node.9 unmodified lines319 self.body320 )321 322 362-class Extends(Node):363- """364- A node that represents the extends tag.365- """366-367- def __init__(self, lineno, template):368- self.lineno = lineno369- self.template = template370-371- def get_items(self):372- return [self.template]373-374- def __repr__(self):375- return 'Extends(%r)' % self.template376-377-323 class Include(Node):324 """325 A node that represents the include tag.326 """327 383- def __init__(self, lineno, template):384- self.lineno = lineno328+ def __init__(self, template, lineno=None, filename=None):329+ Node.__init__(self, lineno, filename)330 self.template = template331 332 def get_items(self):333 return [self.template]8 unmodified lines342 """343 A node for translatable sections.344 """345 401- def __init__(self, lineno, singular, plural, indicator, replacements):402- self.lineno = lineno346+ def __init__(self, singular, plural, indicator, replacements,347+ lineno=None, filename=None):348+ Node.__init__(self, lineno, filename)349 self.singular = singular350 self.plural = plural351 self.indicator = indicator352 self.replacements = replacements11 unmodified lines364 self.plural,365 self.indicator,366 self.replacements367 )368+369+370+class Expression(Node):371+ """372+ Baseclass for all expressions.373+ """374+375+376+class BinaryExpression(Expression):377+ """378+ Baseclass for all binary expressions.379+ """380+381+ def __init__(self, left, right, lineno=None, filename=None):382+ Expression.__init__(self, lineno, filename)383+ self.left = left384+ self.right = right385+386+ def get_items(self):387+ return [self.left, self.right]388+389+ def __repr__(self):390+ return '%s(%r, %r)' % (391+ self.__class__.__name__,392+ self.left,393+ self.right394+ )395+396+397+class UnaryExpression(Expression):398+ """399+ Baseclass for all unary expressions.400+ """401+402+ def __init__(self, node, lineno=None, filename=None):403+ Expression.__init__(self, lineno, filename)404+ self.node = node405+406+ def get_items(self):407+ return [self.node]408+409+ def __repr__(self):410+ return '%s(%r)' % (411+ self.__class__.__name__,412+ self.node413+ )414+415+416+class ConstantExpression(Expression):417+ """418+ any constat such as {{ "foo" }}419+ """420+421+ def __init__(self, value, lineno=None, filename=None):422+ Expression.__init__(self, lineno, filename)423+ self.value = value424+425+ def get_items(self):426+ return [self.value]427+428+ def __repr__(self):429+ return 'ConstantExpression(%r)' % (self.value,)430+431+432+class UndefinedExpression(Expression):433+ """434+ represents the special 'undefined' value.435+ """436+437+ def __repr__(self):438+ return 'UndefinedExpression()'439+440+441+class RegexExpression(Expression):442+ """443+ represents the regular expression literal.444+ """445+446+ def __init__(self, value, lineno=None, filename=None):447+ Expression.__init__(self, lineno, filename)448+ self.value = value449+450+ def get_items(self):451+ return [self.value]452+453+ def __repr__(self):454+ return 'RegexExpression(%r)' % (self.value,)455+456+457+class NameExpression(Expression):458+ """459+ any name such as {{ foo }}460+ """461+462+ def __init__(self, name, lineno=None, filename=None):463+ Expression.__init__(self, lineno, filename)464+ self.name = name465+466+ def get_items(self):467+ return [self.name]468+469+ def allows_assignments(self):470+ return self.name != '_'471+472+ def __repr__(self):473+ return 'NameExpression(%r)' % self.name474+475+476+class ListExpression(Expression):477+ """478+ any list literal such as {{ [1, 2, 3] }}479+ """480+481+ def __init__(self, items, lineno=None, filename=None):482+ Expression.__init__(self, lineno, filename)483+ self.items = items484+485+ def get_items(self):486+ return list(self.items)487+488+ def __repr__(self):489+ return 'ListExpression(%r)' % (self.items,)490+491+492+class DictExpression(Expression):493+ """494+ any dict literal such as {{ {1: 2, 3: 4} }}495+ """496+497+ def __init__(self, items, lineno=None, filename=None):498+ Expression.__init__(self, lineno, filename)499+ self.items = items500+501+ def get_items(self):502+ return list(chain(*self.items))503+504+ def __repr__(self):505+ return 'DictExpression(%r)' % (self.items,)506+507+508+class SetExpression(Expression):509+ """510+ any set literal such as {{ @(1, 2, 3) }}511+ """512+513+ def __init__(self, items, lineno=None, filename=None):514+ Expression.__init__(self, lineno, filename)515+ self.items = items516+517+ def get_items(self):518+ return self.items[:]519+520+ def __repr__(self):521+ return 'SetExpression(%r)' % (self.items,)522+523+524+class ConditionalExpression(Expression):525+ """526+ {{ foo if bar else baz }}527+ """528+529+ def __init__(self, test, expr1, expr2, lineno=None, filename=None):530+ Expression.__init__(self, lineno, filename)531+ self.test = test532+ self.expr1 = expr1533+ self.expr2 = expr2534+535+ def get_items(self):536+ return [self.test, self.expr1, self.expr2]537+538+ def __repr__(self):539+ return 'ConstantExpression(%r, %r, %r)' % (540+ self.test,541+ self.expr1,542+ self.expr2543+ )544+545+546+class FilterExpression(Expression):547+ """548+ {{ foo|bar|baz }}549+ """550+551+ def __init__(self, node, filters, lineno=None, filename=None):552+ Expression.__init__(self, lineno, filename)553+ self.node = node554+ self.filters = filters555+556+ def get_items(self):557+ result = [self.node]558+ for filter, args in self.filters:559+ result.append(filter)560+ result.extend(args)561+ return result562+563+ def __repr__(self):564+ return 'FilterExpression(%r, %r)' % (565+ self.node,566+ self.filters567+ )568+569+570+class TestExpression(Expression):571+ """572+ {{ foo is lower }}573+ """574+575+ def __init__(self, node, name, args, lineno=None, filename=None):576+ Expression.__init__(self, lineno, filename)577+ self.node = node578+ self.name = name579+ self.args = args580+581+ def get_items(self):582+ return [self.node, self.name] + list(self.args)583+584+ def __repr__(self):585+ return 'TestExpression(%r, %r, %r)' % (586+ self.node,587+ self.name,588+ self.args589+ )590+591+592+class CallExpression(Expression):593+ """594+ {{ foo(bar) }}595+ """596+597+ def __init__(self, node, args, kwargs, dyn_args, dyn_kwargs,598+ lineno=None, filename=None):599+ Expression.__init__(self, lineno, filename)600+ self.node = node601+ self.args = args602+ self.kwargs = kwargs603+ self.dyn_args = dyn_args604+ self.dyn_kwargs = dyn_kwargs605+606+ def get_items(self):607+ return [self.node, self.args, self.kwargs, self.dyn_args,608+ self.dyn_kwargs]609+610+ def __repr__(self):611+ return 'CallExpression(%r, %r, %r, %r, %r)' % (612+ self.node,613+ self.args,614+ self.kwargs,615+ self.dyn_args,616+ self.dyn_kwargs617+ )618+619+620+class SubscriptExpression(Expression):621+ """622+ {{ foo.bar }} and {{ foo['bar'] }} etc.623+ """624+625+ def __init__(self, node, arg, lineno=None, filename=None):626+ Expression.__init__(self, lineno, filename)627+ self.node = node628+ self.arg = arg629+630+ def get_items(self):631+ return [self.node, self.arg]632+633+ def __repr__(self):634+ return 'SubscriptExpression(%r, %r)' % (635+ self.node,636+ self.arg637+ )638+639+640+class SliceExpression(Expression):641+ """642+ 1:2:3 etc.643+ """644+645+ def __init__(self, start, stop, step, lineno=None, filename=None):646+ Expression.__init__(self, lineno, filename)647+ self.start = start648+ self.stop = stop649+ self.step = step650+651+ def get_items(self):652+ return [self.start, self.stop, self.step]653+654+ def __repr__(self):655+ return 'SliceExpression(%r, %r, %r)' % (656+ self.start,657+ self.stop,658+ self.step659+ )660+661+662+class TupleExpression(Expression):663+ """664+ For loop unpacking and some other things like multiple arguments665+ for subscripts.666+ """667+668+ def __init__(self, items, lineno=None, filename=None):669+ Expression.__init__(self, lineno, filename)670+ self.items = items671+672+ def get_items(self):673+ return list(self.items)674+675+ def allows_assignments(self):676+ for item in self.items:677+ if not item.allows_assignments():678+ return False679+ return True680+681+ def __repr__(self):682+ return 'TupleExpression(%r)' % (self.items,)683+684+685+class ConcatExpression(Expression):686+ """687+ For {{ foo ~ bar }}. Because of various reasons (especially because688+ unicode conversion takes place for the left and right expression and689+ is better optimized that way)690+ """691+692+ def __init__(self, args, lineno=None, filename=None):693+ Expression.__init__(self, lineno, filename)694+ self.args = args695+696+ def get_items(self):697+ return list(self.args)698+699+ def __repr__(self):700+ return 'ConcatExpression(%r)' % (self.items,)701+702+703+class CompareExpression(Expression):704+ """705+ {{ foo == bar }}, {{ foo >= bar }} etc.706+ """707+708+ def __init__(self, expr, ops, lineno=None, filename=None):709+ Expression.__init__(self, lineno, filename)710+ self.expr = expr711+ self.ops = ops712+713+ def get_items(self):714+ return [self.expr] + list(chain(*self.ops))715+716+ def __repr__(self):717+ return 'CompareExpression(%r, %r)' % (718+ self.expr,719+ self.ops720+ )721+722+723+class MulExpression(BinaryExpression):724+ """725+ {{ foo * bar }}726+ """727+728+729+class DivExpression(BinaryExpression):730+ """731+ {{ foo / bar }}732+ """733+734+735+class FloorDivExpression(BinaryExpression):736+ """737+ {{ foo // bar }}738+ """739+740+741+class AddExpression(BinaryExpression):742+ """743+ {{ foo + bar }}744+ """745+746+747+class SubExpression(BinaryExpression):748+ """749+ {{ foo - bar }}750+ """751+752+753+class ModExpression(BinaryExpression):754+ """755+ {{ foo % bar }}756+ """757+758+759+class PowExpression(BinaryExpression):760+ """761+ {{ foo ** bar }}762+ """763+764+765+class AndExpression(BinaryExpression):766+ """767+ {{ foo and bar }}768+ """769+770+771+class OrExpression(BinaryExpression):772+ """773+ {{ foo or bar }}774+ """775+776+777+class NotExpression(UnaryExpression):778+ """779+ {{ not foo }}780+ """781+782+783+class NegExpression(UnaryExpression):784+ """785+ {{ -foo }}786+ """787+788+789+class PosExpression(UnaryExpression):790+ """791+ {{ +foo }}792+ """modified:jinja/parser.py+976 added-630 removed
12 unmodified lines13 14 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16 """17-from compiler import ast, parse17 from jinja import nodes18 from jinja.datastructure import StateTest19 from jinja.exceptions import TemplateSyntaxError20 from jinja.utils import set2 unmodified lines23 __all__ = ['Parser']24 25 26 # general callback functions for the parser28-end_of_block = StateTest.expect_token('block_end', 'end of block tag')29-end_of_variable = StateTest.expect_token('variable_end', 'end of variable')30-end_of_comment = StateTest.expect_token('comment_end', 'end of comment')27+end_of_block = StateTest.expect_token('block_end',28+ msg='expected end of block tag')29+end_of_variable = StateTest.expect_token('variable_end',30+ msg='expected end of variable')31+end_of_comment = StateTest.expect_token('comment_end',32+ msg='expected end of comment')33 34 # internal tag callbacks33-switch_for = StateTest.expect_name('else', 'endfor')34-end_of_for = StateTest.expect_name('endfor')35-switch_if = StateTest.expect_name('else', 'elif', 'endif')36-end_of_if = StateTest.expect_name('endif')37-end_of_filter = StateTest.expect_name('endfilter')38-end_of_macro = StateTest.expect_name('endmacro')39-end_of_call = StateTest.expect_name('endcall_')40-end_of_block_tag = StateTest.expect_name('endblock')41-end_of_trans = StateTest.expect_name('endtrans')35+switch_for = StateTest.expect_token('else', 'endfor')36+end_of_for = StateTest.expect_token('endfor')37+switch_if = StateTest.expect_token('else', 'elif', 'endif')38+end_of_if = StateTest.expect_token('endif')39+end_of_filter = StateTest.expect_token('endfilter')40+end_of_macro = StateTest.expect_token('endmacro')41+end_of_call = StateTest.expect_token('endcall')42+end_of_block_tag = StateTest.expect_token('endblock')43+end_of_trans = StateTest.expect_token('endtrans')44 45+# this ends a tuple46+tuple_edge_tokens = set(['rparen', 'block_end', 'variable_end', 'in',47+ 'recursive'])48 49+50 class Parser(object):51 """52 The template parser class.53 54 Transforms sourcecode into an abstract syntax tree.55 """56 57 def __init__(self, environment, source, filename=None):52- #XXX: with Jinja 1.3 call becomes a keyword. Add it also53- # to the lexer.py file.58 self.environment = environment59 if isinstance(source, str):60 source = source.decode(environment.template_charset, 'ignore')61 if isinstance(filename, unicode):62 filename = filename.encode('utf-8')63 self.source = source64 self.filename = filename65+ self.closed = False66 62- #: if this template has a parent template it's stored here63- #: after parsing64- self.extends = None67 #: set for blocks in order to keep them unique68 self.blocks = set()69 70 #: mapping of directives that require special treatment71 self.directives = {70- 'raw': self.handle_raw_directive,71- 'for': self.handle_for_directive,72- 'if': self.handle_if_directive,73- 'cycle': self.handle_cycle_directive,74- 'set': self.handle_set_directive,75- 'filter': self.handle_filter_directive,76- 'print': self.handle_print_directive,77- 'macro': self.handle_macro_directive,78- 'call_': self.handle_call_directive,79- 'block': self.handle_block_directive,80- 'extends': self.handle_extends_directive,81- 'include': self.handle_include_directive,82- 'trans': self.handle_trans_directive72+ # "fake" directives that just trigger errors73+ 'raw': self.parse_raw_directive,74+ 'extends': self.parse_extends_directive,75+76+ # real directives77+ 'for': self.parse_for_loop,78+ 'if': self.parse_if_condition,79+ 'cycle': self.parse_cycle_directive,80+ 'call': self.parse_call_directive,81+ 'set': self.parse_set_directive,82+ 'filter': self.parse_filter_directive,83+ 'print': self.parse_print_directive,84+ 'macro': self.parse_macro_directive,85+ 'block': self.parse_block_directive,86+ 'include': self.parse_include_directive,87+ 'trans': self.parse_trans_directive88 }89 90 #: set of directives that are only available in a certain91 #: context.4 unmodified lines96 97 #: get the `no_variable_block` flag98 self.no_variable_block = self.environment.lexer.no_variable_block99 95- self.tokenstream = environment.lexer.tokenize(source, filename)100+ self.stream = environment.lexer.tokenize(source, filename)101 97- def handle_raw_directive(self, lineno, gen):102+ def parse_raw_directive(self):103 """104 Handle fake raw directive. (real raw directives are handled by105 the lexer. But if there are arguments to raw or the end tag106 is missing the parser tries to resolve this directive. In that107 case present the user a useful error message.108 """104- args = list(gen)105- if args:109+ if self.stream:110 raise TemplateSyntaxError('raw directive does not support '111 'any arguments.', lineno,112 self.filename)113 raise TemplateSyntaxError('missing end tag for raw directive.',114 lineno, self.filename)115 112- def handle_for_directive(self, lineno, gen):116+ def parse_extends_directive(self):117 """118+ Handle the extends directive used for inheritance.119+ """120+ raise TemplateSyntaxError('mispositioned extends tag. extends must '121+ 'be the first tag of a template.',122+ self.stream.lineno, self.filename)123+124+ def parse_for_loop(self):125+ """126 Handle a for directive and return a ForLoop node127 """116- recursive = []117- def wrapgen():118- """Wrap the generator to check if we have a recursive for loop."""119- for token in gen:120- if token[1:] == ('name', 'recursive'):121- try:122- item = gen.next()123- except StopIteration:124- recursive.append(True)125- return126- yield token127- yield item128- else:129- yield token130- ast = self.parse_python(lineno, wrapgen(), 'for %s:pass')128+ token = self.stream.expect('for')129+ item = self.parse_tuple_expression(simplified=True)130+ if not item.allows_assignments():131+ raise TemplateSyntaxError('cannot assign to expression',132+ token.lineno, self.filename)133+134+ self.stream.expect('in')135+ seq = self.parse_tuple_expression()136+ if self.stream.current.type == 'recursive':137+ self.stream.next()138+ recursive = True139+ else:140+ recursive = False141+ self.stream.expect('block_end')142+143 body = self.subparse(switch_for)144 145 # do we have an else section?134- if self.tokenstream.next()[2] == 'else':135- self.close_remaining_block()146+ if self.stream.current.type == 'else':147+ self.stream.next()148+ self.stream.expect('block_end')149 else_ = self.subparse(end_of_for, True)150 else:151+ self.stream.next()152 else_ = None139- self.close_remaining_block()153+ self.stream.expect('block_end')154 141- return nodes.ForLoop(lineno, ast.assign, ast.list, body, else_,142- bool(recursive))155+ return nodes.ForLoop(item, seq, body, else_, recursive,156+ token.lineno, self.filename)157 144- def handle_if_directive(self, lineno, gen):158+ def parse_if_condition(self):159 """160 Handle if/else blocks.161 """148- ast = self.parse_python(lineno, gen, 'if %s:pass')149- tests = [(ast.tests[0][0], self.subparse(switch_if))]162+ token = self.stream.expect('if')163+ expr = self.parse_expression()164+ self.stream.expect('block_end')165+ tests = [(expr, self.subparse(switch_if))]166+ else_ = None167 168 # do we have an else section?169 while True:153- lineno, token, needle = self.tokenstream.next()154- if needle == 'else':155- self.close_remaining_block()170+ if self.stream.current.type == 'else':171+ self.stream.next()172+ self.stream.expect('block_end')173 else_ = self.subparse(end_of_if, True)157- break158- elif needle == 'elif':159- gen = self.tokenstream.fetch_until(end_of_block, True)160- ast = self.parse_python(lineno, gen, 'if %s:pass')161- tests.append((ast.tests[0][0], self.subparse(switch_if)))174+ elif self.stream.current.type == 'elif':175+ self.stream.next()176+ expr = self.parse_expression()177+ self.stream.expect('block_end')178+ tests.append((expr, self.subparse(switch_if)))179+ continue180 else:163- else_ = None164- break165- self.close_remaining_block()181+ self.stream.next()182+ break183+ self.stream.expect('block_end')184 167- return nodes.IfCondition(lineno, tests, else_)185+ return nodes.IfCondition(tests, else_, token.lineno, self.filename)186 169- def handle_cycle_directive(self, lineno, gen):187+ def parse_cycle_directive(self):188 """189 Handle {% cycle foo, bar, baz %}.190 """173- ast = self.parse_python(lineno, gen, '_cycle((%s))')174- # ast is something like Discard(CallFunc(Name('_cycle'), ...))175- # skip that.176- return nodes.Cycle(lineno, ast.expr.args[0])191+ token = self.stream.expect('cycle')192+ expr = self.parse_tuple_expression()193+ self.stream.expect('block_end')194+ return nodes.Cycle(expr, token.lineno, self.filename)195 178- def handle_set_directive(self, lineno, gen):196+ def parse_set_directive(self):197 """198 Handle {% set foo = 'value of foo' %}.199 """182- try:183- name = gen.next()184- if name[1] != 'name' or gen.next()[1:] != ('operator', '='):185- raise ValueError()186- except (StopIteration, ValueError):187- raise TemplateSyntaxError('invalid syntax for set', lineno,188- self.filename)189- ast = self.parse_python(lineno, gen, '(%s)')190- # disallow keywords191- if not name[2].endswith('_'):192- raise TemplateSyntaxError('illegal use of keyword %r '193- 'as identifier in set statement.' %194- name[2], lineno, self.filename)195- return nodes.Set(lineno, str(name[2][:-1]), ast.expr)200+ token = self.stream.expect('set')201+ name = self.stream.expect('name')202+ self.test_name(name.value)203+ self.stream.expect('assign')204+ value = self.parse_expression()205+ if self.stream.current.type == 'bang':206+ self.stream.next()207+ scope_local = False208+ else:209+ scope_local = True210+ self.stream.expect('block_end')211+ return nodes.Set(name.value, value, scope_local,212+ token.lineno, self.filename)213 197- def handle_filter_directive(self, lineno, gen):214+ def parse_filter_directive(self):215 """216 Handle {% filter foo|bar %} directives.217 """201- ast = self.parse_python(lineno, gen, '_filter(dummy|%s)')218+ token = self.stream.expect('filter')219+ filters = []220+ while self.stream.current.type != 'block_end':221+ if filters:222+ self.stream.expect('pipe')223+ token = self.stream.expect('name')224+ args = []225+ if self.stream.current.type == 'lparen':226+ while self.stream.current.type != 'rparen':227+ if args:228+ self.stream.expect('comma')229+ args.append(self.parse_expression())230+ self.stream.expect('rparen')231+ filters.append((token.value, args))232+ self.stream.expect('block_end')233 body = self.subparse(end_of_filter, True)203- self.close_remaining_block()204- return nodes.Filter(lineno, body, ast.expr.args[0].nodes[1:])234+ self.stream.expect('block_end')235+ return nodes.Filter(body, filters, token.lineno, self.filename)236 206- def handle_print_directive(self, lineno, gen):237+ def parse_print_directive(self):238 """208- Handle {{ foo }} and {% print foo %}.239+ Handle {% print foo %}.240 """210- ast = self.parse_python(lineno, gen, 'print_(%s)')211- # ast is something like Discard(CallFunc(Name('print_'), ...))212- # so just use the args213- arguments = ast.expr.args214- # we only accept one argument215- if len(arguments) != 1:216- raise TemplateSyntaxError('invalid argument count for print; '217- 'print requires exactly one argument, '218- 'got %d.' % len(arguments), lineno,219- self.filename)220- return nodes.Print(lineno, arguments[0])241+ token = self.stream.expect('print')242+ expr = self.parse_tuple_expression()243+ node = nodes.Print(expr, token.lineno, self.filename)244+ self.stream.expect('block_end')245+ return node246 222- def handle_macro_directive(self, lineno, gen):247+ def parse_macro_directive(self):248 """249 Handle {% macro foo bar, baz %} as well as250 {% macro foo(bar, baz) %}.251 """227- try:228- macro_name = gen.next()229- except StopIteration:230- raise TemplateSyntaxError('macro requires a name', lineno,231- self.filename)232- if macro_name[1] != 'name':233- raise TemplateSyntaxError('expected \'name\', got %r' %234- macro_name[1], lineno,235- self.filename)236- # disallow keywords as identifiers237- elif not macro_name[2].endswith('_'):238- raise TemplateSyntaxError('illegal use of keyword %r '239- 'as macro name.' % macro_name[2],240- lineno, self.filename)252+ token = self.stream.expect('macro')253+ macro_name = self.stream.expect('name')254+ self.test_name(macro_name.value)255+ if self.stream.current.type == 'lparen':256+ self.stream.next()257+ needle_token = 'rparen'258+ else:259+ needle_token = 'block_end'260 242- # make the punctuation around arguments optional243- arg_list = list(gen)244- if arg_list and arg_list[0][1:] == ('operator', '(') and \245- arg_list[-1][1:] == ('operator', ')'):246- arg_list = arg_list[1:-1]261+ args = []262+ while self.stream.current.type != needle_token:263+ if args:264+ self.stream.expect('comma')265+ name = self.stream.expect('name').value266+ self.test_name(name)267+ if self.stream.current.type == 'assign':268+ self.stream.next()269+ default = self.parse_expression()270+ else:271+ default = None272+ args.append((name, default))273 248- ast = self.parse_python(lineno, arg_list, 'def %s(%%s):pass' %249- str(macro_name[2][:-1]))274+ self.stream.next()275+ if needle_token == 'rparen':276+ self.stream.expect('block_end')277+278 body = self.subparse(end_of_macro, True)251- self.close_remaining_block()279+ self.stream.expect('block_end')280 253- if ast.varargs or ast.kwargs:254- raise TemplateSyntaxError('variable length macro signature '255- 'not allowed.', lineno,256- self.filename)281+ return nodes.Macro(macro_name.value, args, body, token.lineno,282+ self.filename)257- if ast.argnames:258- defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + \259- ast.defaults260- args = []261- for idx, argname in enumerate(ast.argnames):262- # disallow keywords as argument names263- if not argname.endswith('_'):264- raise TemplateSyntaxError('illegal use of keyword %r '265- 'as macro argument.' % argname,266- lineno, self.filename)267- args.append((argname[:-1], defaults[idx]))268- else:269- args = None270- return nodes.Macro(lineno, ast.name, args, body)283 272- def handle_call_directive(self, lineno, gen):284+ def parse_call_directive(self):285 """286 Handle {% call foo() %}...{% endcall %}287 """276- expr = self.parse_python(lineno, gen, '(%s)').expr277- if expr.__class__ is not ast.CallFunc:278- raise TemplateSyntaxError('call requires a function or macro '279- 'call as only argument.', lineno,280- self.filename)288+ token = self.stream.expect('call')289+ expr = self.parse_call_expression()290+ self.stream.expect('block_end')291 body = self.subparse(end_of_call, True)282- self.close_remaining_block()283- return nodes.Call(lineno, expr, body)292+ self.stream.expect('block_end')293+ return nodes.Call(expr, body, token.lineno, self.filename)294 285- def handle_block_directive(self, lineno, gen):295+ def parse_block_directive(self):296 """297 Handle block directives used for inheritance.298 """289- tokens = list(gen)290- if not tokens:291- raise TemplateSyntaxError('block requires a name', lineno,292- self.filename)293- block_name = tokens.pop(0)294- if block_name[1] != 'name':295- raise TemplateSyntaxError('expected \'name\', got %r' %296- block_name[1], lineno, self.filename)297- # disallow keywords298- if not block_name[2].endswith('_'):299- raise TemplateSyntaxError('illegal use of keyword %r '300- 'as block name.' % block_name[2],301- lineno, self.filename)302- name = block_name[2][:-1]299+ token = self.stream.expect('block')300+ name = self.stream.expect('name').value301+302 # check if this block does not exist by now.303 if name in self.blocks:304 raise TemplateSyntaxError('block %r defined twice' %305 name, lineno, self.filename)306 self.blocks.add(name)307 309- if tokens:310- body = nodes.NodeList(lineno, [nodes.Print(lineno,311- self.parse_python(lineno, tokens, '(%s)').expr)])308+ if self.stream.current.type != 'block_end':309+ lineno = self.stream.lineno310+ body = nodes.NodeList([self.parse_variable_tag()], lineno,311+ self.filename)312+ self.stream.expect('block_end')313 else:314 # otherwise parse the body and attach it to the block315+ self.stream.expect('block_end')316 body = self.subparse(end_of_block_tag, True)315- self.close_remaining_block()316- return nodes.Block(lineno, name, body)317+ self.stream.expect('block_end')318+ return nodes.Block(name, body, token.lineno, self.filename)319 318- def handle_extends_directive(self, lineno, gen):320+ def parse_include_directive(self):321 """320- Handle the extends directive used for inheritance.321- """322- tokens = list(gen)323- if len(tokens) != 1 or tokens[0][1] != 'string':324- raise TemplateSyntaxError('extends requires a string', lineno,325- self.filename)326- if self.extends is not None:327- raise TemplateSyntaxError('extends called twice', lineno,328- self.filename)329- self.extends = nodes.Extends(lineno, tokens[0][2][1:-1])330-331- def handle_include_directive(self, lineno, gen):332- """322 Handle the include directive used for template inclusion.323 """335- tokens = list(gen)336- # hardcoded include (faster because copied into the bytecode)337- if len(tokens) == 1 and tokens[0][1] == 'string':338- return nodes.Include(lineno, str(tokens[0][2][1:-1]))339- raise TemplateSyntaxError('invalid syntax for include '340- 'directive. Requires a hardcoded '341- 'string', lineno,342- self.filename)324+ token = self.stream.expect('include')325+ template = self.stream.expect('string').value326+ self.stream.expect('block_end')327+ return nodes.Include(template, token.lineno, self.filename)328 344- def handle_trans_directive(self, lineno, gen):329+ def parse_trans_directive(self):330 """331 Handle translatable sections.332 """348- def process_variable(lineno, token, name):349- if token != 'name':350- raise TemplateSyntaxError('can only use variable not '351- 'constants or expressions in '352- 'translation variable blocks.',353- lineno, self.filename)354- # plural name without trailing "_"? that's a keyword355- if not name.endswith('_'):356- raise TemplateSyntaxError('illegal use of keyword \'%s\' as '357- 'identifier in translatable block.'358- % name, lineno, self.filename)359- name = name[:-1]360- if name not in replacements:361- raise TemplateSyntaxError('unregistered translation variable'362- " '%s'." % name, lineno,363- self.filename)364- # check that we don't have an expression here, thus the365- # next token *must* be a variable_end token (or a366- # block_end token when in no_variable_block mode)367- next_token = self.tokenstream.next()[1]368- if next_token != 'variable_end' and not \369- (self.no_variable_block and next_token == 'block_end'):370- raise TemplateSyntaxError('you cannot use variable '371- 'expressions inside translatable '372- 'tags. apply filters in the '373- 'trans header.', lineno,374- self.filename)375- buf.append('%%(%s)s' % name)333+ trans_token = self.stream.expect('trans')334 377- # save the initial line number for the resulting node378- flineno = lineno379- try:380- # check for string translations381- try:382- lineno, token, data = gen.next()383- except StopIteration:384- # no dynamic replacements385- replacements = {}386- first_var = None335+ # string based translations {% trans "foo" %}336+ if self.stream.current.type == 'string':337+ text = self.stream.expect('string')338+ self.stream.expect('block_end')339+ return nodes.Trans(text.value, None, None, None,340+ trans_token.lineno, self.filename)341+342+ # block based translations343+ replacements = {}344+ plural_var = None345+346+ while self.stream.current.type != 'block_end':347+ if replacements:348+ self.stream.expect('comma')349+ name = self.stream.expect('name')350+ if self.stream.current.type == 'assign':351+ self.stream.next()352+ value = self.parse_expression()353 else:388- if token == 'string':389- # check that there are not any more elements390- try:391- gen.next()392- except StopIteration:393- # XXX: this looks fishy394- data = data[1:-1].encode('utf-8').decode('string-escape')395- return nodes.Trans(lineno, data.decode('utf-8'), None,396- None, None)397- raise TemplateSyntaxError('string based translations '398- 'require at most one argument.',399- lineno, self.filename)400- # create a new generator with the popped item as first one401- def wrapgen(oldgen):402- yield lineno, token, data403- for item in oldgen:404- yield item405- gen = wrapgen(gen)354+ value = nodes.NameExpression(name.value, name.lineno,355+ self.filename)356+ if name.value in replacements:357+ raise TemplateSyntaxError('translation variable %r '358+ 'is defined twice' % name.value,359+ name.lineno, self.filename)360+ replacements[name.value] = value361+ if plural_var is None:362+ plural_var = name.value363+ self.stream.expect('block_end')364 407- # block based translations408- first_var = None409- replacements = {}410- for arg in self.parse_python(lineno, gen,411- '_trans(%s)').expr.args:412- if arg.__class__ not in (ast.Keyword, ast.Name):413- raise TemplateSyntaxError('translation tags need expl'414- 'icit names for values.',415- lineno, self.filename)416- # disallow keywords417- if not arg.name.endswith('_'):418- raise TemplateSyntaxError("illegal use of keyword '%s"419- '\' as identifier.' %420- arg.name, lineno,421- self.filename)422- # remove the last "_" before writing423- name = arg.name[:-1]424- if first_var is None:425- first_var = name426- # if it's a keyword use the expression as value,427- # otherwise just reuse the name node.428- replacements[name] = getattr(arg, 'expr', arg)365+ def process_variable():366+ var_name = self.stream.expect('name')367+ if var_name.value not in replacements:368+ raise TemplateSyntaxError('unregistered translation variable'369+ " '%s'." % var_name.value,370+ var_name.lineno, self.filename)371+ buf.append('%%(%s)s' % var_name.value)372 430- # look for endtrans/pluralize431- buf = singular = []432- plural = indicator = None373+ buf = singular = []374+ plural = None375 434- while True:435- lineno, token, data = self.tokenstream.next()436- # comments437- if token == 'comment_begin':438- self.tokenstream.drop_until(end_of_comment, True)439- # nested variables440- elif token == 'variable_begin':441- process_variable(*self.tokenstream.next())442- # nested blocks are not supported, just look for end blocks443- elif token == 'block_begin':444- _, block_token, block_name = self.tokenstream.next()445- if block_token != 'name' or \446- block_name not in ('pluralize', 'endtrans'):447- # if we have a block name check if it's a real448- # directive or a not existing one (which probably449- # is a typo)450- if block_token == 'name':451- # if this block is a context directive the452- # designer has probably misspelled endtrans453- # with endfor or something like that. raise454- # a nicer error message455- if block_name in self.context_directives:456- raise TemplateSyntaxError('unexpected directi'457- "ve '%s' found" %458- block_name, lineno,459- self.filename)460- # if's not a directive, probably misspelled461- # endtrans. Raise the "unknown directive"462- # exception rather than the "not allowed"463- if block_name not in self.directives:464- if block_name.endswith('_'):465- # if we don't have a variable block we466- # have to process this as variable.467- if self.no_variable_block:468- process_variable(_, block_token,469- block_name)470- continue471- block_name = block_name[:-1]472- raise TemplateSyntaxError('unknown directive'473- " '%s'" % block_name,474- lineno,475- self.filename)476- # we have something different and are in the477- # special no_variable_block mode. process this478- # as variable479- elif self.no_variable_block:480- process_variable(_, block_token, block_name)481- continue482- # if it's indeed a known directive we better483- # raise an exception informing the user about484- # the fact that we don't support blocks in485- # translatable sections.486- raise TemplateSyntaxError('directives in translatable'487- ' sections are not '488- 'allowed', lineno,489- self.filename)490- # pluralize491- if block_name == 'pluralize':492- if plural is not None:493- raise TemplateSyntaxError('translation blocks '494- 'support at most one '495- 'plural block',496- lineno, self.filename)497- _, plural_token, plural_name = self.tokenstream.next()498- if plural_token == 'block_end':499- indicator = first_var500- elif plural_token == 'name':501- # disallow keywords502- if not plural_name.endswith('_'):503- raise TemplateSyntaxError('illegal use of '504- "keyword '%s' as "505- 'identifier.' %506- plural_name,507- lineno,508- self.filename)509- plural_name = plural_name[:-1]510- if plural_name not in replacements:511- raise TemplateSyntaxError('unregistered '512- 'translation '513- "variable '%s'" %514- plural_name, lineno,515- self.filename)516- elif self.tokenstream.next()[1] != 'block_end':517- raise TemplateSyntaxError('pluralize takes '518- 'at most one '519- 'argument', lineno,520- self.filename)521- indicator = plural_name522- else:523- raise TemplateSyntaxError('pluralize requires no '524- 'argument or a variable'525- ' name.', lineno,526- self.filename)527- plural = buf = []528- # end translation529- elif block_name == 'endtrans':530- self.close_remaining_block()531- break532- # normal data376+ while True:377+ token = self.stream.current378+ if token.type == 'data':379+ buf.append(token.value.replace('%', '%%'))380+ self.stream.next()381+ elif token.type == 'variable_begin':382+ self.stream.next()383+ process_variable()384+ self.stream.expect('variable_end')385+ elif token.type == 'block_begin':386+ self.stream.next()387+ if plural is None and self.stream.current.type == 'pluralize':388+ self.stream.next()389+ if self.stream.current.type == 'name':390+ plural_var = self.stream.expect('name').value391+ plural = buf = []392+ elif self.stream.current.type == 'endtrans':393+ self.stream.next()394+ self.stream.expect('block_end')395+ break396 else:534- buf.append(data.replace('%', '%%'))397+ if self.no_variable_block:398+ process_variable()399+ else:400+ raise TemplateSyntaxError('blocks are not allowed '401+ 'in trans tags',402+ self.stream.lineno,403+ self.filename)404+ self.stream.expect('block_end')405+ else:406+ assert False, 'something very strange happened'407 536- except StopIteration:537- raise TemplateSyntaxError('unexpected end of translation section',538- self.tokenstream.last[0], self.filename)539-408 singular = u''.join(singular)409 if plural is not None:410 plural = u''.join(plural)543- return nodes.Trans(flineno, singular, plural, indicator,544- replacements or None)411+ return nodes.Trans(singular, plural, plural_var, replacements,412+ trans_token.lineno, self.filename)413 546- def parse_python(self, lineno, gen, template):414+ def parse_expression(self):415 """548- Convert the passed generator into a flat string representing549- python sourcecode and return an ast node or raise a550- TemplateSyntaxError.416+ Parse one expression from the stream.417 """552- tokens = []553- for t_lineno, t_token, t_data in gen:554- if t_token == 'string':555- # because some libraries have problems with unicode556- # objects we do some lazy unicode processing here.557- # if a string is ASCII only we yield it as string558- # in other cases as unicode. This works around559- # problems with datetimeobj.strftime()560- # also escape newlines in strings561- t_data = t_data.replace('\n', '\\n')562- try:563- str(t_data)564- except UnicodeError:565- tokens.append('u' + t_data)566- continue567- tokens.append(t_data)568- source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).569- encode('utf-8'))570- try:571- ast = parse(source, 'exec')572- except SyntaxError, e:573- raise TemplateSyntaxError('invalid syntax in expression',574- lineno + (e.lineno or 0),418+ return self.parse_conditional_expression()419+420+ def parse_subscribed_expression(self):421+ """422+ Like parse_expression but parses slices too. Because this423+ parsing function requires a border the two tokens rbracket424+ and comma mark the end of the expression in some situations.425+ """426+ lineno = self.stream.lineno427+428+ if self.stream.current.type == 'colon':429+ self.stream.next()430+ args = [None]431+ else:432+ node = self.parse_expression()433+ if self.stream.current.type != 'colon':434+ return node435+ self.stream.next()436+ args = [node]437+438+ if self.stream.current.type == 'colon':439+ args.append(None)440+ elif self.stream.current.type not in ('rbracket', 'comma'):441+ args.append(self.parse_expression())442+ else:443+ args.append(None)444+445+ if self.stream.current.type == 'colon':446+ self.stream.next()447+ if self.stream.current.type not in ('rbracket', 'comma'):448+ args.append(self.parse_expression())449+ else:450+ args.append(None)451+ else:452+ args.append(None)453+454+ return nodes.SliceExpression(*(args + [lineno, self.filename]))455+456+ def parse_conditional_expression(self):457+ """458+ Parse a conditional expression (foo if bar else baz)459+ """460+ lineno = self.stream.lineno461+ expr1 = self.parse_or_expression()462+ while self.stream.current.type == 'if':463+ self.stream.next()464+ expr2 = self.parse_or_expression()465+ self.stream.expect('else')466+ expr3 = self.parse_conditional_expression()467+ expr1 = nodes.ConditionalExpression(expr2, expr1, expr3,468+ lineno, self.filename)469+ lineno = self.stream.lineno470+ return expr1471+472+ def parse_or_expression(self):473+ """474+ Parse something like {{ foo or bar }}.475+ """476+ lineno = self.stream.lineno477+ left = self.parse_and_expression()478+ while self.stream.current.type == 'or':479+ self.stream.next()480+ right = self.parse_and_expression()481+ left = nodes.OrExpression(left, right, lineno, self.filename)482+ lineno = self.stream.lineno483+ return left484+485+ def parse_and_expression(self):486+ """487+ Parse something like {{ foo and bar }}.488+ """489+ lineno = self.stream.lineno490+ left = self.parse_compare_expression()491+ while self.stream.current.type == 'and':492+ self.stream.next()493+ right = self.parse_compare_expression()494+ left = nodes.AndExpression(left, right, lineno, self.filename)495+ lineno = self.stream.lineno496+ return left497+498+ def parse_compare_expression(self):499+ """500+ Parse something like {{ foo == bar }}.501+ """502+ known_operators = set(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])503+ lineno = self.stream.lineno504+ expr = self.parse_add_expression()505+ ops = []506+ while True:507+ if self.stream.current.type in known_operators:508+ op = self.stream.current.type509+ self.stream.next()510+ ops.append([op, self.parse_add_expression()])511+ lineno = self.stream.lineno512+ elif self.stream.current.type == 'not' and \513+ self.stream.look().type == 'in':514+ self.stream.skip(2)515+ ops.append(['not in', self.parse_add_expression()])516+ else:517+ break518+ if not ops:519+ return expr520+ return nodes.CompareExpression(expr, ops)521+522+ def parse_add_expression(self):523+ """524+ Parse something like {{ foo + bar }}.525+ """526+ lineno = self.stream.lineno527+ left = self.parse_sub_expression()528+ while self.stream.current.type == 'add':529+ self.stream.next()530+ right = self.parse_sub_expression()531+ left = nodes.AddExpression(left, right, lineno, self.filename)532+ lineno = self.stream.lineno533+ return left534+535+ def parse_sub_expression(self):536+ """537+ Parse something like {{ foo - bar }}.538+ """539+ lineno = self.stream.lineno540+ left = self.parse_concat_expression()541+ while self.stream.current.type == 'sub':542+ self.stream.next()543+ right = self.parse_concat_expression()544+ left = nodes.SubExpression(left, right, lineno, self.filename)545+ lineno = self.stream.lineno546+ return left547+548+ def parse_concat_expression(self):549+ """550+ Parse something like {{ foo ~ bar }}.551+ """552+ lineno = self.stream.lineno553+ args = [self.parse_mul_expression()]554+ while self.stream.current.type == 'tilde':555+ self.stream.next()556+ args.append(self.parse_mul_expression())557+ if len(args) == 1:558+ return args[0]559+ return nodes.ConcatExpression(args, lineno, self.filename)560+561+ def parse_mul_expression(self):562+ """563+ Parse something like {{ foo * bar }}.564+ """565+ lineno = self.stream.lineno566+ left = self.parse_div_expression()567+ while self.stream.current.type == 'mul':568+ self.stream.next()569+ right = self.parse_div_expression()570+ left = nodes.MulExpression(left, right, lineno, self.filename)571+ lineno = self.stream.lineno572+ return left573+574+ def parse_div_expression(self):575+ """576+ Parse something like {{ foo / bar }}.577+ """578+ lineno = self.stream.lineno579+ left = self.parse_floor_div_expression()580+ while self.stream.current.type == 'div':581+ self.stream.next()582+ right = self.parse_floor_div_expression()583+ left = nodes.DivExpression(left, right, lineno, self.filename)584+ lineno = self.stream.lineno585+ return left586+587+ def parse_floor_div_expression(self):588+ """589+ Parse something like {{ foo // bar }}.590+ """591+ lineno = self.stream.lineno592+ left = self.parse_mod_expression()593+ while self.stream.current.type == 'floordiv':594+ self.stream.next()595+ right = self.parse_mod_expression()596+ left = nodes.FloorDivExpression(left, right, lineno, self.filename)597+ lineno = self.stream.lineno598+ return left599+600+ def parse_mod_expression(self):601+ """602+ Parse something like {{ foo % bar }}.603+ """604+ lineno = self.stream.lineno605+ left = self.parse_pow_expression()606+ while self.stream.current.type == 'mod':607+ self.stream.next()608+ right = self.parse_pow_expression()609+ left = nodes.ModExpression(left, right, lineno, self.filename)610+ lineno = self.stream.lineno611+ return left612+613+ def parse_pow_expression(self):614+ """615+ Parse something like {{ foo ** bar }}.616+ """617+ lineno = self.stream.lineno618+ left = self.parse_unary_expression()619+ while self.stream.current.type == 'pow':620+ self.stream.next()621+ right = self.parse_unary_expression()622+ left = nodes.PowExpression(left, right, lineno, self.filename)623+ lineno = self.stream.lineno624+ return left625+626+ def parse_unary_expression(self):627+ """628+ Parse all kinds of unary expressions.629+ """630+ if self.stream.current.type == 'not':631+ return self.parse_not_expression()632+ elif self.stream.current.type == 'sub':633+ return self.parse_neg_expression()634+ elif self.stream.current.type == 'add':635+ return self.parse_pos_expression()636+ return self.parse_primary_expression()637+638+ def parse_not_expression(self):639+ """640+ Parse something like {{ not foo }}.641+ """642+ token = self.stream.expect('not')643+ node = self.parse_unary_expression()644+ return nodes.NotExpression(node, token.lineno, self.filename)645+646+ def parse_neg_expression(self):647+ """648+ Parse something like {{ -foo }}.649+ """650+ token = self.stream.expect('sub')651+ node = self.parse_unary_expression()652+ return nodes.NegExpression(node, token.lineno, self.filename)653+654+ def parse_pos_expression(self):655+ """656+ Parse something like {{ +foo }}.657+ """658+ token = self.stream.expect('add')659+ node = self.parse_unary_expression()660+ return nodes.PosExpression(node, token.lineno, self.filename)661+662+ def parse_primary_expression(self, parse_postfix=True):663+ """664+ Parse a primary expression such as a name or literal.665+ """666+ current = self.stream.current667+ if current.type == 'name':668+ if current.value in ('true', 'false'):669+ node = self.parse_bool_expression()670+ elif current.value == 'none':671+ node = self.parse_none_expression()672+ elif current.value == 'undefined':673+ node = self.parse_undefined_expression()674+ elif current.value == '_':675+ node = self.parse_gettext_call()676+ else:677+ node = self.parse_name_expression()678+ elif current.type in ('integer', 'float'):679+ node = self.parse_number_expression()680+ elif current.type == 'string':681+ node = self.parse_string_expression()682+ elif current.type == 'regex':683+ node = self.parse_regex_expression()684+ elif current.type == 'lparen':685+ node = self.parse_paren_expression()686+ elif current.type == 'lbracket':687+ node = self.parse_list_expression()688+ elif current.type == 'lbrace':689+ node = self.parse_dict_expression()690+ elif current.type == 'at':691+ node = self.parse_set_expression()692+ else:693+ raise TemplateSyntaxError("unexpected token '%s'" %694+ self.stream.current,695+ self.stream.current.lineno,696 self.filename)576- assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' % \577- len(ast.node.nodes)578- result = ast.node.nodes[0]579- nodes.inc_lineno(lineno, result)580- return result697+ if parse_postfix:698+ node = self.parse_postfix_expression(node)699+ return node700 582- def parse(self):701+ def parse_tuple_expression(self, enforce=False, simplified=False):702 """584- Parse the template and return a Template node. Also unescape the585- names escaped by the lexer (unused python keywords) and set the586- filename attributes for all nodes in the tree.703+ Parse multiple expressions into a tuple. This can also return704+ just one expression which is not a tuple. If you want to enforce705+ a tuple, pass it enforce=True.706 """588- body = self.subparse(None)589- def walk(nodes_, stack):590- for node in nodes_:591- # all names excluding keywords have an trailing underline.592- # if we find a name without trailing underline that's a593- # keyword and this code raises an error. else strip the594- # underline again595- if node.__class__ in (ast.AssName, ast.Name, ast.Keyword):596- if not node.name.endswith('_'):597- raise TemplateSyntaxError('illegal use of keyword %r '598- 'as identifier.' %599- node.name, node.lineno,600- self.filename)601- node.name = node.name[:-1]602- # same for attributes603- elif node.__class__ is ast.Getattr:604- if not node.attrname.endswith('_'):605- raise TemplateSyntaxError('illegal use of keyword %r '606- 'as attribute name.' %607- node.name, node.lineno,608- self.filename)609- node.attrname = node.attrname[:-1]610- # if we have a ForLoop we ensure that nobody patches existing611- # object using "for foo.bar in seq"612- elif node.__class__ is nodes.ForLoop:613- def check(node):614- if node.__class__ not in (ast.AssName, ast.AssTuple):615- raise TemplateSyntaxError('can\'t assign to '616- 'expression.',617- node.lineno,618- self.filename)619- for n in node.getChildNodes():620- check(n)621- check(node.item)622- # ensure that in child templates block are either top level623- # or located inside of another block tag.624- elif self.extends is not None and \625- node.__class__ is nodes.Block:626- if stack[-1] is not body:627- for n in stack:628- if n.__class__ is nodes.Block:629- break630- else:631- raise TemplateSyntaxError('misplaced block %r, '632- 'blocks in child '633- 'templates must be '634- 'either top level or '635- 'located in a block '636- 'tag.' % node.name,637- node.lineno,638- self.filename)639- # now set the filename and continue working on the childnodes640- node.filename = self.filename641- stack.append(node)642- walk(node.getChildNodes(), stack)643- stack.pop()644- walk([body], [body])645- return nodes.Template(self.filename, body, self.extends)707+ lineno = self.stream.lineno708+ if simplified:709+ parse = self.parse_primary_expression710+ else:711+ parse = self.parse_expression712+ args = []713+ is_tuple = False714+ while True:715+ if args:716+ self.stream.expect('comma')717+ if self.stream.current.type in tuple_edge_tokens:718+ break719+ args.append(parse())720+ if self.stream.current.type == 'comma':721+ is_tuple = True722+ else:723+ break724+ if not is_tuple and args:725+ if enforce:726+ raise TemplateSyntaxError('tuple expected', lineno,727+ self.filename)728+ return args[0]729+ return nodes.TupleExpression(args, lineno, self.filename)730 731+ def parse_bool_expression(self):732+ """733+ Parse a boolean literal.734+ """735+ token = self.stream.expect('name')736+ if token.value == 'true':737+ value = True738+ elif token.value == 'false':739+ value = False740+ else:741+ raise TemplateSyntaxError("expected boolean literal",742+ token.lineno, self.filename)743+ return nodes.ConstantExpression(value, token.lineno, self.filename)744+745+ def parse_none_expression(self):746+ """747+ Parse a none literal.748+ """749+ token = self.stream.expect('name', 'none')750+ return nodes.ConstantExpression(None, token.lineno, self.filename)751+752+ def parse_undefined_expression(self):753+ """754+ Parse an undefined literal.755+ """756+ token = self.stream.expect('name', 'undefined')757+ return nodes.UndefinedExpression(token.lineno, self.filename)758+759+ def parse_gettext_call(self):760+ """761+ parse {{ _('foo') }}.762+ """763+ # XXX: check if only one argument was passed and if764+ # it is a string literal. Maybe that should become a special765+ # expression anyway.766+ token = self.stream.expect('name', '_')767+ node = nodes.NameExpression(token.value, token.lineno, self.filename)768+ return self.parse_call_expression(node)769+770+ def parse_name_expression(self):771+ """772+ Parse any name.773+ """774+ token = self.stream.expect('name')775+ self.test_name(token.value)776+ return nodes.NameExpression(token.value, token.lineno, self.filename)777+778+ def parse_number_expression(self):779+ """780+ Parse a number literal.781+ """782+ token = self.stream.current783+ if token.type not in ('integer', 'float'):784+ raise TemplateSyntaxError('integer or float literal expected',785+ token.lineno, self.filename)786+ self.stream.next()787+ return nodes.ConstantExpression(token.value, token.lineno, self.filename)788+789+ def parse_string_expression(self):790+ """791+ Parse a string literal.792+ """793+ token = self.stream.expect('string')794+ return nodes.ConstantExpression(token.value, token.lineno, self.filename)795+796+ def parse_regex_expression(self):797+ """798+ Parse a regex literal.799+ """800+ token = self.stream.expect('regex')801+ return nodes.RegexExpression(token.value, token.lineno, self.filename)802+803+ def parse_paren_expression(self):804+ """805+ Parse a parenthized expression.806+ """807+ self.stream.expect('lparen')808+ try:809+ return self.parse_tuple_expression()810+ finally:811+ self.stream.expect('rparen')812+813+ def parse_list_expression(self):814+ """815+ Parse something like {{ [1, 2, "three"] }}816+ """817+ token = self.stream.expect('lbracket')818+ items = []819+ while self.stream.current.type != 'rbracket':820+ if items:821+ self.stream.expect('comma')822+ if self.stream.current.type == 'rbracket':823+ break824+ items.append(self.parse_expression())825+ self.stream.expect('rbracket')826+827+ return nodes.ListExpression(items, token.lineno, self.filename)828+829+ def parse_dict_expression(self):830+ """831+ Parse something like {{ {1: 2, 3: 4} }}832+ """833+ token = self.stream.expect('lbrace')834+ items = []835+ while self.stream.current.type != 'rbrace':836+ if items:837+ self.stream.expect('comma')838+ if self.stream.current.type == 'rbrace':839+ break840+ key = self.parse_expression()841+ self.stream.expect('colon')842+ value = self.parse_expression()843+ items.append((key, value))844+ self.stream.expect('rbrace')845+846+ return nodes.DictExpression(items, token.lineno, self.filename)847+848+ def parse_set_expression(self):849+ """850+ Parse something like {{ @(1, 2, 3) }}.851+ """852+ token = self.stream.expect('at')853+ self.stream.expect('lparen')854+ items = []855+ while self.stream.current.type != 'rparen':856+ if items:857+ self.stream.expect('comma')858+ if self.stream.current.type == 'rparen':859+ break860+ items.append(self.parse_expression())861+ self.stream.expect('rparen')862+863+ return nodes.SetExpression(items, token.lineno, self.filename)864+865+ def parse_postfix_expression(self, node):866+ """867+ Parse a postfix expression such as a filter statement or a868+ function call.869+ """870+ while True:871+ current = self.stream.current.type872+ if current == 'dot' or current == 'lbracket':873+ node = self.parse_subscript_expression(node)874+ elif current == 'lparen':875+ node = self.parse_call_expression(node)876+ elif current == 'pipe':877+ node = self.parse_filter_expression(node)878+ elif current == 'is':879+ node = self.parse_test_expression(node)880+ else:881+ break882+ return node883+884+ def parse_subscript_expression(self, node):885+ """886+ Parse a subscript statement. Gets attributes and items from an887+ object.888+ """889+ lineno = self.stream.lineno890+ if self.stream.current.type == 'dot':891+ self.stream.next()892+ token = self.stream.current893+ if token.type in ('name', 'integer'):894+ arg = nodes.ConstantExpression(token.value, token.lineno,895+ self.filename)896+ else:897+ raise TemplateSyntaxError('expected name or number',898+ token.lineno, self.filename)899+ self.stream.next()900+ elif self.stream.current.type == 'lbracket':901+ self.stream.next()902+ args = []903+ while self.stream.current.type != 'rbracket':904+ if args:905+ self.stream.expect('comma')906+ args.append(self.parse_subscribed_expression())907+ self.stream.expect('rbracket')908+ if len(args) == 1:909+ arg = args[0]910+ else:911+ arg = nodes.TupleExpression(args, lineno, self.filename)912+ else:913+ raise TemplateSyntaxError('expected subscript expression',914+ self.lineno, self.filename)915+ return nodes.SubscriptExpression(node, arg, lineno, self.filename)916+917+ def parse_call_expression(self, node=None):918+ """919+ Parse a call.920+ """921+ if node is None:922+ node = self.parse_primary_expression(parse_postfix=False)923+ token = self.stream.expect('lparen')924+ args = []925+ kwargs = []926+ dyn_args = None927+ dyn_kwargs = None928+ require_comma = False929+930+ def ensure(expr):931+ if not expr:932+ raise TemplateSyntaxError('invalid syntax for function '933+ 'declaration', token.lineno,934+ self.filename)935+936+ while self.stream.current.type != 'rparen':937+ if require_comma:938+ self.stream.expect('comma')939+ if self.stream.current.type == 'mul':940+ ensure(dyn_args is None and dyn_kwargs is None)941+ self.stream.next()942+ dyn_args = self.parse_expression()943+ elif self.stream.current.type == 'pow':944+ ensure(dyn_kwargs is None)945+ self.stream.next()946+ dyn_kwargs = self.parse_expression()947+ else:948+ ensure(dyn_args is None and dyn_kwargs is None)949+ if self.stream.current.type == 'name' and \950+ self.stream.look().type == 'assign':951+ key = self.stream.current.value952+ self.stream.skip(2)953+ kwargs.append((key, self.parse_expression()))954+ else:955+ ensure(not kwargs)956+ args.append(self.parse_expression())957+958+ require_comma = True959+ self.stream.expect('rparen')960+961+ return nodes.CallExpression(node, args, kwargs, dyn_args,962+ dyn_kwargs, token.lineno,963+ self.filename)964+965+ def parse_filter_expression(self, node):966+ """967+ Parse filter calls.968+ """969+ lineno = self.stream.lineno970+ filters = []971+ while self.stream.current.type == 'pipe':972+ self.stream.next()973+ token = self.stream.expect('name')974+ args = []975+ if self.stream.current.type == 'lparen':976+ self.stream.next()977+ while self.stream.current.type != 'rparen':978+ if args:979+ self.stream.expect('comma')980+ args.append(self.parse_expression())981+ self.stream.expect('rparen')982+ filters.append((token.value, args))983+ return nodes.FilterExpression(node, filters, lineno, self.filename)984+985+ def parse_test_expression(self, node):986+ """987+ Parse test calls.988+ """989+ token = self.stream.expect('is')990+ if self.stream.current.type == 'not':991+ self.stream.next()992+ negated = True993+ else:994+ negated = False995+ name = self.stream.expect('name').value996+ args = []997+ if self.stream.current.type == 'lparen':998+ self.stream.next()999+ while self.stream.current.type != 'rparen':1000+ if args:1001+ self.stream.expect('comma')1002+ args.append(self.parse_expression())1003+ self.stream.expect('rparen')1004+ elif self.stream.current.type in ('name', 'string', 'integer',1005+ 'float', 'lparen', 'lbracket',1006+ 'lbrace', 'regex'):1007+ args.append(self.parse_expression())1008+ node = nodes.TestExpression(node, name, args, token.lineno,1009+ self.filename)1010+ if negated:1011+ node = nodes.NotExpression(node, token.lineno, self.filename)1012+ return node1013+1014+ def test_name(self, name):1015+ """1016+ Test if a name is not a special constant1017+ """1018+ if name in ('true', 'false', 'none', 'undefined', '_'):1019+ raise TemplateSyntaxError('expected name not special constant',1020+ self.stream.lineno, self.filename)1021+1022 def subparse(self, test, drop_needle=False):1023 """1024 Helper function used to parse the sourcecode until the test1025 function which is passed a tuple in the form (lineno, token, data)1026 returns True. In that case the current token is pushed back to652- the tokenstream and the generator ends.1027+ the stream and the generator ends.1028 1029 The test function is only called for the first token after a1030 block tag. Variable tags are *not* aliases for {% print %} in1031 that case.1032 1033 If drop_needle is True the needle_token is removed from the659- tokenstream.1034+ stream.1035 """661- def finish():662- """Helper function to remove unused nodelists."""663- if data_buffer:664- flush_data_buffer()665- if len(result) == 1:666- return result[0]667- return result1036+ if self.closed:1037+ raise RuntimeError('parser is closed')1038+ result = []1039+ buffer = []1040+ next = self.stream.next1041+ lineno = self.stream.lineno1042 669- def flush_data_buffer():670- """Helper function to write the contents of the buffer671- to the result nodelist."""672- format_string = []673- insertions = []674- for item in data_buffer:675- if item[0] == 'variable':676- p = self.handle_print_directive(*item[1:])677- format_string.append('%s')678- insertions.append(p)679- else:680- format_string.append(item[2].replace('%', '%%'))681- # if we do not have insertions yield it as text node682- if not insertions:683- result.append(nodes.Text(data_buffer[0][1],684- (u''.join(format_string)).replace('%%', '%')))685- # if we do not have any text data we yield some variable nodes686- elif len(insertions) == len(format_string):687- result.extend(insertions)688- # otherwise we go with a dynamic text node689- else:690- result.append(nodes.DynamicText(data_buffer[0][1],691- u''.join(format_string),692- insertions))693- # clear the buffer694- del data_buffer[:]1043+ def assemble_list():1044+ push_buffer()1045+ return nodes.NodeList(result, lineno, self.filename)1046 696- def process_variable(gen):697- data_buffer.append(('variable', lineno, tuple(gen)))1047+ def push_variable():1048+ buffer.append((True, self.parse_tuple_expression()))1049 699- lineno = self.tokenstream.last[0]700- result = nodes.NodeList(lineno)701- data_buffer = []702- for lineno, token, data in self.tokenstream:703- # comments704- if token == 'comment_begin':705- self.tokenstream.drop_until(end_of_comment, True)1050+ def push_data():1051+ buffer.append((False, self.stream.expect('data')))1052 707- # this token marks the begin or a variable section.708- # parse everything till the end of it.709- elif token == 'variable_begin':710- gen = self.tokenstream.fetch_until(end_of_variable, True)711- process_variable(gen)1053+ def push_buffer():1054+ if not buffer:1055+ return1056+ template = []1057+ variables = []1058+ for is_var, data in buffer:1059+ if is_var:1060+ template.append('%s')1061+ variables.append(data)1062+ else:1063+ template.append(data.value.replace('%', '%%'))1064+ result.append(nodes.Text(u''.join(template), variables,1065+ buffer[0][1].lineno, self.filename))1066+ del buffer[:]1067 713- # this token marks the start of a block. like for variables714- # just parse everything until the end of the block715- elif token == 'block_begin':716- # if we have something in the buffer we write the717- # data back718- if data_buffer:719- flush_data_buffer()1068+ def push_node(node):1069+ push_buffer()1070+ result.append(node)1071 721- node = None722- gen = self.tokenstream.fetch_until(end_of_block, True)723- try:724- lineno, token, data = gen.next()725- except StopIteration:726- raise TemplateSyntaxError('unexpected end of block',727- lineno, self.filename)728-729- # first token *must* be a name token730- if token != 'name':731- # well, not always. if we have a lexer without variable732- # blocks configured we process these tokens as variable733- # block.1072+ while self.stream:1073+ token_type = self.stream.current.type1074+ if token_type == 'variable_begin':1075+ next()1076+ push_variable()1077+ self.stream.expect('variable_end')1078+ elif token_type == 'block_begin':1079+ next()1080+ if test is not None and test(self.stream.current):1081+ if drop_needle:1082+ next()1083+ return assemble_list()1084+ handler = self.directives.get(self.stream.current.type)1085+ if handler is None:1086 if self.no_variable_block:735- process_variable([(lineno, token, data)] + list(gen))1087+ push_variable()1088+ self.stream.expect('block_end')1089+ elif self.stream.current.type in self.context_directives:1090+ raise TemplateSyntaxError('unexpected directive %r.' %1091+ self.stream.current.type,1092+ lineno, self.filename)1093 else:737- raise TemplateSyntaxError('unexpected %r token (%r)' %738- (token, data), lineno,739- self.filename)740-741- # if a test function is passed to subparse we check if we742- # reached the end of such a requested block.743- if test is not None and test(lineno, token, data):744- if not drop_needle:745- self.tokenstream.push(lineno, token, data)746- return finish()747-748- # the first token tells us which directive we want to call.749- # if if doesn't match any existing directive it's like a750- # template syntax error.751- if data in self.directives:752- node = self.directives[data](lineno, gen)753- # context depending directive found754- elif data in self.context_directives:755- raise TemplateSyntaxError('unexpected directive %r' %756- str(data), lineno,757- self.filename)758- # keyword or unknown name with trailing slash1094+ raise TemplateSyntaxError('unknown directive %r.' %1095+ self.stream.current.type,1096+ lineno, self.filename)1097 else:760- # non name token in no_variable_block mode.761- if token != 'name' and self.no_variable_block:762- process_variable([(lineno, token, data)] +763- list(gen))764- continue765- if data.endswith('_'):766- # it was a non keyword identifier and we have767- # no variable tag. sounds like we should process768- # this as variable tag769- if self.no_variable_block:770- process_variable([(lineno, token, data)] +771- list(gen))772- continue773- # otherwise strip the trailing underscore for the774- # exception that is raised775- data = data[:-1]776- raise TemplateSyntaxError('unknown directive %r' %777- str(data), lineno,778- self.filename)779- # some tags like the extends tag do not output nodes.780- # so just skip that.781- if node is not None:782- result.append(node)1098+ node = handler()1099+ if node is not None:1100+ push_node(node)1101+ elif token_type == 'data':1102+ push_data()1103 784- # here the only token we should get is "data". all other785- # tokens just exist in block or variable sections. (if the786- # tokenizer is not brocken)787- elif token in 'data':788- data_buffer.append(('text', lineno, data))789-790- # so this should be unreachable code1104+ # this should be unreachable code1105 else:792- raise AssertionError('unexpected token %r (%r)' % (token,793- data))1106+ assert False, "unexpected token %r" % self.stream.current1107 795- # still here and a test function is provided? raise and error1108 if test is not None:797- # if the callback is a state test lambda wrapper we798- # can use the `error_message` property to get the error799- if isinstance(test, StateTest):800- msg = ': ' + test.error_message801- else:802- msg = ''803- raise TemplateSyntaxError('unexpected end of template' + msg,804- lineno, self.filename)1109+ msg = isinstance(test, StateTest) and ': ' + test.message or ''1110+ raise TemplateSyntaxError('unexpected end of stream' + msg,1111+ self.stream.lineno, self.filename)805- return finish()1112 807- def close_remaining_block(self):1113+ return assemble_list()1114+1115+ def parse(self):1116 """809- If we opened a block tag because one of our tags requires an end810- tag we can use this method to drop the rest of the block from811- the stream. If the next token isn't the block end we throw an812- error.1117+ Parse the template and return a Template node. This also does some1118+ post processing sanitizing and parses for an extends tag.1119 """814- lineno, _, tagname = self.tokenstream.last1120+ if self.closed:1121+ raise RuntimeError('parser is closed')1122+1123 try:816- lineno, token, data = self.tokenstream.next()817- except StopIteration:818- raise TemplateSyntaxError('missing closing tag', lineno,819- self.filename)820- if token != 'block_end':821- print token, data, list(self.tokenstream)822- raise TemplateSyntaxError('expected empty %s-directive but '823- 'found additional arguments.' %824- tagname, lineno, self.filename)1124+ # get the leading whitespace, if we are not in a child1125+ # template we push that back to the stream later.1126+ leading_whitespace = self.stream.read_whitespace()1127+1128+ # parse an optional extends which *must* be the first node1129+ # of a template.1130+ if self.stream.current.type == 'block_begin' and \1131+ self.stream.look().type == 'extends':1132+ self.stream.skip(2)1133+ extends = self.stream.expect('string').value1134+ self.stream.expect('block_end')1135+ else:1136+ extends = None1137+ if leading_whitespace:1138+ self.stream.push(leading_whitespace)1139+1140+ body = self.subparse(None)1141+ def walk(nodelist, stack):1142+ for node in nodelist:1143+ if extends is not None and \1144+ node.__class__ is nodes.Block and \1145+ stack[-1] is not body:1146+ for n in stack:1147+ if n.__class__ is nodes.Block:1148+ break1149+ else:1150+ raise TemplateSyntaxError('misplaced block %r, '1151+ 'blocks in child '1152+ 'templates must be '1153+ 'either top level or '1154+ 'located in a block '1155+ 'tag.' % node.name,1156+ node.lineno,1157+ self.filename)1158+ stack.append(node)1159+ walk(node.get_child_nodes(), stack)1160+ stack.pop()1161+ walk([body], [body])1162+ return nodes.Template(extends, body, 1, self.filename)1163+ finally:1164+ self.close()1165+1166+ def close(self):1167+ """Clean up soon."""1168+ self.closed = True1169+ self.stream = self.directives = self.stream = self.blocks = \1170+ self.environment = Nonemodified:jinja/plugin.py+5 added
12 unmodified lines13 14 :copyright: 2007 by Armin Ronacher.15 :license: BSD, see LICENSE for more details.16 """17+from warnings import warn18 from jinja.environment import Environment19 from jinja.loaders import FunctionLoader, FileSystemLoader, PackageLoader20 from jinja.exceptions import TemplateNotFound21 99 unmodified lines121 performance. In that case of `getmtime_func`122 not being provided this won't have an effect.123 =================== =================================================124 """125+ warn(DeprecationWarning('general plugin interface implementation '126+ 'deprecated because not an accepted '127+ 'standard.'))128+129 if 'environment' in options:130 env = options['environment']131 if not len(options) == 1:132 raise TypeError('if environment provided no other '34 unmodified linesmodified:jinja/tests.py+13 added-10 removed
90 unmodified lines91 *not* raw strings.92 93 .. sourcecode:: jinja94 95- {% if var is matching('^\\d+$') %}95+ {% if var is matching @/^\d+$/ %}96 var looks like a number97 {% else %}98 var doesn't really look like a number99 {% endif %}100 """101- if isinstance(regex, unicode):102- regex = re.compile(regex, re.U)103- elif isinstance(regex, str):104- regex = re.compile(regex)105- elif type(regex) is not regex_type:106- regex = None101 def wrapped(environment, context, value):102+ if type(regex) is regex_type:103+ regex_ = regex104+ else:105+ if environment.disable_regexps:106+ raise RuntimeError('regular expressions disabled.')107+ if isinstance(regex, unicode):108+ regex_ = re.compile(regex, re.U)109+ elif isinstance(regex, str):110+ regex_ = re.compile(regex)108- if regex is None:109- return False110- return regex.search(value) is not None111+ else:112+ return False113+ return regex_.search(value) is not None114 return wrapped115 116 117 def test_sameas(other):26 unmodified linesmodified:jinja/utils.py+30 added-18 removed
13 unmodified lines14 import re15 import sys16 import string17 from types import MethodType, FunctionType18-from compiler.ast import CallFunc, Name, Const19-from jinja.nodes import Trans18+from jinja import nodes19 from jinja.exceptions import SecurityException, TemplateNotFound20 21 # the python2.4 version of deque is missing the remove method22 # because a for loop with a lookup for the missing value written46 unmodified lines69 if reverse:70 rv.reverse()71 return rv72 74-# if we have extended debugger support we should really use it75-try:76- from jinja._tbtools import *77- has_extended_debugger = True78-except ImportError:79- has_extended_debugger = False80-73 # group by support74 try:75 from itertools import groupby76 except ImportError:118 unmodified lines195 if not isinstance(name, basestring):196 raise AttributeError(name)197 if name[:2] == name[-2:] == '__':198 raise SecurityException('not allowed to access internal attributes')207- if obj.__class__ in callable_types and name.startswith('func_') or \208- name.startswith('im_'):199+ if getattr(obj, '__class__', None) in callable_types and \200+ name.startswith('func_') or name.startswith('im_'):201 raise SecurityException('not allowed to access function attributes')202 r = _getattr(obj, 'jinja_allowed_attributes', None)203 if r is not None and name not in r:204 raise SecurityException('disallowed attribute accessed')213- return _getattr(obj, name)205 206+ # attribute lookups convert unicode strings to ascii bytestrings.207+ # this process could raise an UnicodeEncodeError.208+ try:209+ return _getattr(obj, name)210+ except UnicodeError:211+ raise AttributeError(name)212 213+214 def safe_range(start, stop=None, step=None):215 """216 "Safe" form of range that does not generate too large lists.217 """131 unmodified lines349 """350 Used by the python translator to capture output of substreams.351 (macros, filter sections etc)352 """353+ def wrapped(*a, **kw):354+ __traceback_hide__ = True355- return lambda *a, **kw: capture_generator(f(*a, **kw))355+ return capture_generator(f(*a, **kw))356+ return wrapped357 358 359 def empty_block(context):360 """13 unmodified lines374 todo = [ast]375 result = []376 while todo:377 node = todo.pop()377- if node.__class__ is Trans:378+ if node.__class__ is nodes.Trans:379 result.append((node.lineno, node.singular, node.plural))379- elif node.__class__ is CallFunc and \380- node.node.__class__ is Name and \380+ elif node.__class__ is nodes.CallExpression and \381+ node.node.__class__ is nodes.NameExpression and \382 node.node.name == '_':382- if len(node.args) == 1 and node.args[0].__class__ is Const:383+ if len(node.args) == 1 and not node.kwargs and not node.dyn_args \384+ and not node.dyn_kwargs and \385+ node.args[0].__class__ is nodes.ConstantExpression:386 result.append((node.lineno, node.args[0].value, None))384- todo.extend(node.getChildNodes())387+ todo.extend(node.get_child_nodes())388 result.sort(lambda a, b: cmp(a[0], b[0]))389 return result390 391 219 unmodified lines611 rv = CacheDict(self.capacity)612 rv._mapping = deepcopy(self._mapping)613 rv._queue = deepcopy(self._queue)614 return rv615+616+617+NAMESPACE = {618+ 'range': safe_range,619+ 'debug': debug_helper,620+ 'lipsum': generate_lorem_ipsum,621+ 'watchchanges': watch_changes,622+ 'rendertemplate': render_included623+}modified:tests/runtime/bigtable.py+5 added-1 removed
5 unmodified lines6 #7 # Author: Jonas Borgström <jonas@edgewall.com>8 # Author: Armin Ronacher <armin.ronacher@active-4.com>9 10-import cgi10+import os11 import sys12+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))13+14+import cgi15 import timeit16 import jdebug17 from StringIO import StringIO18 19+20 try:21 from genshi.builder import tag22 from genshi.template import MarkupTemplate23 have_genshi = True167 unmodified linesmodified:tests/runtime/exception.py+22 added-4 removed
1-import jdebug1+import os2 import sys3+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))4+5+import jdebug6 from jinja import Environment, DictLoader7 from jinja.exceptions import TemplateNotFound8 from wsgiref.simple_server import make_server9 27 unmodified lines37 <li><a href="nested_runtime_error">nested runtime error</a></li>38 <li><a href="code_runtime_error">runtime error in code</a></li>39 <li><a href="syntax_from_string">a syntax error from string</a></li>40 <li><a href="runtime_from_string">runtime error from a string</a></li>41+ <li><a href="multiple_templates">multiple templates</a></li>42 </ul>43 </body>44 </html>45 ''',10 unmodified lines56 ''',57 '/nested_syntax_error': u'''58 {% include 'syntax_broken' %}59 ''',56-60 '/code_runtime_error': u'''We have a runtime error here:61 {{ broken() }}''',62+ '/multiple_templates': '''\63+{{ fire_multiple_broken() }}64+''',65 66 'runtime_broken': '''\67 This is an included template68 {% set a = 1 / 0 %}''',69 'syntax_broken': '''\70 This is an included template65-{% raw %}just some foo'''71+{% raw %}just some foo''',72+ 'multiple_broken': '''\73+Just some context:74+{% include 'macro_broken' %}75+{{ broken() }}76+''',77+ 'macro_broken': '''\78+{% macro broken %}79+ {{ 1 / 0 }}80+{% endmacro %}81+'''82 }))83+e.globals['fire_multiple_broken'] = lambda: \84+ e.get_template('multiple_broken').render()85 86 FAILING_STRING_TEMPLATE = '{{ 1 / 0 }}'87 BROKEN_STRING_TEMPLATE = '{% if foo %}...{% endfor %}'88 19 unmodified lines108 109 110 if __name__ == '__main__':111 from werkzeug.debug import DebuggedApplication94- app = DebuggedApplication(test)112+ app = DebuggedApplication(test, True)113 make_server("localhost", 7000, app).serve_forever()modified:tests/test_lexer.py+23 added
12 unmodified lines13 <!--- for item in seq -->14 <li>{item}</li>15 <!--- endfor -->16 </ul>'''17+BYTEFALLBACK = u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}'''18 19 20 def test_balancing():21 from jinja import Environment7 unmodified lines29 env = Environment('<!--', '-->', '{', '}')30 tmpl = env.from_string(COMMENTS)31 assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "32 "<li>1</li>\n <li>2</li>\n</ul>")33+34+35+def test_string_escapes(env):36+ for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':37+ tmpl = env.from_string('{{ %s }}' % repr(char)[1:])38+ assert tmpl.render() == char39+ assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'40+41+42+def test_bytefallback(env):43+ tmpl = env.from_string(BYTEFALLBACK)44+ assert tmpl.render() == u"'foo'|u'b\\xe4r'"45+46+47+def test_operators(env):48+ from jinja.lexer import operators49+ for test, expect in operators.iteritems():50+ if test in '([{}])':51+ continue52+ stream = env.lexer.tokenize('{{ %s }}' % test)53+ stream.next()54+ assert stream.current.type == expectmodified:tests/test_loaders.py+13 added-8 removed
44 unmodified lines45 46 47 def test_package_loader():48 env = Environment(loader=package_loader)49+ for x in xrange(2):49- tmpl = env.get_template('test.html')50- assert tmpl.render().strip() == 'BAR'51- try:52- env.get_template('missing.html')53- except TemplateNotFound:54- pass55- else:56- raise AssertionError('expected template exception')50+ tmpl = env.get_template('test.html')51+ assert tmpl.render().strip() == 'BAR'52+ try:53+ env.get_template('missing.html')54+ except TemplateNotFound:55+ pass56+ else:57+ raise AssertionError('expected template exception')58 59+ # second run in native mode (no pkg_resources)60+ package_loader.force_native = True61+ del package_loader._load_func62 63+64 def test_filesystem_loader():65 env = Environment(loader=filesystem_loader)66 tmpl = env.get_template('test.html')67 assert tmpl.render().strip() == 'BAR'111 unmodified linesmodified:tests/test_macros.py+7 added
53 unmodified lines54 {% macro test() %}{{ caller is not defined }}{% endmacro %}\55 {{ test() }}\56 '''57 58+INCLUDETEMPLATE = '''{% macro test(foo) %}[{{ foo }}]{% endmacro %}'''59 60+61 def test_simple(env):62 tmpl = env.from_string(SIMPLE)63 assert tmpl.render() == 'Hello Peter!'64 41 unmodified lines106 107 def test_caller_undefined(env):108 tmpl = env.from_string(CALLERUNDEFINED)109 assert tmpl.render() == 'True'110+111+112+def test_include(env):113+ tmpl = env.from_string('{% include "include" %}{{ test("foo") }}')114+ assert tmpl.render() == '[foo]'modified:tests/test_security.py+2 added-2 removed
41 unmodified lines42 test_restricted = '''43 >>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")44 Traceback (most recent call last):45 ...46-TemplateSyntaxError: can't assign to expression. (line 1)46+TemplateSyntaxError: cannot assign to expression (line 1)47 >>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")48 Traceback (most recent call last):49 ...50-TemplateSyntaxError: can't assign to expression. (line 1)50+TemplateSyntaxError: cannot assign to expression (line 1)51 '''modified:tests/test_syntax.py+112 added-4 removed
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9+from jinja import Environment, DictLoader10+from jinja.exceptions import TemplateSyntaxError11 12+13 CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''14 SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''15 ATTR = '''{{ foo.bar }}|{{ foo['bar'] }}'''16 SUBSCRIPT = '''{{ foo[0] }}|{{ foo[-1] }}'''17 KEYATTR = '''{{ {'items': 'foo'}.items }}|{{ {}.items() }}'''15-TUPLE = '''{{ () }}'''18+TUPLE = '''{{ () }}|{{ (1,) }}|{{ (1, 2) }}'''19 MATH = '''{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}'''20 DIV = '''{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}'''21 UNARY = '''{{ +3 }}|{{ -3 }}'''22+CONCAT = '''{{ [1, 2] ~ 'foo' }}'''23 COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}'''24+INOP = '''{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}'''20-LITERALS = '''{{ [] }}|{{ {} }}|{{ '' }}'''25+LITERALS = '''{{ [] }}|{{ {} }}|{{ () }}|{{ '' }}|{{ @() }}'''26 BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}'''27 GROUPING = '''{{ (true and false) or (false and true) and not false }}'''28+CONDEXPR = '''{{ 0 if true else 1 }}'''29+DJANGOATTR = '''{{ [1, 2, 3].0 }}'''30+FILTERPRIORITY = '''{{ "foo"|upper + "bar"|upper }}'''31+REGEX = '''{{ @/\S+/.findall('foo bar baz') }}'''32+TUPLETEMPLATES = [33+ '{{ () }}',34+ '{{ (1, 2) }}',35+ '{{ (1, 2,) }}',36+ '{{ 1, }}',37+ '{{ 1, 2 }}',38+ '{% for foo, bar in seq %}...{% endfor %}',39+ '{% for x in foo, bar %}...{% endfor %}',40+ '{% for x in foo, %}...{% endfor %}',41+ '{% for x in foo, recursive %}...{% endfor %}',42+ '{% for x in foo, bar recursive %}...{% endfor %}',43+ '{% for x, in foo, recursive %}...{% endfor %}'44+]45+TRAILINGCOMMA = '''{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}|{{ @(1, 2,) }}'''46 47 48 def test_call():49 from jinja import Environment24 unmodified lines74 75 76 def test_tuple(env):77 tmpl = env.from_string(TUPLE)55- assert tmpl.render() == '[]'78+ assert tmpl.render() == '()|(1,)|(1, 2)'79 80 81 def test_math(env):82 tmpl = env.from_string(MATH)9 unmodified lines92 tmpl = env.from_string(UNARY)93 assert tmpl.render() == '3|-3'94 95 96+def test_concat(env):97+ tmpl = env.from_string(CONCAT)98+ assert tmpl.render() == '[1, 2]foo'99+100+101 def test_compare(env):102 tmpl = env.from_string(COMPARE)103 assert tmpl.render() == 'True|True|True|True|True'104 105 106+def test_inop(env):107+ tmpl = env.from_string(INOP)108+ assert tmpl.render() == 'True|False'109+110+111 def test_literals(env):112 tmpl = env.from_string(LITERALS)80- assert tmpl.render() == '[]|{}|'113+ assert tmpl.render() == '[]|{}|()||set([])'114 115 116 def test_bool(env):117 tmpl = env.from_string(BOOL)2 unmodified lines120 121 def test_grouping(env):122 tmpl = env.from_string(GROUPING)123 assert tmpl.render() == 'False'124+125+126+def test_django_attr(env):127+ tmpl = env.from_string(DJANGOATTR)128+ assert tmpl.render() == '1'129+130+131+def test_conditional_expression(env):132+ tmpl = env.from_string(CONDEXPR)133+ assert tmpl.render() == '0'134+135+136+def test_filter_priority(env):137+ tmpl = env.from_string(FILTERPRIORITY)138+ assert tmpl.render() == 'FOOBAR'139+140+141+def test_function_calls(env):142+ tests = [143+ (True, '*foo, bar'),144+ (True, '*foo, *bar'),145+ (True, '*foo, bar=42'),146+ (True, '**foo, *bar'),147+ (True, '**foo, bar'),148+ (False, 'foo, bar'),149+ (False, 'foo, bar=42'),150+ (False, 'foo, bar=23, *args'),151+ (False, 'a, b=c, *d, **e'),152+ (False, '*foo, **bar')153+ ]154+ for should_fail, sig in tests:155+ if should_fail:156+ try:157+ print env.from_string('{{ foo(%s) }}' % sig)158+ except TemplateSyntaxError:159+ continue160+ assert False, 'expected syntax error'161+ else:162+ env.from_string('foo(%s)' % sig)163+164+165+def test_regex(env):166+ tmpl = env.from_string(REGEX)167+ assert tmpl.render() == "['foo', 'bar', 'baz']"168+169+170+def test_tuple_expr(env):171+ for tmpl in TUPLETEMPLATES:172+ assert env.from_string(tmpl)173+174+175+def test_trailing_comma(env):176+ tmpl = env.from_string(TRAILINGCOMMA)177+ assert tmpl.render() == '(1, 2)|[1, 2]|{1: 2}|set([1, 2])'178+179+180+def test_extends_position():181+ env = Environment(loader=DictLoader({182+ 'empty': '[{% block empty %}{% endblock %}]'183+ }))184+ tests = [185+ ('{% extends "empty" %}', '[!]'),186+ (' {% extends "empty" %}', '[!]'),187+ (' !\n', ' !\n!'),188+ ('{# foo #} {% extends "empty" %}', '[!]'),189+ ('{% set foo = "blub" %}{% extends "empty" %}', None)190+ ]191+192+ for tmpl, expected_output in tests:193+ try:194+ tmpl = env.from_string(tmpl + '{% block empty %}!{% endblock %}')195+ except TemplateSyntaxError:196+ assert expected_output is None, 'got syntax error'197+ else:198+ assert expected_output == tmpl.render()modified:tests/test_tests.py+9 added-2 removed
9 unmodified lines10 DEFINED = '''{{ missing is defined }}|{{ true is defined }}'''11 EVEN = '''{{ 1 is even }}|{{ 2 is even }}'''12 LOWER = '''{{ "foo" is lower }}|{{ "FOO" is lower }}'''13 MATCHING = '''{{ "42" is matching('^\\d+$') }}|\14-{{ "foo" is matching('^\\d+$') }}'''14+{{ "foo" is matching('^\\d+$') }}|\15+{{ "foo bar" is matching @/^foo\\s+BAR$/i }}'''16 NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\17 {{ 42 is numeric }}'''18 ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''19 SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\20 {{ "foo" is sequence }}|\21 {{ 42 is sequence }}'''22 UPPER = '''{{ "FOO" is upper }}|{{ "foo" is upper }}'''23 SAMEAS = '''{{ foo is sameas(false) }}|{{ 0 is sameas(false) }}'''24+NOPARENFORARG1 = '''{{ foo is sameas none }}'''25 26 27 def test_defined(env):28 tmpl = env.from_string(DEFINED)11 unmodified lines40 41 42 def test_matching(env):43 tmpl = env.from_string(MATCHING)42- assert tmpl.render() == 'True|False'44+ assert tmpl.render() == 'True|False|True'45 46 47 def test_numeric(env):48 tmpl = env.from_string(NUMERIC)17 unmodified lines66 67 def test_sameas(env):68 tmpl = env.from_string(SAMEAS)69 assert tmpl.render(foo=False) == 'True|False'70+71+72+def test_no_paren_for_arg1(env):73+ tmpl = env.from_string(NOPARENFORARG1)74+ assert tmpl.render(foo=None) == 'True'modified:tests/test_various.py+16 added-5 removed
27 unmodified lines28 {{ yield }}29 {{ while }}30 {{ pass }}31 {{ finally }}'''32-LIGHTKW = '''{{ call }}'''32 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''33 RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''34 CONST = '''{{ true }}|{{ false }}|{{ none }}|{{ undefined }}|\35 {{ none is defined }}|{{ undefined is defined }}'''36+LOCALSET = '''{% set foo = 0 %}\37+{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\38+{{ foo }}'''39+NONLOCALSET = '''{% set foo = 0 %}\40+{% for item in [1, 2] %}{% set foo = 1! %}{% endfor %}\41+{{ foo }}'''42 CONSTASS1 = '''{% set true = 42 %}'''43 CONSTASS2 = '''{% for undefined in seq %}{% endfor %}'''44 45 46 def test_keywords(env):47 env.from_string(KEYWORDS)48 49 45-def test_lightkw(env):46- env.from_string(LIGHTKW)47-48-50 def test_unpacking(env):51 tmpl = env.from_string(UNPACKING)52 assert tmpl.render() == '1|2|3'53 46 unmodified lines100 except TemplateSyntaxError:101 pass102 else:103 raise AssertionError('expected syntax error')104+105+106+def test_localset(env):107+ tmpl = env.from_string(LOCALSET)108+ assert tmpl.render() == '0'109+110+111+def test_nonlocalset(env):112+ tmpl = env.from_string(NONLOCALSET)113+ assert tmpl.render() == '1'modified:CHANGES+63 added
14 unmodified lines15 - added `groupby` filter.16 17 - added `sameas` test function.18 19+- standalone parser. Jinja does not use the python parser any more and will20+ continue having the same semantics in any future python versions. This21+ was done in order to simplify updating Jinja to 2.6 and 3.0 and to support22+ non python syntax.23 24+- added support for ``expr1 if test else expr2`` (conditional expressions)25+26+- ``foo.0`` as alias for ``foo[0]`` is possible now. This is mainly for27+ django compatibility.28+29+- the filter operators has a much higher priority now which makes it30+ possible to do ``foo|filter + bar|filter``.31+32+- new AST. the return value of `Environment.parse` is now a Jinja AST and not33+ a Jinja-Python AST. This is also the only backwards incompatible change but34+ should not affect many users because this feature is more or less35+ undocumented and has few use cases.36+37+- tuple syntax returns tuples now and not lists any more.38+39+- the print directive and ``{{ variable }}`` syntax now accepts and implicit40+ tuple like the `for` and `cycle` tags. (``{{ 1, 2 }}`` is an implicit alias41+ for ``{{ (1, 2) }}` like ``{% for a, b in seq %}`` is for42+ ``{% for (a, b) in seq %}``.43+44+- tests called with *one* parameter don't need parentheses. This gives a more45+ natural syntax for the `sameas` test and some others:46+ ``{{ foo is sameas bar }}`` instead of ``{{ foo is sameas(bar) }}``. If you47+ however want to pass more than one argument you have to use parentheses48+ because ``{{ foo is sometest bar, baz }}`` is handled as49+ ``{{ (foo is sometest(bar), baz) }}``, so as tuple expression.50+51+- removed support for octal character definitions in strings such as52+ ``'\14'``, use ``'\x0c'`` now.53+54+- added regular expression literal. ``@/expr/flags`` equals55+ ``re.compile(r'(?flags)expr')``. This is useful for the `matching` test and56+ probably some others.57+58+- added set literal. We do not use python3's {1, 2} syntax because59+ this conflicts with the dict literal. To be compatible with the regex60+ literal we use ``@(1, 2)`` instead.61+62+- fixed bug in `get_attribute` that disallowed retreiving attributes of objects63+ without a `__class__` such as `_sre.SRE_Pattern`.64+65+- addded `django.contrib.jinja` which provides advanced support for django.66+ (thanks Bryan McLemore)67+68+- debugger is now able to rewrite the whole traceback, not only the first69+ frame. (requires the optional debugger c module which is compiled70+ automatically on installation if possible)71+72+- if the set that is postfixed with a bang (!) it acts like the python 373+ "nonlocal" keyword. This means that you can now override variables74+ defined in the outer scope from within a loop.75+76+- ``foo + bar`` is now a simpler alternative to ``foo|string + bar|string``77+78+- `PackageLoader` can now work without pkg_resources too79+80+- added `getattribute` and `getitem` filter.81+82+83 Version 1.184 -----------85 (codename: sinka, released Jun 1, 2007)86 119 unmodified linesmodified:jdebug.py+5 added-3 removed
34 unmodified lines35 36 def p(x=None, f=None):37 if x is None and f is not None:38 x = e.loader.get_source(f)39- print PythonTranslator(e, Parser(e, x, f).parse()).translate()39+ print PythonTranslator(e, Parser(e, x, f).parse(), None).translate()40 41 def l(x):42- for item in e.lexer.tokenize(x):43- print '%5s %-20s %r' % item42+ for token in e.lexer.tokenize(x):43+ print '%5s %-20s %r' % (item.lineno,44+ item.type,45+ item.value)46 47 if __name__ == '__main__':48 if len(sys.argv) > 1:49 from jinja import FileSystemLoader5 unmodified lines