greatly improved error message reporting. This fixes #339
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk extra : rebase_source : d8f677273490fa73d5603b68478fa3b54f60ccb9
authored by Armin Ronacher · committed by Armin Ronacher · parent d9ea26e · Browse files · 4 files·+177 added−44 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+177 added−44 removed
- tests:+28 added−1 removed
- other:+149 added−43 removed
Provenance
- Commit
5dcb724- Tree
9feda40- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
d9ea26e
4 files changed+177 added−44 removed
modified:jinja2/lexer.py+42 added-6 removed
137 unmodified lines138 ignore_if_empty = frozenset([TOKEN_WHITESPACE, TOKEN_DATA,139 TOKEN_COMMENT, TOKEN_LINECOMMENT])140 141 142+def _describe_token_type(token_type):143+ if token_type in reverse_operators:144+ return reverse_operators[token_type]145+ return {146+ TOKEN_COMMENT_BEGIN: 'begin of comment',147+ TOKEN_COMMENT_END: 'end of comment',148+ TOKEN_COMMENT: 'comment',149+ TOKEN_LINECOMMENT: 'comment',150+ TOKEN_BLOCK_BEGIN: 'begin of statement block',151+ TOKEN_BLOCK_END: 'end of statement block',152+ TOKEN_VARIABLE_BEGIN: 'begin of print statement',153+ TOKEN_VARIABLE_END: 'end of print statement',154+ TOKEN_LINESTATEMENT_BEGIN: 'begin of line statement',155+ TOKEN_LINESTATEMENT_END: 'end of line statement',156+ TOKEN_DATA: 'template data / text',157+ TOKEN_EOF: 'end of template'158+ }.get(token_type, token_type)159+160+161+def describe_token(token):162+ """Returns a description of the token."""163+ if token.type == 'name':164+ return token.value165+ return _describe_token_type(token.type)166+167+168+def describe_token_expr(expr):169+ """Like `describe_token` but for token expressions."""170+ if ':' in expr:171+ type, value = expr.split(':', 1)172+ if type == 'name':173+ return value174+ else:175+ type = expr176+ return _describe_token_type(type)177+178+179 def count_newlines(value):180 """Count the number of newline characters in the string. This is181 useful for extensions that filter a stream.182 """172 unmodified lines355 """Expect a given token type and return it. This accepts the same356 argument as :meth:`jinja2.lexer.Token.test`.357 """358 if not self.current.test(expr):322- if ':' in expr:323- expr = expr.split(':')[1]359+ expr = describe_token_expr(expr)360 if self.current.type is TOKEN_EOF:361 raise TemplateSyntaxError('unexpected end of template, '362 'expected %r.' % expr,363 self.current.lineno,364 self.name, self.filename)365 raise TemplateSyntaxError("expected token %r, got %r" %330- (expr, str(self.current)),366+ (expr, describe_token(self.current)),367 self.current.lineno,368 self.name, self.filename)369 try:370 return self.current246 unmodified lines617 elif data == '[':618 balancing_stack.append(']')619 elif data in ('}', ')', ']'):620 if not balancing_stack:585- raise TemplateSyntaxError('unexpected "%s"' %621+ raise TemplateSyntaxError('unexpected \'%s\'' %622 data, lineno, name,623 filename)624 expected_op = balancing_stack.pop()625 if expected_op != data:590- raise TemplateSyntaxError('unexpected "%s", '591- 'expected "%s"' %626+ raise TemplateSyntaxError('unexpected \'%s\', '627+ 'expected \'%s\'' %628 (data, expected_op),629 lineno, name,630 filename)631 # yield items48 unmodified linesmodified:jinja2/parser.py+105 added-36 removed
9 unmodified lines10 """11 from jinja2 import nodes12 from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13 from jinja2.utils import next14+from jinja2.lexer import describe_token, describe_token_expr15 16 17+#: statements that callinto 18 _statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',19 'macro', 'include', 'from', 'import',20 'set'])21 _compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])15 unmodified lines37 for extension in environment.extensions.itervalues():38 for tag in extension.tags:39 self.extensions[tag] = extension.parse40 self._last_identifier = 041+ self._tag_stack = []42+ self._end_token_stack = []43 44 def fail(self, msg, lineno=None, exc=TemplateSyntaxError):45 """Convenience method that raises `exc` with the message, passed46 line number or last line number as well as the current name and2 unmodified lines49 if lineno is None:50 lineno = self.stream.current.lineno51 raise exc(msg, lineno, self.name, self.filename)52 53+ def _fail_ut_eof(self, name, end_token_stack, lineno):54+ expected = []55+ for exprs in end_token_stack:56+ expected.extend(map(describe_token_expr, exprs))57+ currently_looking = ' or '.join("'%s'" % describe_token_expr(expr)58+ for expr in end_token_stack[-1])59+60+ if name is None:61+ message = ['Unexpected end of template.']62+ else:63+ message = ['Encountered unknown tag \'%s\'.' % name]64+65+ if name is not None and name in expected:66+ message.append('You probably made a nesting mistake. Jinja '67+ 'is expecting this tag, but currently looking '68+ 'for %s.' % currently_looking)69+ else:70+ message.append('Jinja was looking for the following tags: '71+ '%s.' % currently_looking)72+73+ if self._tag_stack:74+ message.append('The innermost block that needs to be '75+ 'closed is \'%s\'.' % self._tag_stack[-1])76+77+ self.fail(' '.join(message), lineno)78+79+ def fail_unknown_tag(self, name, lineno=None):80+ """Called if the parser encounters an unknown tag. Tries to fail81+ with a human readable error message that could help to identify82+ the problem.83+ """84+ return self._fail_ut_eof(name, self._end_token_stack, lineno)85+86+ def fail_eof(self, end_tokens=None, lineno=None):87+ """Like fail_unknown_tag but for end of template situations."""88+ stack = list(self._end_token_stack)89+ if end_tokens is not None:90+ stack.append(end_tokens)91+ return self._fail_ut_eof(None, stack, lineno)92+93 def is_tuple_end(self, extra_end_rules=None):94 """Are we at the end of a tuple?"""95 if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):96 return True12 unmodified lines109 """Parse a single statement."""110 token = self.stream.current111 if token.type != 'name':112 self.fail('tag name expected', token.lineno)69- if token.value in _statement_keywords:70- return getattr(self, 'parse_' + self.stream.current.value)()71- if token.value == 'call':72- return self.parse_call_block()73- if token.value == 'filter':74- return self.parse_filter_block()75- ext = self.extensions.get(token.value)76- if ext is not None:77- return ext(self)78- self.fail('unknown tag %r' % token.value, token.lineno)113+ self._tag_stack.append(token.value)114+ pop_tag = True115+ try:116+ if token.value in _statement_keywords:117+ return getattr(self, 'parse_' + self.stream.current.value)()118+ if token.value == 'call':119+ return self.parse_call_block()120+ if token.value == 'filter':121+ return self.parse_filter_block()122+ ext = self.extensions.get(token.value)123+ if ext is not None:124+ return ext(self)125 126+ # did not work out, remove the token we pushed by accident127+ # from the stack so that the unknown tag fail function can128+ # produce a proper error message.129+ self._tag_stack.pop()130+ pop_tag = False131+ self.fail_unknown_tag(token.value, token.lineno)132+ finally:133+ if pop_tag:134+ self._tag_stack.pop()135+136 def parse_statements(self, end_tokens, drop_needle=False):137 """Parse multiple statements into a list until one of the end tokens138 is reached. This is used to parse the body of statements as it also139 parses template data if appropriate. The parser checks first if the10 unmodified lines150 # by adding some sort of end of statement token and parsing those here.151 self.stream.expect('block_end')152 result = self.subparse(end_tokens)153 154+ # we reached the end of the template too early, the subparser155+ # does not check for this, so we do that now156+ if self.stream.current.type == 'eof':157+ self.fail_eof(end_tokens)158+159 if drop_needle:160 next(self.stream)161 return result162 391 unmodified lines554 node = self.parse_list()555 elif token.type == 'lbrace':556 node = self.parse_dict()557 else:497- self.fail("unexpected token '%s'" % (token,), token.lineno)558+ self.fail("unexpected '%s'" % describe_token(token), token.lineno)559 if with_postfix:560 node = self.parse_postfix(node)561 return node562 239 unmodified lines802 body = []803 data_buffer = []804 add_data = data_buffer.append805 806+ if end_tokens is not None:807+ self._end_token_stack.append(end_tokens)808+809 def flush_data():810 if data_buffer:811 lineno = data_buffer[0].lineno812 body.append(nodes.Output(data_buffer[:], lineno=lineno))813 del data_buffer[:]814 815+ try:751- while self.stream:752- token = self.stream.current753- if token.type == 'data':754- if token.value:755- add_data(nodes.TemplateData(token.value,756- lineno=token.lineno))757- next(self.stream)758- elif token.type == 'variable_begin':759- next(self.stream)760- add_data(self.parse_tuple(with_condexpr=True))761- self.stream.expect('variable_end')762- elif token.type == 'block_begin':763- flush_data()764- next(self.stream)765- if end_tokens is not None and \766- self.stream.current.test_any(*end_tokens):767- return body768- rv = self.parse_statement()769- if isinstance(rv, list):770- body.extend(rv)816+ while self.stream:817+ token = self.stream.current818+ if token.type == 'data':819+ if token.value:820+ add_data(nodes.TemplateData(token.value,821+ lineno=token.lineno))822+ next(self.stream)823+ elif token.type == 'variable_begin':824+ next(self.stream)825+ add_data(self.parse_tuple(with_condexpr=True))826+ self.stream.expect('variable_end')827+ elif token.type == 'block_begin':828+ flush_data()829+ next(self.stream)830+ if end_tokens is not None and \831+ self.stream.current.test_any(*end_tokens):832+ return body833+ rv = self.parse_statement()834+ if isinstance(rv, list):835+ body.extend(rv)836+ else:837+ body.append(rv)838+ self.stream.expect('block_end')839 else:772- body.append(rv)773- self.stream.expect('block_end')774- else:775- raise AssertionError('internal parsing error')840+ raise AssertionError('internal parsing error')841 777- flush_data()842+ flush_data()843+ finally:844+ if end_tokens is not None:845+ self._end_token_stack.pop()846+847 return body848 849 def parse(self):850 """Parse the whole template into a `Template` node."""3 unmodified linesmodified:tests/test_parser.py+28 added-1 removed
4 unmodified lines5 6 :copyright: (c) 2009 by the Jinja Team.7 :license: BSD, see LICENSE for more details.8 """9-from jinja2 import Environment9+from jinja2 import Environment, Template, TemplateSyntaxError10 11 env = Environment()12 13 99 unmodified lines113 assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'114 env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')115 tmpl = env.from_string(LINE_SYNTAX_PRIORITY2)116 assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'117+118+119+def test_error_messages():120+ def assert_error(code, expected):121+ try:122+ Template(code)123+ except TemplateSyntaxError, e:124+ assert str(e) == expected, 'unexpected error message'125+ else:126+ assert False, 'that was suposed to be an error'127+128+ assert_error('{% for item in seq %}...{% endif %}',129+ "Encountered unknown tag 'endif'. Jinja was looking "130+ "for the following tags: 'endfor' or 'else'. The "131+ "innermost block that needs to be closed is 'for'.")132+ assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',133+ "Encountered unknown tag 'endfor'. Jinja was looking for "134+ "the following tags: 'elif' or 'else' or 'endif'. The "135+ "innermost block that needs to be closed is 'if'.")136+ assert_error('{% if foo %}',137+ "Unexpected end of template. Jinja was looking for the "138+ "following tags: 'elif' or 'else' or 'endif'. The "139+ "innermost block that needs to be closed is 'if'.")140+ assert_error('{% for item in seq %}',141+ "Unexpected end of template. Jinja was looking for the "142+ "following tags: 'endfor' or 'else'. The innermost block "143+ "that needs to be closed is 'for'.")modified:CHANGES+2 added-1 removed
1 unmodified line2 ================3 4 Version 2.35 -----------6-(codename to be selected, release date to be selected.)6+(codename to be selected, release date will be February 9th 2010)7 8 - fixes issue with code generator that causes unbound variables9 to be generated if set was used in if-blocks and other small10 identifier problems.2 unmodified lines13 given.14 - fixed a problem with having call blocks in outer scopes that15 have an argument that is also used as local variable in an16 inner frame [#360].17+- greatly improved error message reporting (#339)18 19 Version 2.2.120 -------------21 (bugfix release, released on September 14th 2009)114 unmodified lines