Skip to content
Myr

Jinja doesn't have keywords any longer. The reason for this radical change is that the previous keywords where incompatible with the python keywords which made it impossible to name a variable "filter" or call a function with such a keyword parameter.

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 000b491 · Browse files · 6 files+75 added−73 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+75 added−73 removed

  • tests:+1 added−0 removed
  • other:+74 added−73 removed

6 files+75 added−73 removed

modified:jinja2/datastructure.py+3 added-7 removed
12 unmodified lines
13from jinja2.exceptions import TemplateSyntaxError, TemplateRuntimeError141516class Token(tuple):17 """18 Token class.19 """17 """Token class."""18 __slots__ = ()19 lineno, type, value = (property(itemgetter(x)) for x in range(3))2021 def __new__(cls, lineno, type, value):
37 unmodified lines
59 )606162class TokenStreamIterator(object):65 """66 The iterator for tokenstreams. Iterate over the stream63 """The iterator for tokenstreams. Iterate over the stream64 until the eof token is reached.65 """6667 def __init__(self, stream):
11 unmodified lines
79 return token808182class TokenStream(object):86 """87 A token stream wraps a generator and supports pushing tokens back.83 """A token stream wraps a generator and supports pushing tokens back.84 It also provides some functions to expect tokens and similar stuff.8586 Important note: Do never push more than one token back to the87 stream. Although the stream object won't stop you
75 unmodified lines
modified:jinja2/environment.py+2 added-1 removed
89 unmodified lines
9091 `variable_start_string`92 The string marking the begin of a print statement.93 Defaults to ``'{{'``.94 9495 `variable_stop_string`96 The string marking the end of a print statement. Defaults to ``'}}'``.9798 `comment_start_string`
184 unmodified lines
283 """284 try:285 return Parser(self, source, filename).parse()286 except TemplateSyntaxError, e:287 raise288 exc_type, exc_value, tb = translate_syntax_error(e)289 raise exc_type, exc_value, tb290291 def lex(self, source, name=None):
370 unmodified lines
modified:jinja2/ext.py-1 removed
12 unmodified lines
13from collections import deque14from jinja2 import nodes15from jinja2.environment import get_spontaneous_environment16from jinja2.runtime import Undefined, concat17from jinja2.parser import statement_end_tokens17from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError18from jinja2.utils import import_string, Markup1920
292 unmodified lines
modified:jinja2/lexer.py+1 added-11 removed
31 unmodified lines
32integer_re = re.compile(r'\d+')33name_re = re.compile(r'\b[a-zA-Z_][a-zA-Z0-9_]*\b')34float_re = re.compile(r'\d+\.\d+')3536# set of used keywords37keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',38 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',39 'extends', 'filter', 'for', 'if', 'in', 'include',40 'is', 'macro', 'not', 'or', 'raw', 'call', 'endcall',41 'from', 'import'])4236# bind operators to token types37operators = {38 '+': 'add',39 '-': 'sub',
113 unmodified lines
153 tag_rules = [154 (whitespace_re, None, None),155 (float_re, 'float', None),156 (integer_re, 'integer', None),164 (c(r'\b(?:%s)\b' % '|'.join(sorted(keywords, key=lambda x: -len(x)))),165 'keyword', None),157 (name_re, 'name', None),158 (string_re, 'string', None),159 (operator_re, 'operator', None)160 ]
83 unmodified lines
244245 def tokenize(self, source, filename=None):246 """Works like `tokeniter` but returns a tokenstream of tokens and not247 a generator or token tuples. Additionally all token values are already257 converted into types and postprocessed. For example keywords are258 already keyword tokens, not named tokens, comments are removed,248 converted into types and postprocessed. For example comments are removed,249 integers and floats converted, strings unescaped etc.250 """251 source = unicode(source)252 def generate():
171 unmodified lines
modified:jinja2/parser.py+68 added-53 removed
11 unmodified lines
12from jinja2 import nodes13from jinja2.exceptions import TemplateSyntaxError141516statement_end_tokens = set(['variable_end', 'block_end', 'in'])16_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',17 'macro', 'include', 'from', 'import'])19_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq', 'in'])20_tuple_edge_tokens = set(['rparen']) | statement_end_tokens18_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])192021class Parser(object):22 """The template parser class.
13 unmodified lines
36 for extension in environment.extensions:37 for tag in extension.tags:38 self.extensions[tag] = extension.parse3940 def is_statement_end(self):41 """Are we at the end of a statement?"""42 if self.stream.current.type in ('variable_end', 'block_end'):43 return True44 return self.stream.current.test('name:in')4546 def is_tuple_end(self):47 """Are we at the end of a tuple?"""48 return self.stream.current.type is 'rparen' or self.is_statement_end()4950 def parse_statement(self):51 """Parse a single statement."""52 token_type = self.stream.current.type53 if self.stream.current.type is 'name':45 if token_type in _statement_keywords:46 return getattr(self, 'parse_' + token_type)()47 elif token_type is 'call':48 return self.parse_call_block()49 elif token_type is 'filter':50 return self.parse_filter_block()51 elif token_type is 'name':52 ext = self.extensions.get(self.stream.current.value)53 if ext is not None:54 return ext(self)54 if self.stream.current.value in _statement_keywords:55 return getattr(self, 'parse_' + self.stream.current.value)()56 elif self.stream.current.value == 'call':57 return self.parse_call_block()58 elif self.stream.current.value == 'filter':59 return self.parse_filter_block()60 else:61 ext = self.extensions.get(self.stream.current.value)62 if ext is not None:63 return ext(self)64 lineno = self.stream.current.lineno65 expr = self.parse_tuple()66 if self.stream.current.type == 'assign':67 result = self.parse_assign(expr)
31 unmodified lines
99 return result100101 def parse_for(self):102 """Parse a for loop."""94 lineno = self.stream.expect('for').lineno103 lineno = self.stream.expect('name:for').lineno104 target = self.parse_tuple(simplified=True)105 if not target.can_assign():106 raise TemplateSyntaxError("can't assign to '%s'" %107 target.__class__.__name__.lower(),108 target.lineno, self.filename)109 target.set_ctx('store')101 self.stream.expect('in')110 self.stream.expect('name:in')111 iter = self.parse_tuple(no_condexpr=True)112 test = None104 if self.stream.current.type is 'if':113 if self.stream.current.type is 'name:if':114 self.stream.next()115 test = self.parse_expression()107 body = self.parse_statements(('endfor', 'else'))108 if self.stream.next().type is 'endfor':116 body = self.parse_statements(('name:endfor', 'name:else'))117 if self.stream.next().value == 'endfor':118 else_ = []119 else:111 else_ = self.parse_statements(('endfor',), drop_needle=True)120 else_ = self.parse_statements(('name:endfor',), drop_needle=True)121 return nodes.For(target, iter, body, else_, test, lineno=lineno)122123 def parse_if(self):124 """Parse an if construct."""116 node = result = nodes.If(lineno=self.stream.expect('if').lineno)125 node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)126 while 1:127 # TODO: exclude conditional expressions here128 node.test = self.parse_tuple()120 node.body = self.parse_statements(('elif', 'else', 'endif'))121 token_type = self.stream.next().type122 if token_type is 'elif':129 node.body = self.parse_statements(('name:elif', 'name:else',130 'name:endif'))131 token = self.stream.next()132 if token.test('name:elif'):133 new_node = nodes.If(lineno=self.stream.current.lineno)134 node.else_ = [new_node]135 node = new_node136 continue127 elif token_type is 'else':128 node.else_ = self.parse_statements(('endif',),137 elif token.test('name:else'):138 node.else_ = self.parse_statements(('name:endif',),139 drop_needle=True)140 else:141 node.else_ = []142 break143 return result144145 def parse_block(self):136 node = nodes.Block(lineno=self.stream.expect('block').lineno)146 node = nodes.Block(lineno=self.stream.next().lineno)147 node.name = self.stream.expect('name').value138 node.body = self.parse_statements(('endblock',), drop_needle=True)148 node.body = self.parse_statements(('name:endblock',), drop_needle=True)149 return node150151 def parse_extends(self):142 node = nodes.Extends(lineno=self.stream.expect('extends').lineno)152 node = nodes.Extends(lineno=self.stream.next().lineno)153 node.template = self.parse_expression()154 return node155156 def parse_include(self):147 node = nodes.Include(lineno=self.stream.expect('include').lineno)157 node = nodes.Include(lineno=self.stream.next().lineno)158 node.template = self.parse_expression()159 return node160161 def parse_import(self):152 node = nodes.Import(lineno=self.stream.expect('import').lineno)162 node = nodes.Import(lineno=self.stream.next().lineno)163 node.template = self.parse_expression()164 self.stream.expect('name:as')165 node.target = self.stream.expect('name').value166 if not nodes.Name(node.target, 'store').can_assign():
2 unmodified lines
169 self.filename)170 return node171172 def parse_from(self):163 node = nodes.FromImport(lineno=self.stream.expect('from').lineno)173 node = nodes.FromImport(lineno=self.stream.next().lineno)174 node.template = self.parse_expression()165 self.stream.expect('import')175 self.stream.expect('name:import')176 node.names = []177 while 1:178 if node.names:179 self.stream.expect('comma')
46 unmodified lines
226 args.append(arg)227 self.stream.expect('rparen')228229 def parse_call_block(self):220 node = nodes.CallBlock(lineno=self.stream.expect('call').lineno)230 node = nodes.CallBlock(lineno=self.stream.next().lineno)231 if self.stream.current.type is 'lparen':232 self.parse_signature(node)233 else:234 node.args = []
2 unmodified lines
237 node.call = self.parse_expression()238 if not isinstance(node.call, nodes.Call):239 raise TemplateSyntaxError('expected call', node.lineno,240 self.filename)231 node.body = self.parse_statements(('endcall',), drop_needle=True)241 node.body = self.parse_statements(('name:endcall',), drop_needle=True)242 return node243244 def parse_filter_block(self):235 node = nodes.FilterBlock(lineno=self.stream.expect('filter').lineno)245 node = nodes.FilterBlock(lineno=self.stream.next().lineno)246 node.filter = self.parse_filter(None, start_inline=True)237 node.body = self.parse_statements(('endfilter',), drop_needle=True)247 node.body = self.parse_statements(('name:endfilter',),248 drop_needle=True)249 return node250251 def parse_macro(self):241 node = nodes.Macro(lineno=self.stream.expect('macro').lineno)252 node = nodes.Macro(lineno=self.stream.next().lineno)253 node.name = self.stream.expect('name').value254 # make sure that assignments to that name are allowed255 if not nodes.Name(node.name, 'store').can_assign():256 raise TemplateSyntaxError('can\'t assign macro to %r' %257 node.target, node.lineno,258 self.filename)259 self.parse_signature(node)249 node.body = self.parse_statements(('endmacro',), drop_needle=True)260 node.body = self.parse_statements(('name:endmacro',),261 drop_needle=True)262 return node263264 def parse_print(self):253 node = nodes.Output(lineno=self.stream.expect('print').lineno)265 node = nodes.Output(lineno=self.stream.next().lineno)266 node.nodes = []255 while self.stream.current.type not in statement_end_tokens:267 while not self.is_statement_end():268 if node.nodes:269 self.stream.expect('comma')270 node.nodes.append(self.parse_expression())271 return node
6 unmodified lines
278279 def parse_condexpr(self):280 lineno = self.stream.current.lineno281 expr1 = self.parse_or()270 while self.stream.current.type is 'if':282 while self.stream.current.test('name:if'):283 self.stream.next()284 expr2 = self.parse_or()273 self.stream.expect('else')285 self.stream.expect('name:else')286 expr3 = self.parse_condexpr()287 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)288 lineno = self.stream.current.lineno289 return expr1290291 def parse_or(self):292 lineno = self.stream.current.lineno293 left = self.parse_and()282 while self.stream.current.type is 'or':294 while self.stream.current.test('name:or'):295 self.stream.next()296 right = self.parse_and()297 left = nodes.Or(left, right, lineno=lineno)298 lineno = self.stream.current.lineno
1 unmodified line
300301 def parse_and(self):302 lineno = self.stream.current.lineno303 left = self.parse_compare()292 while self.stream.current.type is 'and':304 while self.stream.current.test('name:and'):305 self.stream.next()306 right = self.parse_compare()307 left = nodes.And(left, right, lineno=lineno)308 lineno = self.stream.current.lineno
7 unmodified lines
316 token_type = self.stream.current.type317 if token_type in _compare_operators:318 self.stream.next()319 ops.append(nodes.Operand(token_type, self.parse_add()))308 elif token_type is 'not' and self.stream.look().type is 'in':320 elif self.stream.current.test('name:in'):321 self.stream.next()322 ops.append(nodes.Operand('in', self.parse_add()))323 elif self.stream.current.test('name:not') and \324 self.stream.look().test('name:in'):325 self.stream.skip(2)326 ops.append(nodes.Operand('notin', self.parse_add()))327 else:328 break
84 unmodified lines
413414 def parse_unary(self):415 token_type = self.stream.current.type416 lineno = self.stream.current.lineno401 if token_type is 'not':417 if token_type is 'name' and self.stream.current.value == 'not':418 self.stream.next()419 node = self.parse_unary()420 return nodes.Not(node, lineno=lineno)421 if token_type is 'sub':
35 unmodified lines
457 node = self.parse_postfix(node)458 return node459460 def parse_tuple(self, enforce=False, simplified=False, no_condexpr=False):445 """446 Parse multiple expressions into a tuple. This can also return461 """Parse multiple expressions into a tuple. This can also return462 just one expression which is not a tuple. If you want to enforce463 a tuple, pass it enforce=True (currently unused).464 """465 lineno = self.stream.current.lineno
7 unmodified lines
473 is_tuple = False474 while 1:475 if args:476 self.stream.expect('comma')462 if self.stream.current.type in _tuple_edge_tokens:477 if self.is_tuple_end():478 break479 args.append(parse())480 if self.stream.current.type is 'comma':481 is_tuple = True
42 unmodified lines
524 elif token_type is 'lparen':525 node = self.parse_call(node)526 elif token_type is 'pipe':527 node = self.parse_filter(node)513 elif token_type is 'is':528 elif token_type is 'name' and self.stream.current.value == 'is':529 node = self.parse_test(node)530 else:531 break532 return node
119 unmodified lines
652 start_inline = False653 return node654655 def parse_test(self, node):641 token = self.stream.expect('is')642 if self.stream.current.type is 'not':656 token = self.stream.next()657 if self.stream.current.test('name:not'):658 self.stream.next()659 negated = True660 else:661 negated = False
3 unmodified lines
665 if self.stream.current.type is 'lparen':666 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)667 elif self.stream.current.type in ('name', 'string', 'integer',668 'float', 'lparen', 'lbracket',654 'lbrace', 'regex'):669 'lbrace'):670 args = [self.parse_expression()]671 else:672 args = []673 node = nodes.Test(node, name, args, kwargs, dyn_args,
45 unmodified lines
modified:tests/test_syntax.py+1 added
152 unmodified lines
153154155def test_tuple_expr(env):156 for tmpl in TUPLETEMPLATES:157 print tmpl158 assert env.from_string(tmpl)159160161def test_trailing_comma(env):
2 unmodified lines