Skip to content
Myr

improved exception system. now both name (load name) and filename are passed.

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 a7f016d · Browse files · 7 files+76 added−93 removed
This commit

State

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

Diff stats

7 files+76 added−93 removed

  • other:+76 added−93 removed

7 files+76 added−93 removed

modified:docs/extensions.rst+1 added-1 removed
165 unmodified lines
166extensions:167168.. autoclass:: jinja2.parser.Parser169 :members: parse_expression, parse_tuple, parse_assign_target,170 parse_statements, free_identifier170 parse_statements, free_identifier, fail171172 .. attribute:: filename173174 The filename of the template the parser processes. This is **not**
49 unmodified lines
modified:jinja2/compiler.py+8 added-5 removed
595 unmodified lines
596 vars = ', '.join(sorted(overriden_closure_vars))597 raise TemplateAssertionError('It\'s not possible to set and '598 'access variables derived from '599 'an outer scope! (affects: %s' %600 vars, node.lineno, self.filename)600 vars, node.lineno, self.name,601 self.filename)602603 # remove variables from a closure from the frame's undeclared604 # identifiers.605 func_frame.identifiers.undeclared -= (
42 unmodified lines
648 for block in node.find_all(nodes.Block):649 if block.name in self.blocks:650 raise TemplateAssertionError('block %r defined twice' %651 block.name, block.lineno,651 self.filename)652 self.name, self.filename)653 self.blocks[block.name] = block654655 # find all imports and import them656 for import_ in node.find_all(nodes.ImportedName):
94 unmodified lines
751 """Calls the extender."""752 if not frame.toplevel:753 raise TemplateAssertionError('cannot use extend from a non '754 'top-level scope', node.lineno,754 self.filename)755 self.name, self.filename)756757 # if the number of extends statements in general is zero so758 # far, we don't have to add a check if something extended759 # the template before this one.
632 unmodified lines
1392 self.write(self.filters[node.name] + '(')1393 func = self.environment.filters.get(node.name)1394 if func is None:1395 raise TemplateAssertionError('no filter named %r' % node.name,1395 node.lineno, self.filename)1396 node.lineno, self.name,1397 self.filename)1398 if getattr(func, 'contextfilter', False):1399 self.write('context, ')1400 elif getattr(func, 'environmentfilter', False):1401 self.write('environment, ')
9 unmodified lines
1411 def visit_Test(self, node, frame):1412 self.write(self.tests[node.name] + '(')1413 if node.name not in self.environment.tests:1414 raise TemplateAssertionError('no test named %r' % node.name,1413 node.lineno, self.filename)1415 node.lineno, self.name,1416 self.filename)1417 self.visit(node.node, frame)1418 self.signature(node, frame)1419 self.write(')')1420
29 unmodified lines
modified:jinja2/environment.py+5 added-5 removed
286 unmodified lines
287 return obj[argument]288 except (TypeError, LookupError):289 return self.undefined(obj=obj, name=argument)290291 def parse(self, source, filename=None):291 def parse(self, source, name=None, filename=None):292 """Parse the sourcecode and return the abstract syntax tree. This293 tree of nodes is used by the compiler to convert the template into294 executable source- or bytecode. This is useful for debugging or to295 extract information from templates.
1 unmodified line
297 If you are :ref:`developing Jinja2 extensions <writing-extensions>`298 this gives you a good overview of the node tree generated.299 """300 try:301 return Parser(self, source, filename).parse()301 return Parser(self, source, name, filename).parse()302 except TemplateSyntaxError, e:303 from jinja2.debug import translate_syntax_error304 exc_type, exc_value, tb = translate_syntax_error(e)305 raise exc_type, exc_value, tb306307 def lex(self, source, filename=None):307 def lex(self, source, name=None, filename=None):308 """Lex the given sourcecode and return a generator that yields309 tokens as tuples in the form ``(lineno, token_type, value)``.310 This can be useful for :ref:`extension development <writing-extensions>`311 and debugging templates.312 """313 return self.lexer.tokeniter(source, filename)313 return self.lexer.tokeniter(source, name, filename)314315 def compile(self, source, name=None, filename=None, raw=False):316 """Compile a node or template source code. The `name` parameter is317 the load name of the template after it was joined using
7 unmodified lines
325 code equivalent to the bytecode returned otherwise. This method is326 mainly used internally.327 """328 if isinstance(source, basestring):329 source = self.parse(source, filename)329 source = self.parse(source, name, filename)330 if self.optimized:331 node = optimize(source, self)332 source = generate(node, self, name, filename)333 if raw:
341 unmodified lines
modified:jinja2/exceptions.py+7 added-2 removed
33 unmodified lines
3435class TemplateSyntaxError(TemplateError):36 """Raised to tell the user that there is a problem with the template."""3738 def __init__(self, message, lineno, filename):39 TemplateError.__init__(self, '%s (line %s)' % (message, lineno))38 def __init__(self, message, lineno, name=None, filename=None):39 if name is not None:40 extra = '%s, line %d' % (name, lineno)41 else:42 extra = 'line %d' % lineno43 TemplateError.__init__(self, '%s (%s)' % (message, extra))44 self.message = message45 self.lineno = lineno46 self.name = name47 self.filename = filename484950class TemplateAssertionError(TemplateSyntaxError):
14 unmodified lines
modified:jinja2/ext.py+8 added-14 removed
147 unmodified lines
148 break149150 name = parser.stream.expect('name')151 if name.value in variables:152 raise TemplateAssertionError('translatable variable %r defined '153 'twice.' % name.value, name.lineno,154 parser.filename)152 parser.fail('translatable variable %r defined twice.' %153 name.value, name.lineno,154 exc=TemplateAssertionError)155156 # expressions157 if parser.stream.current.type is 'assign':158 parser.stream.next()
42 unmodified lines
201202 if not have_plural:203 plural_expr = None204 elif plural_expr is None:205 raise TemplateAssertionError('pluralize without variables',206 lineno, parser.filename)205 parser.fail('pluralize without variables', lineno)206207 if variables:208 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)209 for x, y in variables.items()])
24 unmodified lines
234 break235 elif parser.stream.current.test('name:pluralize'):236 if allow_pluralize:237 break239 raise TemplateSyntaxError('a translatable section can '240 'have only one pluralize '241 'section',242 parser.stream.current.lineno,243 parser.filename)244 raise TemplateSyntaxError('control structures in translatable'245 ' sections are not allowed.',246 parser.stream.current.lineno,247 parser.filename)238 parser.fail('a translatable section can have only one '239 'pluralize section')240 parser.fail('control structures in translatable sections are '241 'not allowed')242 else:243 assert False, 'internal parser error'244245 return referenced, concat(buf)
124 unmodified lines
modified:jinja2/lexer.py+23 added-42 removed
67 unmodified lines
68assert len(operators) == len(reverse_operators), 'operators dropped'69operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in70 sorted(operators, key=lambda x: -len(x))))7172simple_escapes = {73 'a': '\a',74 'n': '\n',75 'r': '\r',76 'f': '\f',77 't': '\t',78 'v': '\v',79 '\\': '\\',80 '"': '"',81 "'": "'",82 '0': '\x00'83}84unicode_escapes = {85 'x': 2,86 'u': 4,87 'U': 888}729091def unescape_string(lineno, filename, s):92 r"""Unescape a string. Supported escapes:93 \a, \n, \r\, \f, \v, \\, \", \', \09495 \x00, \u0000, \U00000000, \N{...}96 """97 try:98 return s.encode('ascii', 'backslashreplace').decode('unicode-escape')99 except UnicodeError, e:100 msg = str(e).split(':')[-1].strip()101 raise TemplateSyntaxError(msg, lineno, filename)10210373class Failure(object):74 """Class that raises a `TemplateSyntaxError` if called.75 Used by the `Lexer` to specify known errors.76 """
77 unmodified lines
154 parser however does not iterate over it but calls :meth:`next` to go155 one token ahead. The current active token is stored as :attr:`current`.156 """157189 def __init__(self, generator, filename):158 def __init__(self, generator, name, filename):159 self._next = generator.next160 self._pushed = deque()161 self.current = Token(1, 'initial', '')162 self.name = name163 self.filename = filename164 self.next()165166 def __iter__(self):
60 unmodified lines
227 if self.current.type is 'eof':228 raise TemplateSyntaxError('unexpected end of template, '229 'expected %r.' % expr,230 self.current.lineno,261 self.filename)231 self.name, self.filename)232 raise TemplateSyntaxError("expected token %r, got %r" %233 (expr, str(self.current)),234 self.current.lineno,265 self.filename)235 self.name, self.filename)236 try:237 return self.current238 finally:239 self.next()
127 unmodified lines
367 (c(r'\s*(\n|$)'), 'linestatement_end', '#pop')368 ] + tag_rules369 }370401 def tokenize(self, source, filename=None):371 def tokenize(self, source, name=None, filename=None):372 """Works like `tokeniter` but returns a tokenstream of tokens and not373 a generator or token tuples. Additionally all token values are already374 converted into types and postprocessed. For example comments are removed,375 integers and floats converted, strings unescaped etc.376 """377 source = unicode(source)378 def generate():409 for lineno, token, value in self.tokeniter(source, filename):379 for lineno, token, value in self.tokeniter(source, name, filename):380 if token in ('comment_begin', 'comment', 'comment_end'):381 continue382 elif token == 'linestatement_begin':383 token = 'block_begin'
11 unmodified lines
395 token = value396 elif token == 'name':397 value = str(value)398 elif token == 'string':429 value = unescape_string(lineno, filename, value[1:-1])399 # try to unescape string400 try:401 value = value[1:-1] \402 .encode('ascii', 'backslashreplace') \403 .decode('unicode-escape')404 except Exception, e:405 msg = str(e).split(':')[-1].strip()406 raise TemplateSyntaxError(msg, lineno, name, filename)407 # if we can express it as bytestring (ascii only)408 # we do that for support of semi broken APIs409 # as datetime.datetime.strftime410 try:411 value = str(value)412 except UnicodeError:413 pass414 elif token == 'integer':
2 unmodified lines
417 value = float(value)418 elif token == 'operator':419 token = operators[value]420 yield Token(lineno, token, value)441 return TokenStream(generate(), filename)421 return TokenStream(generate(), name, filename)422443 def tokeniter(self, source, filename=None):423 def tokeniter(self, source, name, filename=None):424 """This method tokenizes the text and returns the tokens in a425 generator. Use this method if you just want to tokenize a template.426 The output you get is not compatible with the input the jinja parser427 wants. The parser uses the `tokenize` function with returns a
71 unmodified lines
499 balancing_stack.append(']')500 elif data in ('}', ')', ']'):501 if not balancing_stack:502 raise TemplateSyntaxError('unexpected "%s"' %523 data, lineno,503 data, lineno, name,504 filename)505 expected_op = balancing_stack.pop()506 if expected_op != data:507 raise TemplateSyntaxError('unexpected "%s", '508 'expected "%s"' %509 (data, expected_op),530 lineno, filename)510 lineno, name,511 filename)512 # yield items513 if tokens is not None:514 yield lineno, tokens, data515 lineno += data.count('\n')
40 unmodified lines
556 return557 # something went wrong558 raise TemplateSyntaxError('unexpected char %r at %d' %559 (source[pos], pos), lineno,579 filename)560 name, filename)
modified:jinja2/parser.py+24 added-24 removed
21 unmodified lines
22 """This is the central parsing class Jinja2 uses. It's passed to23 extensions and can be used to parse expressions or statements.24 """2526 def __init__(self, environment, source, filename=None):26 def __init__(self, environment, source, name=None, filename=None):27 self.environment = environment28 if isinstance(filename, unicode):29 filename = filename.encode('utf-8')30 self.source = unicode(source)31 self.name = name32 self.filename = filename33 self.closed = False34 self.stream = environment.lexer.tokenize(self.source, filename)35 self.extensions = {}
1 unmodified line
37 for tag in extension.tags:38 self.extensions[tag] = extension.parse39 self._last_identifier = 04041 def fail(self, msg, lineno=None, exc=TemplateSyntaxError):42 """Convenience method that raises `exc` with the message, passed43 line number or last line number as well as the current name and44 filename.45 """46 if lineno is None:47 lineno = self.stream.current.lineno48 raise TemplateSyntaxError(msg, lineno, self.name, self.filename)4950 def is_tuple_end(self, extra_end_rules=None):51 """Are we at the end of a tuple?"""52 if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):53 return True
11 unmodified lines
65 def parse_statement(self):66 """Parse a single statement."""67 token = self.stream.current68 if token.type is not 'name':59 raise TemplateSyntaxError('tag name expected', token.lineno,60 self.filename)69 self.fail('tag name expected', token.lineno)70 if token.value in _statement_keywords:71 return getattr(self, 'parse_' + self.stream.current.value)()72 if token.value == 'call':73 return self.parse_call_block()
1 unmodified line
75 return self.parse_filter_block()76 ext = self.extensions.get(token.value)77 if ext is not None:78 return ext(self)70 raise TemplateSyntaxError('unknown tag %r' % token.value,71 token.lineno, self.filename)79 self.fail('unknown tag %r' % token.value, token.lineno)8081 def parse_statements(self, end_tokens, drop_needle=False):82 """Parse multiple statements into a list until one of the end tokens83 is reached. This is used to parse the body of statements as it also
117 unmodified lines
201 if parse_context():202 break203 target = self.parse_assign_target(name_only=True)204 if target.name.startswith('__'):197 raise TemplateAssertionError('names starting with two '198 'underscores can not be '199 'imported', target.lineno,200 self.filename)205 self.fail('names starting with two underscores can not '206 'be imported', target.lineno,207 exc=TemplateAssertionError)208 if self.stream.skip_if('name:as'):209 alias = self.parse_assign_target(name_only=True)210 node.names.append((target.name, alias.name))211 else:
30 unmodified lines
242 node.defaults = []243244 node.call = self.parse_expression()245 if not isinstance(node.call, nodes.Call):239 raise TemplateSyntaxError('expected call', node.lineno,240 self.filename)246 self.fail('expected call', node.lineno)247 node.body = self.parse_statements(('name:endcall',), drop_needle=True)248 return node249250 def parse_filter_block(self):
39 unmodified lines
290 else:291 target = self.parse_primary(with_postfix=False)292 target.set_ctx('store')293 if not target.can_assign():288 raise TemplateSyntaxError('can\'t assign to %r' %289 target.__class__.__name__.lower(),290 target.lineno, self.filename)294 self.fail('can\'t assign to %r' % target.__class__.295 __name__.lower(), target.lineno)296 return target297298 def parse_expression(self, with_condexpr=True):299 """Parse an expression. Per default all expressions are parsed, if
173 unmodified lines
473 node = self.parse_list()474 elif token.type is 'lbrace':475 node = self.parse_dict()476 else:472 raise TemplateSyntaxError("unexpected token '%s'" %473 (token,), token.lineno,474 self.filename)477 self.fail("unexpected token '%s'" % (token,), token.lineno)478 if with_postfix:479 node = self.parse_postfix(node)480 return node481
83 unmodified lines
565 token = self.stream.next()566 if token.type is 'dot':567 attr_token = self.stream.current568 if attr_token.type not in ('name', 'integer'):566 raise TemplateSyntaxError('expected name or number',567 attr_token.lineno, self.filename)569 self.fail('expected name or number', attr_token.lineno)570 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)571 self.stream.next()572 elif token.type is 'lbracket':573 args = []
6 unmodified lines
580 arg = args[0]581 else:582 arg = nodes.Tuple(args, self.lineno, self.filename)583 else:582 raise TemplateSyntaxError('expected subscript expression',583 self.lineno, self.filename)584 self.fail('expected subscript expression', self.lineno)585 return nodes.Subscript(node, arg, 'load', lineno=token.lineno)586587 def parse_subscribed(self):588 lineno = self.stream.current.lineno
34 unmodified lines
623 require_comma = False624625 def ensure(expr):626 if not expr:626 raise TemplateSyntaxError('invalid syntax for function '627 'call expression', token.lineno,628 self.filename)627 self.fail('invalid syntax for function call expression',628 token.lineno)629630 while self.stream.current.type is not 'rparen':631 if require_comma:632 self.stream.expect('comma')
123 unmodified lines