[svn] some changes in jinja. added recursion support for {% for %}, pos -> lineno for better debugging once debugging works
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 fed86c1 · Browse files · 9 files·+607 added−178 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+607 added−178 removed
- other:+607 added−178 removed
Provenance
- Commit
5887538- Tree
a82c8f1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
fed86c1
9 files changed+607 added−178 removed
modified:jinja/translators/python.py+140 added-47 removed
19 unmodified lines20 21 def __init__(self, environment, node):22 self.environment = environment23 self.node = node24- self.indention = 025- self.last_pos = 024 25 self.constants = {26 'true': 'True',27 'false': 'False',2 unmodified lines30 }31 32 self.handlers = {33 # jinja nodes34+ nodes.Template: self.handle_template,35 nodes.Text: self.handle_template_text,36 nodes.NodeList: self.handle_node_list,37 nodes.ForLoop: self.handle_for_loop,38 nodes.IfCondition: self.handle_if_condition,39 nodes.Cycle: self.handle_cycle,40 nodes.Print: self.handle_print,41+ nodes.Macro: self.handle_macro,42 # used python nodes43 ast.Name: self.handle_name,44 ast.AssName: self.handle_name,45 ast.Compare: self.handle_compare,30 unmodified lines76 self.unsupported.update({77 ast.GenExpr: 'generator expressions'78 })79 80+ self.reset()81+82 def indent(self, text):83 """84 Indent the current text.85 """7 unmodified lines93 out = self.handlers[node.__class__](node)94 elif node.__class__ in self.unsupported:95 raise TemplateSyntaxError('unsupported syntax element %r found.'96 % self.unsupported[node.__class__],95- self.last_pos)97+ node.lineno)98 else:99 raise AssertionError('unhandled node %r' % node.__class__)100 return out101 102 # -- jinja nodes103 104+ def handle_template(self, node):105+ """106+ Handle a template node. Basically do nothing but calling the107+ handle_node_list function.108+ """109+ return self.handle_node_list(node)110+111+ def handle_template_text(self, node):112+ """113+ Handle data around nodes.114+ """115+ return self.indent('write(%r)' % node.text)116+117 def handle_node_list(self, node):118 """119 In some situations we might have a node list. It's just120 a collection of multiple statements.121 """107- self.last_pos = node.pos122 buf = []123 for n in node:124 buf.append(self.handle_node(n))125 return '\n'.join(buf)2 unmodified lines128 """129 Handle a for loop. Pretty basic, just that we give the else130 clause a different behavior.131 """118- self.last_pos = node.pos132 buf = []133 write = lambda x: buf.append(self.indent(x))134 write('context.push()')122- write('parent_loop = context[\'loop\']')123- write('loop_data = None')124- write('for (loop_data, %s) in environment.iterate(%s):' % (125- self.handle_node(node.item),126- self.handle_node(node.seq)127- ))135+136+ # recursive loops137+ if node.recursive:138+ write('def forloop(seq):')139+ self.indention += 1140+ write('context[\'loop\'].push(seq)')141+ write('for %s in context[\'loop\']:' %142+ self.handle_node(node.item),143+ )144+145+ # simple loops146+ else:147+ write('context[\'loop\'] = LoopContext(%s, context[\'loop\'], None)' %148+ self.handle_node(node.seq))149+ write('for %s in context[\'loop\']:' %150+ self.handle_node(node.item)151+ )152+153+ # handle real loop code154 self.indention += 1129- write('loop_data.parent = parent_loop')130- write('context[\'loop\'] = loop_data')155 buf.append(self.handle_node(node.body))156 self.indention -= 1157+158+ # else part of loop159 if node.else_ is not None:134- write('if loop_data is None:')160+ write('if not context[\'loop\'].iterated:')161 self.indention += 1162 buf.append(self.handle_node(node.else_))163 self.indention -= 1164+165+ # call recursive for loop!166+ if node.recursive:167+ write('context[\'loop\'].pop()')168+ self.indention -= 1169+ write('context[\'loop\'] = LoopContext(None, context[\'loop\'], forloop)')170+ write('forloop(%s)' % self.handle_node(node.seq))171+172 write('context.pop()')173 return '\n'.join(buf)174 175 def handle_if_condition(self, node):176 """177 Handle an if condition node.178 """145- self.last_pos = node.pos179 buf = []180 write = lambda x: buf.append(self.indent(x))181+ for idx, (test, body) in enumerate(node.tests):182+ write('%sif %s:' % (183+ idx and 'el' or '',184+ self.handle_node(test)148- write('if %s:' % self.handle_node(node.test))149- self.indention += 1150- buf.append(self.handle_node(node.body))151- self.indention -= 1185+ ))186+ self.indention += 1187+ buf.append(self.handle_node(body))188+ self.indention -= 1189 if node.else_ is not None:190 write('else:')191 self.indention += 1192 buf.append(self.handle_node(node.else_))3 unmodified lines196 def handle_cycle(self, node):197 """198 Handle the cycle tag.199 """200+ name = '::cycle_%x' % self.last_cycle_id201+ self.last_cycle_id += 1202 buf = []203 write = lambda x: buf.append(self.indent(x))165- write('# XXX: add some code here')166- self.last_pos = node.pos204+205+ write('if not %r in context.current:' % name)206+ self.indention += 1207+ if node.seq.__class__ in (ast.Tuple, ast.List):208+ write('context.current[%r] = CycleContext([%s])' % (209+ name,210+ ', '.join([self.handle_node(n) for n in node.seq.nodes])211+ ))212+ hardcoded = True213+ else:214+ write('context.current[%r] = CycleContext()' % name)215+ hardcoded = False216+ self.indention -= 1217+218+ if hardcoded:219+ write('write_var(context.current[%r].cycle())' % name)220+ else:221+ write('write_var(context.current[%r].cycle(%s))' % (222+ name,223+ self.handle_node(node.seq)224+ ))225+226 return '\n'.join(buf)227 228 def handle_print(self, node):229 """230 Handle a print statement.231 """173- self.last_pos = node.pos232 return self.indent('write_var(%s)' % self.handle_node(node.variable))233 176- def handle_template_text(self, node):234+ def handle_macro(self, node):235 """178- Handle data around nodes.236+ Handle macro declarations.237 """180- self.last_pos = node.pos181- return self.indent('write(%r)' % node.text)238+ buf = []239 240+ args = []241+ for name, n in node.arguments:242+ if n is None:243+ args.append('%s=Undefined' % name)244+ else:245+ args.append('%s=%s' % (name, self.handle_node(n)))246+ buf.append(self.indent('def macro(%s):' % ', '.join(args)))247+ self.indention += 1248+ buf.append(self.handle_node(node.body))249+ self.indention -= 1250+ buf.append(self.indent('context[%r] = macro' % node.name))251+252+ return '\n'.join(buf)253+254 # -- python nodes255 256 def handle_name(self, node):257 """6 unmodified lines264 def handle_compare(self, node):265 """266 Any sort of comparison267 """268+ # the semantic for the is operator is different.269+ # for jinja the is operator performs tests and must270+ # be the only operator271+ if node.ops[0][0] == 'is':272+ if len(node.ops) > 1:273+ raise TemplateSyntaxError('is operator must not be chained',274+ node.lineno)275+ elif node.ops[0][1].__class__ is not ast.Name:276+ raise TemplateSyntaxError('is operator requires a test name',277+ ' as operand', node.lineno)278+ return 'environment.perform_test(%s, context, %r)' % (279+ self.handle_node(node.expr),280+ node.ops[0][1].name281+ )282+283+ # normal operators284 buf = []285 buf.append(self.handle_node(node.expr))286 for op, n in node.ops:287+ if op == 'is':288+ raise TemplateSyntaxError('is operator must not be chained',289+ node.lineno)290 buf.append(op)291 buf.append(self.handle_node(n))292 return ' '.join(buf)293 8 unmodified lines302 Handle variable based attribute access foo['bar'].303 """304 if len(node.subs) != 1:305 raise TemplateSyntaxError('attribute access requires one argument',216- self.last_pos)306+ node.lineno)307 assert node.flags != 'OP_DELETE', 'wtf? do we support that?'308 if node.subs[0].__class__ is ast.Sliceobj:309 return '%s[%s]' % (310 self.handle_node(node.expr),25 unmodified lines336 """337 filters = []338 for n in node.nodes[1:]:339 if n.__class__ is ast.CallFunc:340+ if n.node.__class__ is not ast.Name:341+ raise TemplateSyntaxError('invalid filter. filter must '342+ 'be a hardcoded function name '343+ 'from the filter namespace',344+ n.lineno)345 args = []346 for arg in n.args:347 if arg.__class__ is ast.Keyword:348 raise TemplateSyntaxError('keyword arguments for '349 'filters are not supported.',255- self.last_pos)350+ n.lineno)351 args.append(self.handle_node(arg))352 if n.star_args is not None or n.dstar_args is not None:353 raise TemplateSynaxError('*args / **kwargs is not supported '259- 'for filters', self.last_pos)260- args = ', '.join(args)354+ 'for filters', n.lineno)355 if args:262- args = ', ' + args263- filters.append('environment.prepare_filter(%s%s)' % (264- self.handle_node(n.node),265- args356+ args = ', ' + ', '.join(args)357+ filters.append('environment.prepare_filter(%r%s)' % (358+ n.node.name,359+ args or ''360 ))361 elif n.__class__ is ast.Name:362 filters.append('environment.prepare_filter(%s)' %363 self.handle_node(n))364 else:365 raise TemplateSyntaxError('invalid filter. filter must be a '366 'hardcoded function name from the '367 'filter namespace',274- self.last_pos)368+ n.lineno)369 return 'environment.apply_filters(%s, context, [%s])' % (370 self.handle_node(node.nodes[0]),371 ', '.join(filters)372 )156 unmodified lines529 for n in node.nodes:530 args.append(self.handle_node(n))531 return '[%s]' % ':'.join(args)532 439- def translate(self):533+ def reset(self):534 self.indention = 1441- self.last_pos = 0442- lines = [443- 'from jinja.datastructures import Undefined',444- 'def generate(environment, context, write, write_var=None):',445- ' """This function was automatically generated by',446- ' the jinja python translator. do not edit."""',447- ' if write_var is None:',448- ' write_var = write'449- ]450- lines.append(self.handle_node(self.node))451- return '\n'.join(lines)535+ self.last_cycle_id = 0536 537+ def translate(self):538+ return (539+ 'from jinja.datastructures import Undefined, LoopContext, CycleContext\n'540+ 'def generate(context, write, write_var=None):\n'541+ ' environment = context.environment\n'542+ ' if write_var is None:\n'543+ ' write_var = lambda x: write(environment.finish_var(x))\n'544+ ) + self.handle_node(self.node)545 546+547 def translate(environment, node):548 """549 Do the translation to python.550 """1 unmodified linemodified:jinja/datastructure.py+66 added-30 removed
20 unmodified lines21 class UndefinedType(object):22 """23 An object that does not exist.24 """25+ __slots__ = ()26 27 def __init__(self):28 try:29 Undefined38 unmodified lines68 """69 Dict like object.70 """71 71- __slots__ = ('stack')72-72 def __init__(*args, **kwargs):73 try:74 self = args[0]75 self.environment = args[1]2 unmodified lines78 raise TypeError('%r requires environment as first argument. '79 'The rest of the arguments are forwarded to '80 'the default dict constructor.')81 self._stack = [initial, {}]82+ self.globals, self.current = self._stack83 84 def pop(self):85 if len(self._stack) <= 2:86 raise ValueError('cannot pop initial layer')87- return self._stack.pop()87+ rv = self._stack.pop()88+ self.current = self._stack[-1]89+ return rv90 91 def push(self, data=None):92 self._stack.append(data or {})93+ self.current = self._stack[-1]94 95 def __getitem__(self, name):96+ # don't give access to jinja internal variables97+ if name.startswith('::'):98+ return Undefined99 for d in _reversed(self._stack):100 if name in d:101 return d[name]102 return Undefined18 unmodified lines121 Simple class that provides special loop variables.122 Used by `Environment.iterate`.123 """124 119- def __init__(self, index, length):120- self.index = 0121- self.length = length122- try:123- self.length = len(seq)124- except TypeError:125- self.seq = list(seq)126- self.length = len(self.seq)127- else:128- self.seq = seq125+ jinja_allowed_attributes = ['index', 'index0', 'length', 'parent',126+ 'even', 'odd']127 130- def revindex(self):131- return self.length - self.index + 1132- revindex = property(revindex)128+ def __init__(self, seq, parent, loop_function):129+ self.loop_function = loop_function130+ self.parent = parent131+ self._stack = []132+ if seq is not None:133+ self.push(seq)134 134- def revindex0(self):135- return self.length - self.index136- revindex0 = property(revindex0)135+ def push(self, seq):136+ self._stack.append({137+ 'index': -1,138+ 'seq': seq,139+ 'length': len(seq)140+ })141 138- def index0(self):139- return self.index - 1140- index0 = property(index0)142+ def pop(self):143+ return self._stack.pop()144 142- def even(self):143- return self.index % 2 == 0144- even = property(even)145+ iterated = property(lambda s: s._stack[-1]['index'] > -1)146+ index0 = property(lambda s: s._stack[-1]['index'])147+ index = property(lambda s: s._stack[-1]['index'] + 1)148+ length = property(lambda s: s._stack[-1]['length'])149+ even = property(lambda s: s._stack[-1]['index'] % 2 == 0)150+ odd = property(lambda s: s._stack[-1]['index'] % 2 == 1)151 146- def odd(self):147- return self.index % 2 == 1148- odd = property(odd)152+ def __iter__(self):153+ s = self._stack[-1]154+ for idx, item in enumerate(s['seq']):155+ s['index'] = idx156+ yield item157 158+ def __call__(self, seq):159+ if self.loop_function is not None:160+ return self.loop_function(seq)161+ return Undefined162 163+164+class CycleContext(object):165+ """166+ Helper class used for cycling.167+ """168+169+ def __init__(self, seq=None):170+ self.lineno = -1171+ if seq is not None:172+ self.seq = seq173+ self.length = len(seq)174+ self.cycle = self.cycle_static175+ else:176+ self.cycle = self.cycle_dynamic177+178+ def cycle_static(self):179+ self.lineno = (self.lineno + 1) % self.length180+ return self.seq[self.lineno]181+182+ def cycle_dynamic(self, seq):183+ self.lineno = (self.lineno + 1) % len(seq)184+ return seq[self.lineno]185+186+187 class TokenStream(object):188 """189 A token stream works like a normal generator just that190 it supports pushing tokens back to the stream.47 unmodified lines238 yield token239 except StopIteration:240 raise IndexError('end of stream reached')241 206- def push(self, pos, token, data):242+ def push(self, lineno, token, data):243 """Push an yielded token back to the stream."""208- self._pushed.append((pos, token, data))244+ self._pushed.append((lineno, token, data))modified:jinja/defaults.py+1 added
7 unmodified lines8 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 from jinja.filters import FILTERS as DEFAULT_FILTERS12+from jinja.tests import TESTS as DEFAULT_TESTSmodified:jinja/environment.py+44 added-20 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja.lexer import Lexer12 from jinja.parser import Parser13-from jinja.datastructure import LoopContext, Undefined14-from jinja.exceptions import FilterNotFound15-from jinja.defaults import DEFAULT_FILTERS13+from jinja.datastructure import Undefined14+from jinja.exceptions import FilterNotFound, TestNotFound15+from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS16 17 18 class Environment(object):19 """9 unmodified lines29 comment_end_string='#}',30 template_charset='utf-8',31 charset='utf-8',32 loader=None,33- filters=None):33+ filters=None,34+ tests=None):35 36 # lexer / parser information37 self.block_start_string = block_start_string38 self.block_end_string = block_end_string6 unmodified lines45 self.template_charset = template_charset46 self.charset = charset47 self.loader = loader48 self.filters = filters or DEFAULT_FILTERS.copy()49+ self.tests = filters or DEFAULT_TESTS.copy()50 51 # create lexer52 self.lexer = Lexer(self)53 13 unmodified lines67 return unicode(value)68 except UnicodeError:69 return str(value).decode(self.charset, 'ignore')70 69- def iterate(self, seq):70- """71- Helper function used by the python translator runtime code to72- iterate over a sequence.73- """74- try:75- length = len(seq)76- except TypeError:77- seq = list(seq)78- length = len(seq)79- loop_data = LoopContext(0, length)80- for item in seq:81- loop_data.index += 182- yield loop_data, item83-71 def prepare_filter(self, name, *args):72 """73 Prepare a filter.74 """9 unmodified lines84 for f in filters:85 value = f(self, context, value)86 return value87 88+ def perform_test(self, value, context, testname):89+ """90+ Perform a test on a variable.91+ """92+ try:93+ test = self.tests[testname]94+ except KeyError:95+ raise TestNotFound(testname)96+ return bool(test(self, context, value))97+98 def get_attribute(self, obj, name):99 """100 Get the attribute name from obj.101 """102 try:106- return getattr(obj, name)103+ rv = getattr(obj, name)104+ r = getattr(obj, 'jinja_allowed_attributes', None)105+ if r is not None:106+ if name not in r:107+ raise AttributeError()108+ return rv109 except AttributeError:110 return obj[name]111 except:112 return Undefined113+114+ def call_function(self, f, args, kwargs, dyn_args, dyn_kwargs):115+ """116+ Function call helper117+ """118+ if dyn_args is not None:119+ args += dyn_args120+ elif dyn_kwargs is not None:121+ kwargs.update(dyn_kwargs)122+ return f(*args, **kwargs)123+124+ def finish_var(self, value):125+ """126+ As long as no write_var function is passed to the template127+ evaluator the source generated by the python translator will128+ call this function for all variables. You can use this to129+ enable output escaping etc or just ensure that None and130+ Undefined values are rendered as empty strings.131+ """132+ if value is None or value is Undefined:133+ return u''134+ return unicode(value)modified:jinja/exceptions.py+13 added-4 removed
21 unmodified lines22 def __init__(self, message):23 KeyError.__init__(self, message)24 25 26+class TestNotFound(KeyError, TemplateError):27+ """28+ Raised if a test does not exist.29+ """30+31+ def __init__(self, message):32+ KeyError.__init__(self, message)33+34+35 class TemplateSyntaxError(SyntaxError, TemplateError):36 """37 Raised to tell the user that there is a problem with the template.38 """39 31- def __init__(self, message, pos):40+ def __init__(self, message, lineno):41 SyntaxError.__init__(self, message)33- self.pos = pos42+ self.lineno = lineno43 44 45 class TemplateRuntimeError(TemplateError):46 """47 Raised by the template engine if a tag encountered an error when48 rendering.49 """50 42- def __init__(self, message, pos):51+ def __init__(self, message, lineno):52 RuntimeError.__init__(self, message)44- self.pos = pos53+ self.lineno = linenomodified:jinja/lexer.py+15 added-8 removed
21 unmodified lines22 # braces and parenthesis23 '[', ']', '(', ')', '{', '}',24 # attribute access and comparison / logical operators25 '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',26- ur'or\b', ur'and\b', ur'not\b'26+ ur'or\b', ur'and\b', ur'not\b', ur'in\b', ur'is'27 ]))28 29 30 class Failure(object):5 unmodified lines36 def __init__(self, message, cls=TemplateSyntaxError):37 self.message = message38 self.error_class = cls39 40- def __call__(self, position):41- raise self.error_class(self.message, position)40+ def __call__(self, lineno):41+ raise self.error_class(self.message, lineno)42 43 44 class Lexer(object):45 """56 unmodified lines102 Normally it's a better idea to use the `tokenize` function which103 returns a `TokenStream` but in some situations it can be useful104 to use this function since it can be marginally faster.105 """106- pos = 0106+ source = type(source)('\n').join(source.splitlines())107+ pos = lineno = 0108 stack = ['root']109 statetokens = self.rules['root']110 source_length = len(source)111 6 unmodified lines118 if isinstance(tokens, tuple):119 for idx, token in enumerate(tokens):120 # hidden group121 if token is None:122+ g += m.group(idx)123+ if g:124+ lineno += g.count('\n')125 continue126 # failure group127 elif isinstance(token, Failure):128 raise token(m.start(idx + 1))2 unmodified lines131 # group that matched132 elif token == '#bygroup':133 for key, value in m.groupdict().iteritems():134 if value is not None:131- yield m.start(key), key, value135+ yield lineno, key, value136+ lineno += value.count('\n')137 break138 else:139 raise RuntimeError('%r wanted to resolve '140 'the token dynamically'2 unmodified lines143 # normal group144 else:145 data = m.group(idx + 1)146 if data:142- yield m.start(idx + 1), token, data147+ yield lineno, token, data148+ lineno += data.count('\n')149 # strings as token just are yielded as it, but just150 # if the data is not empty151 else:152 data = m.group()153 if tokens is not None:154 if data:149- yield pos, tokens, data155+ yield lineno, tokens, data156+ lineno += data.count('\n')157 # fetch new position into new variable so that we can check158 # if there is a internal parsing error which would result159 # in an infinite loop160 pos2 = m.end()33 unmodified lines194 if pos >= source_length:195 return196 # something went wrong197 raise TemplateSyntaxError('unexpected char %r at %d' %191- (source[pos], pos), pos)198+ (source[pos], pos), lineno)modified:jinja/nodes.py+108 added-22 removed
6 unmodified lines7 8 :copyright: 2006 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11-from compiler.ast import Node11+from compiler import ast12+from compiler.misc import set_filename13 14 15+def inc_lineno(offset, tree):16+ """17+ Increment the linenumbers of all nodes in tree with offset.18+ """19+ todo = [tree]20+ while todo:21+ node = todo.pop()22+ node.lineno = (node.lineno or 0) + offset23+ todo.extend(node.getChildNodes())24+25+26+class Node(ast.Node):27+ """28+ jinja node.29+ """30+31+ def getChildren(self):32+ return self.get_items()33+34+ def getChildNodes(self):35+ return [x for x in self.get_items() if isinstance(x, ast.Node)]36+37+38 class Text(Node):39 """40 Node that represents normal text.41 """42 19- def __init__(self, pos, text):20- self.pos = pos43+ def __init__(self, lineno, text):44+ self.lineno = lineno45 self.text = text46 47+ def get_items(self):48+ return [self.text]49+50 def __repr__(self):51 return 'Text(%r)' % (self.text,)52 53 1 unmodified line55 """56 A node that stores multiple childnodes.57 """58 32- def __init__(self, pos, data=None):33- self.pos = pos59+ def __init__(self, lineno, data=None):60+ self.lineno = lineno61 list.__init__(self, data or ())62 63+ getChildren = getChildNodes = lambda s: list(s)64+65 def __repr__(self):37- return 'NodeList(%s)' % list.__repr__(self)66+ return '%s(%s)' % (67+ self.__class__.__name__,68+ list.__repr__(self)69+ )70 71 72+class Template(NodeList):73+ """74+ A template.75+ """76+77+ def __init__(self, filename, node):78+ if node.__class__ is not NodeList:79+ node = (node,)80+ NodeList.__init__(self, 0, node)81+ set_filename(filename, self)82+83+84 class ForLoop(Node):85 """86 A node that represents a for loop87 """88 45- def __init__(self, pos, item, seq, body, else_):46- self.pos = pos89+ def __init__(self, lineno, item, seq, body, else_, recursive):90+ self.lineno = lineno91 self.item = item92 self.seq = seq93 self.body = body94 self.else_ = else_95+ self.recursive = recursive96 97+ def get_items(self):98+ return [self.item, self.seq, self.body, self.else_, self.recursive]99+100 def __repr__(self):53- return 'ForLoop(%r, %r, %r, %r)' % (101+ return 'ForLoop(%r, %r, %r, %r, %r)' % (102 self.item,103 self.seq,104 self.body,57- self.else_105+ self.else_,106+ self.recursive107 )108 109 110 class IfCondition(Node):111 """112 A node that represents an if condition.113 """114 66- def __init__(self, pos, test, body, else_):67- self.pos = pos68- self.test = test69- self.body = body115+ def __init__(self, lineno, tests, else_):116+ self.lineno = lineno117+ self.tests = tests118 self.else_ = else_119 120+ def get_items(self):121+ result = []122+ for test in tests:123+ result.extend(test)124+ result.append(self._else)125+ return result126+127 def __repr__(self):73- return 'IfCondition(%r, %r, %r)' % (74- self.test,75- self.body,128+ return 'IfCondition(%r, %r)' % (129+ self.tests,130 self.else_131 )132 133 1 unmodified line135 """136 A node that represents the cycle statement.137 """138 85- def __init__(self, pos, seq):86- self.pos = pos139+ def __init__(self, lineno, seq):140+ self.lineno = lineno141 self.seq = seq142 143+ def get_items(self):144+ return [self.seq]145+146 def __repr__(self):147 return 'Cycle(%r)' % (self.seq,)148 149 150 class Print(Node):151 """95- A node that represents variable tags and print calls152+ A node that represents variable tags and print calls.153 """154 98- def __init__(self, pos, variable):99- self.pos = pos155+ def __init__(self, lineno, variable):156+ self.lineno = lineno157 self.variable = variable158 159+ def get_items(self):160+ return [self.variable]161+162 def __repr__(self):163 return 'Print(%r)' % (self.variable,)164+165+166+class Macro(Node):167+ """168+ A node that represents a macro.169+ """170+171+ def __init__(self, lineno, name, arguments, body):172+ self.lineno = lineno173+ self.name = name174+ self.arguments = arguments175+ self.body = body176+177+ def get_items(self):178+ result = [self.name]179+ for item in self.arguments:180+ result.extend(item)181+ result.append(self.body)182+ return result183+184+ def __repr__(self):185+ return 'Macro(%r, %r, %r)' % (186+ self.name,187+ self.arguments,188+ self.body189+ )modified:jinja/parser.py+97 added-47 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 from compiler import ast, parse13+from compiler.misc import set_filename14 from jinja import nodes15 from jinja.datastructure import TokenStream16 from jinja.exceptions import TemplateSyntaxError17 2 unmodified lines20 end_of_block = lambda p, t, d: t == 'block_end'21 end_of_variable = lambda p, t, d: t == 'variable_end'22 switch_for = lambda p, t, d: t == 'name' and d in ('else', 'endfor')23 end_of_for = lambda p, t, d: t == 'name' and d == 'endfor'23-switch_if = lambda p, t, d: t == 'name' and d in ('else', 'endif')24+switch_if = lambda p, t, d: t == 'name' and d in ('else', 'elif', 'endif')25 end_of_if = lambda p, t, d: t == 'name' and d == 'endif'26+end_of_macro = lambda p, t, d: t == 'name' and d == 'endmacro'27 28 29 class Parser(object):30 """24 unmodified lines55 self.directives = {56 'for': self.handle_for_directive,57 'if': self.handle_if_directive,58 'cycle': self.handle_cycle_directive,57- 'print': self.handle_print_directive59+ 'print': self.handle_print_directive,60+ 'macro': self.handle_macro_directive61 }62 60- def handle_for_directive(self, pos, gen):63+ def handle_for_directive(self, lineno, gen):64 """65 Handle a for directive and return a ForLoop node66 """67+ #XXX: maybe we could make the "recurse" part optional by using68+ # a static analysis later.69+ recursive = []70+ def wrapgen():71+ """Wrap the generator to check if we have a recursive for loop."""72+ for token in gen:73+ if token[1:] == ('name', 'recursive'):74+ try:75+ item = gen.next()76+ except StopIteration:77+ recursive.append(True)78+ return79+ yield token80+ yield item81+ else:82+ yield token64- ast = self.parse_python(pos, gen, 'for %s:pass\nelse:pass')83+ ast = self.parse_python(lineno, wrapgen(), 'for %s:pass')84 body = self.subparse(switch_for)85 86 # do we have an else section?87 if self.tokenstream.next()[2] == 'else':2 unmodified lines90 else:91 else_ = None92 self.close_remaining_block()93 75- return nodes.ForLoop(pos, ast.assign, ast.list, body, else_)94+ return nodes.ForLoop(lineno, ast.assign, ast.list, body, else_, bool(recursive))95 77- def handle_if_directive(self, pos, gen):96+ def handle_if_directive(self, lineno, gen):97 """79- Handle if/else blocks. elif is not supported by now.98+ Handle if/else blocks.99 """81- ast = self.parse_python(pos, gen, 'if %s:pass\nelse:pass')82- body = self.subparse(switch_if)100+ ast = self.parse_python(lineno, gen, 'if %s:pass')101+ tests = [(ast.tests[0][0], self.subparse(switch_if))]102 103 # do we have an else section?85- if self.tokenstream.next()[2] == 'else':86- self.close_remaining_block()87- else_ = self.subparse(end_of_if, True)88- else:89- else_ = None104+ while True:105+ lineno, token, needle = self.tokenstream.next()106+ if needle == 'else':107+ self.close_remaining_block()108+ else_ = self.subparse(end_of_if, True)109+ break110+ elif needle == 'elif':111+ gen = self.tokenstream.fetch_until(end_of_block, True)112+ ast = self.parse_python(lineno, gen, 'if %s:pass')113+ tests.append((ast.tests[0][0], self.subparse(switch_if)))114+ else:115+ else_ = None116+ break117 self.close_remaining_block()118 92- return nodes.IfCondition(pos, ast.tests[0][0], body, else_)119+ return nodes.IfCondition(lineno, tests, else_)120 94- def handle_cycle_directive(self, pos, gen):121+ def handle_cycle_directive(self, lineno, gen):122 """123 Handle {% cycle foo, bar, baz %}.124 """98- ast = self.parse_python(pos, gen, '_cycle((%s))')125+ ast = self.parse_python(lineno, gen, '_cycle((%s))')126 # ast is something like Discard(CallFunc(Name('_cycle'), ...))127 # skip that.101- return nodes.Cycle(pos, ast.expr.args[0])128+ return nodes.Cycle(lineno, ast.expr.args[0])129 103- def handle_print_directive(self, pos, gen):130+ def handle_print_directive(self, lineno, gen):131 """132 Handle {{ foo }} and {% print foo %}.133 """107- ast = self.parse_python(pos, gen, 'print_(%s)')134+ ast = self.parse_python(lineno, gen, 'print_(%s)')135 # ast is something like Discard(CallFunc(Name('print_'), ...))136 # so just use the args137 arguments = ast.expr.args138 # we only accept one argument139 if len(arguments) != 1:140 raise TemplateSyntaxError('invalid argument count for print; '141 'print requires exactly one argument, '115- 'got %d.' % len(arguments), pos)116- return nodes.Print(pos, arguments[0])142+ 'got %d.' % len(arguments), lineno)143+ return nodes.Print(lineno, arguments[0])144 118- def parse_python(self, pos, gen, template='%s'):145+ def handle_macro_directive(self, lineno, gen):146 """147+ Handle {% macro foo(bar, baz) %}.148+ """149+ try:150+ macro_name = gen.next()151+ except StopIteration:152+ raise TemplateSyntaxError('macro requires a name', lineno)153+ if macro_name[1] != 'name':154+ raise TemplateSyntaxError('expected \'name\', got %r' %155+ macro_name[1], lineno)156+ ast = self.parse_python(lineno, gen, 'def %s(%%s):pass' % str(macro_name[2]))157+ body = self.subparse(end_of_macro, True)158+ self.close_remaining_block()159+160+ if ast.varargs or ast.kwargs:161+ raise TemplateSyntaxError('variable length macro signature '162+ 'not allowed.', lineno)163+ defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + ast.defaults164+ return nodes.Macro(lineno, ast.name, zip(ast.argnames, defaults), body)165+166+ def parse_python(self, lineno, gen, template='%s'):167+ """168 Convert the passed generator into a flat string representing169 python sourcecode and return an ast node or raise a170 TemplateSyntaxError.171 """172 tokens = []125- for t_pos, t_token, t_data in gen:173+ for t_lineno, t_token, t_data in gen:174 if t_token == 'string':175 tokens.append('u' + t_data)176 else:177 tokens.append(t_data)178 source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).encode('utf-8'))179 try:180 ast = parse(source, 'exec')181 except SyntaxError, e:134- raise TemplateSyntaxError(str(e), pos + e.offset - 1)182+ raise TemplateSyntaxError(str(e), lineno + e.lineno - 1)183 assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' % len(ast.node.nodes)136- return ast.node.nodes[0]184+ result = ast.node.nodes[0]185+ nodes.inc_lineno(lineno, result)186+ return result187 188 def parse(self):189 """140- Parse the template and return a nodelist.190+ Parse the template and return a Template.191 """142- return self.subparse(None)192+ return nodes.Template(self.filename, self.subparse(None))193 194 def subparse(self, test, drop_needle=False):195 """196 Helper function used to parse the sourcecode until the test147- function which is passed a tuple in the form (pos, token, data)197+ function which is passed a tuple in the form (lineno, token, data)198 returns True. In that case the current token is pushed back to199 the tokenstream and the generator ends.200 201 The test function is only called for the first token after a7 unmodified lines209 if len(result) == 1:210 return result[0]211 return result212 163- pos = self.tokenstream.last[0]164- result = nodes.NodeList(pos)165- for pos, token, data in self.tokenstream:213+ lineno = self.tokenstream.last[0]214+ result = nodes.NodeList(lineno)215+ for lineno, token, data in self.tokenstream:216 # this token marks the begin or a variable section.217 # parse everything till the end of it.218 if token == 'variable_begin':219 gen = self.tokenstream.fetch_until(end_of_variable, True)170- result.append(self.directives['print'](pos, gen))220+ result.append(self.directives['print'](lineno, gen))221 222 # this token marks the start of a block. like for variables223 # just parse everything until the end of the block224 elif token == 'block_begin':225 gen = self.tokenstream.fetch_until(end_of_block, True)226 try:177- pos, token, data = gen.next()227+ lineno, token, data = gen.next()228 except StopIteration:179- raise TemplateSyntaxError('unexpected end of block', pos)229+ raise TemplateSyntaxError('unexpected end of block', lineno)230 231 # first token *must* be a name token232 if token != 'name':183- raise TemplateSyntaxError('unexpected %r token' % token, pos)233+ raise TemplateSyntaxError('unexpected %r token' % token, lineno)234 235 # if a test function is passed to subparse we check if we236 # reached the end of such a requested block.187- if test is not None and test(pos, token, data):237+ if test is not None and test(lineno, token, data):238 if not drop_needle:189- self.tokenstream.push(pos, token, data)239+ self.tokenstream.push(lineno, token, data)240 return finish()241 242 # the first token tells us which directive we want to call.243 # if if doesn't match any existing directive it's like a244 # template syntax error.245 if data in self.directives:196- node = self.directives[data](pos, gen)246+ node = self.directives[data](lineno, gen)247 else:198- raise TemplateSyntaxError('unknown directive %r' % data, pos)248+ raise TemplateSyntaxError('unknown directive %r' % data, lineno)249 result.append(node)250 251 # here the only token we should get is "data". all other252 # tokens just exist in block or variable sections. (if the253 # tokenizer is not brocken)254 elif token == 'data':205- result.append(nodes.Text(pos, data))255+ result.append(nodes.Text(lineno, data))256 257 # so this should be unreachable code258 else:209- raise AssertionError('unexpected token %r' % token)259+ raise AssertionError('unexpected token %r(%r)' % (token, data))260 261 # still here and a test function is provided? raise and error262 if test is not None:213- raise TemplateSyntaxError('unexpected end of template', pos)263+ raise TemplateSyntaxError('unexpected end of template', lineno)264 return finish()265 266 def close_remaining_block(self):267 """1 unmodified line269 tag we can use this method to drop the rest of the block from270 the stream. If the next token isn't the block end we throw an271 error.272 """223- pos = self.tokenstream.last[0]273+ lineno = self.tokenstream.last[0]274 try:225- pos, token, data = self.tokenstream.next()275+ lineno, token, data = self.tokenstream.next()276 except StopIteration:227- raise TemplateSyntaxError('missing closing tag', pos)277+ raise TemplateSyntaxError('missing closing tag', lineno)278 if token != 'block_end':229- raise TemplateSyntaxError('expected close tag, found %r' % token, pos)279+ raise TemplateSyntaxError('expected close tag, found %r' % token, lineno)added:jinja/tests.py+123 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja.tests4+ ~~~~~~~~~~~5+6+ Jinja test functions. Used with the "is" operator.7+8+ :copyright: 2006 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+import re12+from jinja.datastructure import Undefined13+14+15+number_re = re.compile(r'^-?\d+(\.\d+)$')16+17+regex_type = type(number_re)18+19+20+def test_odd():21+ """22+ {{ var is odd }}23+24+ Return True if the variable is odd.25+ """26+ return lambda e, c, v: v % 2 == 127+28+29+def test_even():30+ """31+ {{ var is even }}32+33+ Return True of the variable is even.34+ """35+ return lambda e, c, v: v % 2 == 036+37+38+def test_defined():39+ """40+ {{ var is defined }}41+42+ Return True if the variable is defined.43+ """44+ return lambda e, c, v: v is not Undefined45+46+47+def test_lower():48+ """49+ {{ var is lower }}50+51+ Return True if the variable is lowercase.52+ """53+ return lambda e, c, v: isinstance(v, basestring) and v.islower()54+55+56+def test_upper():57+ """58+ {{ var is upper }}59+60+ Return True if the variable is uppercase.61+ """62+ return lambda e, c, v: isinstance(v, basestring) and v.isupper()63+64+65+def test_numeric():66+ """67+ {{ var is numeric }}68+69+ Return True if the variable is numeric.70+ """71+ return lambda e, c, v: isinstance(v, (int, long, float)) or (72+ isinstance(v, basestring) and73+ number_re.match(v) is not None)74+75+76+def test_sequence():77+ """78+ {{ var is sequence }}79+80+ Return True if the variable is a sequence.81+ """82+ def wrapped(environment, context, value):83+ try:84+ len(value)85+ value.__getitem__86+ except:87+ return False88+ return True89+ return wrapped90+91+92+def test_matching(regex):93+ """94+ {{ var is matching('\d+$') }}95+96+ Test if the variable matches the regular expression97+ given. If the regular expression is a string additional98+ slashes are automatically added, if it's a compiled regex99+ it's used without any modifications.100+ """101+ if isinstance(regex, unicode):102+ regex = re.compile(regex.encode('unicode-escape'), re.U)103+ elif isinstance(regex, unicode):104+ regex = re.compile(regex.encode('string-escape'))105+ elif type(regex) is not regex_type:106+ regex = None107+ def wrapped(environment, context, value):108+ if regex is None:109+ return False110+ else:111+ return regex.match(value)112+ return wrapped113+114+TESTS = {115+ 'odd': test_odd,116+ 'even': test_even,117+ 'defined': test_defined,118+ 'lower': test_lower,119+ 'upper': test_upper,120+ 'numeric': test_numeric,121+ 'sequence': test_sequence,122+ 'matching': test_matching123+}