[svn] implemented compile time error handling
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 9baa5ba · Browse files · 7 files·+219 added−85 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+219 added−85 removed
- tests:+66 added−11 removed
- other:+153 added−74 removed
Provenance
- Commit
8ff24c4- Tree
962c3ad- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
9baa5ba
7 files changed+219 added−85 removed
modified:jinja/datastructure.py+2 added-2 removed
13 unmodified lines14 set15 except NameError:16 from sets import Set as set17 18-from jinja.exceptions import TemplateRuntimeError18+from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError19 20 21 def contextcallable(f):22 """336 unmodified lines359 return360 else:361 yield token362 except StopIteration:363- raise IndexError('end of stream reached')363+ raise TemplateSyntaxError('end of stream reached')364 365 def drop_until(self, test, drop_needle=False):366 """Fetch tokens until a function matches and drop all367 tokens."""6 unmodified linesmodified:jinja/exceptions.py+2 added-1 removed
68 unmodified lines69 """70 Raised to tell the user that there is a problem with the template.71 """72 73- def __init__(self, message, lineno):73+ def __init__(self, message, lineno, filename):74 SyntaxError.__init__(self, message)75 self.lineno = lineno76+ self.filename = filename77 78 79 class TemplateRuntimeError(TemplateError):80 """3 unmodified linesmodified:jinja/loaders.py+8 added-3 removed
14 unmodified lines15 from os import path16 from threading import Lock17 from jinja.parser import Parser18 from jinja.translators.python import PythonTranslator, Template19-from jinja.exceptions import TemplateNotFound20-from jinja.utils import CacheDict19+from jinja.exceptions import TemplateNotFound, TemplateSyntaxError20+from jinja.utils import CacheDict, raise_syntax_error21 try:22 from pkg_resources import resource_exists, resource_string, \23 resource_filename24 except ImportError:22 unmodified lines47 48 class LoaderWrapper(object):49 """50 Wraps a loader so that it's bound to an environment.51+ Also handles template syntax errors.52 """53 54 def __init__(self, environment, loader):55 self.environment = environment23 unmodified lines79 will just output a string with the translated code.80 """81 # just ascii chars are allowed as template names82 name = str(name)83+ try:82- return self.loader.load(self.environment, name, translator)84+ return self.loader.load(self.environment, name, translator)85+ except TemplateSyntaxError, e:86+ __traceback_hide__ = True87+ raise_syntax_error(e, self.environment)88 89 def _loader_missing(self, *args, **kwargs):90 """Helper method that overrides all other methods if no91 loader is defined."""384 unmodified linesmodified:jinja/parser.py+117 added-59 removed
69 unmodified lines70 self.extends = None71 self.blocks = set()72 73 self.directives = {74+ 'raw': self.handle_raw_directive,75 'for': self.handle_for_directive,76 'if': self.handle_if_directive,77 'cycle': self.handle_cycle_directive,78 'set': self.handle_set_directive,5 unmodified lines84 'include': self.handle_include_directive,85 'trans': self.handle_trans_directive86 }87 88+ def handle_raw_directive(self, lineno, gen):89+ """90+ Handle fake raw directive. (real raw directives are handled by91+ the lexer. But if there are arguments to raw or the end tag92+ is missing the parser tries to resolve this directive. In that93+ case present the user a useful error message.94+ """95+ args = list(gen)96+ if args:97+ raise TemplateSyntaxError('raw directive does not support '98+ 'any arguments.', lineno,99+ self.filename)100+ raise TemplateSyntaxError('missing end tag for raw directive.',101+ lineno, self.filename)102+103 def handle_for_directive(self, lineno, gen):104 """105 Handle a for directive and return a ForLoop node106 """69 unmodified lines176 name = gen.next()177 if name[1] != 'name' or gen.next()[1:] != ('operator', '='):178 raise ValueError()179 except (StopIteration, ValueError):164- raise TemplateSyntaxError('invalid syntax for set', lineno)180+ raise TemplateSyntaxError('invalid syntax for set', lineno,181+ self.filename)182 ast = self.parse_python(lineno, gen, '(%s)')183 # disallow keywords184 if not name[2].endswith('_'):185 raise TemplateSyntaxError('illegal use of keyword %r '186 'as identifier in set statement.' %170- name[2], lineno)187+ name[2], lineno, self.filename)188 return nodes.Set(lineno, str(name[2][:-1]), ast.expr)189 190 def handle_filter_directive(self, lineno, gen):191 """15 unmodified lines207 # we only accept one argument208 if len(arguments) != 1:209 raise TemplateSyntaxError('invalid argument count for print; '210 'print requires exactly one argument, '194- 'got %d.' % len(arguments), lineno)211+ 'got %d.' % len(arguments), lineno,212+ self.filename)213 return nodes.Print(lineno, arguments[0])214 215 def handle_macro_directive(self, lineno, gen):216 """1 unmodified line218 """219 try:220 macro_name = gen.next()221 except StopIteration:204- raise TemplateSyntaxError('macro requires a name', lineno)222+ raise TemplateSyntaxError('macro requires a name', lineno,223+ self.filename)224 if macro_name[1] != 'name':225 raise TemplateSyntaxError('expected \'name\', got %r' %207- macro_name[1], lineno)226+ macro_name[1], lineno,227+ self.filename)228 # disallow keywords as identifiers229 elif not macro_name[2].endswith('_'):230 raise TemplateSyntaxError('illegal use of keyword %r '231 'as macro name.' % macro_name[2],212- lineno)232+ lineno, self.filename)233 234 ast = self.parse_python(lineno, gen, 'def %s(%%s):pass' %235 str(macro_name[2][:-1]))236 body = self.subparse(end_of_macro, True)237 self.close_remaining_block()238 239 if ast.varargs or ast.kwargs:240 raise TemplateSyntaxError('variable length macro signature '221- 'not allowed.', lineno)241+ 'not allowed.', lineno,242+ self.filename)243 if ast.argnames:223- defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + ast.defaults244+ defaults = [None] * (len(ast.argnames) - len(ast.defaults)) + \245+ ast.defaults246 args = []247 for idx, argname in enumerate(ast.argnames):248 # disallow keywords as argument names249 if not argname.endswith('_'):250 raise TemplateSyntaxError('illegal use of keyword %r '251 'as macro argument.' % argname,230- lineno)252+ lineno, self.filename)253 args.append((argname[:-1], defaults[idx]))254 else:255 args = None256 return nodes.Macro(lineno, ast.name, args, body)3 unmodified lines260 Handle block directives used for inheritance.261 """262 tokens = list(gen)263 if not tokens:242- raise TemplateSyntaxError('block requires a name', lineno)264+ raise TemplateSyntaxError('block requires a name', lineno,265+ self.filename)266 block_name = tokens.pop(0)267 if block_name[1] != 'name':268 raise TemplateSyntaxError('expected \'name\', got %r' %246- block_name[1], lineno)269+ block_name[1], lineno, seilf.filename)270 # disallow keywords271 if not block_name[2].endswith('_'):272 raise TemplateSyntaxError('illegal use of keyword %r '273 'as block name.' % block_name[2],251- lineno)274+ lineno, self.filename)275 name = block_name[2][:-1]276 if tokens:277 raise TemplateSyntaxError('block got too many arguments, '255- 'requires one.', lineno)278+ 'requires one.', lineno,279+ self.filename)280 281 # check if this block does not exist by now.282 if name in self.blocks:283 raise TemplateSyntaxError('block %r defined twice' %260- name, lineno)284+ name, lineno, self.filename)285 self.blocks.add(name)286 287 # now parse the body and attach it to the block288 body = self.subparse(end_of_block_tag, True)5 unmodified lines294 Handle the extends directive used for inheritance.295 """296 tokens = list(gen)297 if len(tokens) != 1 or tokens[0][1] != 'string':274- raise TemplateSyntaxError('extends requires a string', lineno)298+ raise TemplateSyntaxError('extends requires a string', lineno,299+ self.filename)300 if self.extends is not None:301 raise TemplateSyntaxError('extends called twice', lineno)302 self.extends = nodes.Extends(lineno, tokens[0][2][1:-1])303 2 unmodified lines306 Handle the include directive used for template inclusion.307 """308 tokens = list(gen)309 if len(tokens) != 1 or tokens[0][1] != 'string':285- raise TemplateSyntaxError('include requires a string', lineno)310+ raise TemplateSyntaxError('include requires a string', lineno,311+ self.filename)312 return nodes.Include(lineno, tokens[0][2][1:-1])313 314 def handle_trans_directive(self, lineno, gen):315 """15 unmodified lines331 try:332 gen.next()333 except StopIteration:334 #XXX: what about escapes?309- return nodes.Trans(lineno, data[1:-1], None, None, None)335+ return nodes.Trans(lineno, data[1:-1], None,336+ None, None)337 raise TemplateSyntaxError('string based translations '338 'require at most one argument.',312- lineno)339+ lineno, self.filename)340 # create a new generator with the popped item as first one341 def wrapgen(oldgen):342 yield lineno, token, data343 for item in oldgen:2 unmodified lines346 347 # block based translations348 first_var = None349 replacements = {}323- for arg in self.parse_python(lineno, gen, '_trans(%s)').expr.args:350+ for arg in self.parse_python(lineno, gen,351+ '_trans(%s)').expr.args:352 if arg.__class__ is not ast.Keyword:325- raise TemplateSyntaxError('translation tags need explicit '326- 'names for values.', lineno)327- # argument name doesn't end with "_"? that's a keyword then353+ raise TemplateSyntaxError('translation tags need expl'354+ 'icit names for values.',355+ lineno, self.filename)356+ # disallow keywords357 if not arg.name.endswith('_'):358 raise TemplateSyntaxError('illegal use of keyword %r '359 'as identifier.' % arg.name,331- lineno)360+ lineno, self.filename)361 # remove the last "_" before writing362 if first_var is None:363 first_var = arg.name[:-1]364 replacements[arg.name[:-1]] = arg.expr13 unmodified lines378 if variable_token != 'name':379 raise TemplateSyntaxError('can only use variable not '380 'constants or expressions '381 'in translation variable '353- 'blocks.', lineno)382+ 'blocks.', lineno,383+ self.filename)384 # plural name without trailing "_"? that's a keyword385 if not variable_name.endswith('_'):386 raise TemplateSyntaxError('illegal use of keyword '387 '%r as identifier in trans '358- 'block.' % variable_name, lineno)388+ 'block.' % variable_name,389+ lineno, self.filename)390 variable_name = variable_name[:-1]391 if variable_name not in replacements:392 raise TemplateSyntaxError('unregistered translation '362- 'variable %r.' % variable_name,363- lineno)393+ 'variable %r.' %394+ variable_name, lineno,395+ self.filename)396 if self.tokenstream.next()[1] != 'variable_end':365- raise TemplateSyntaxError('you cannot use variable expressions '366- 'inside trans tags. apply filters '367- 'in the trans header.', lineno)397+ raise TemplateSyntaxError('you cannot use variable '398+ 'expressions inside trans '399+ 'tags. apply filters '400+ 'in the trans header.',401+ lineno, self.filename)402 buf.append('%%(%s)s' % variable_name)403 # nested blocks are not supported, just look for end blocks404 elif token == 'block_begin':405 _, block_token, block_name = self.tokenstream.next()406 if block_token != 'name' or \407 block_name not in ('pluralize', 'endtrans'):374- raise TemplateSyntaxError('blocks in translatable sections '375- 'are not supported', lineno)408+ raise TemplateSyntaxError('blocks in translatable '409+ 'sections are not '410+ 'supported', lineno,411+ self.filename)412 # pluralize413 if block_name == 'pluralize':414 if plural is not None:379- raise TemplateSyntaxError('translation blocks support '380- 'at most one plural block',381- lineno)415+ raise TemplateSyntaxError('translation blocks '416+ 'support at most one '417+ 'plural block',418+ lineno, self.filename)419 _, plural_token, plural_name = self.tokenstream.next()420 if plural_token == 'block_end':421 indicator = first_var422 elif plural_token == 'name':386- # plural name without trailing "_"? that's a keyword423+ # disallow keywords424 if not plural_name.endswith('_'):388- raise TemplateSyntaxError('illegal use of keyword '389- '%r as identifier.' %390- plural_name, lineno)425+ raise TemplateSyntaxError('illegal use of '426+ 'keyword %r as '427+ 'identifier.' %428+ plural_name,429+ lineno,430+ self.filename)431 plural_name = plural_name[:-1]432 if plural_name not in replacements:393- raise TemplateSyntaxError('unknown tranlsation '433+ raise TemplateSyntaxError('unregistered '434+ 'translation '435 'variable %r' %395- plural_name, lineno)436+ plural_name, lineno,437+ self.filename)438 elif self.tokenstream.next()[1] != 'block_end':439 raise TemplateSyntaxError('pluralize takes '440 'at most one '399- 'argument', lineno)441+ 'argument', lineno,442+ self.filename)443 indicator = plural_name444 else:445 raise TemplateSyntaxError('pluralize requires no '403- 'argument or a variable '404- 'name.')446+ 'argument or a variable'447+ ' name.', lineno,448+ self.filename)449 plural = buf = []450 # end translation451 elif block_name == 'endtrans':452 self.close_remaining_block()3 unmodified lines456 buf.append(data.replace('%', '%%'))457 458 except StopIteration:459 raise TemplateSyntaxError('unexpected end of translation section',416- self.tokenstream.last[0])460+ self.tokenstream.last[0], self.filename)461 462 singular = u''.join(singular)463 if plural is not None:464 plural = u''.join(plural)421- return nodes.Trans(flineno, singular, plural, indicator, replacements or None)465+ return nodes.Trans(flineno, singular, plural, indicator,466+ replacements or None)467 468 469 def parse_python(self, lineno, gen, template):470 """6 unmodified lines477 if t_token == 'string':478 tokens.append('u' + t_data)479 else:480 tokens.append(t_data)436- source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).encode('utf-8'))481+ source = '\xef\xbb\xbf' + (template % (u' '.join(tokens)).482+ encode('utf-8'))483 try:484 ast = parse(source, 'exec')485 except SyntaxError, e:440- raise TemplateSyntaxError('invalid syntax', lineno + e.lineno)441- assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' % len(ast.node.nodes)486+ raise TemplateSyntaxError('invalid syntax', lineno + e.lineno,487+ self.filename)488+ assert len(ast.node.nodes) == 1, 'get %d nodes, 1 expected' %\489+ len(ast.node.nodes)490 result = ast.node.nodes[0]491 nodes.inc_lineno(lineno, result)492 return result493 13 unmodified lines507 if node.__class__ in (ast.AssName, ast.Name):508 if not node.name.endswith('_'):509 raise TemplateSyntaxError('illegal use of keyword %r '510 'as identifier.' % node.name,463- node.lineno)511+ node.lineno, self.filename)512 node.name = node.name[:-1]513 elif node.__class__ is ast.Getattr:514 if not node.attrname.endswith('_'):515 raise TemplateSyntaxError('illegal use of keyword %r '468- 'as attribute name.' % node.name)516+ 'as attribute name.' %517+ node.name, node.lineno,518+ self.filename)519 node.attrname = node.attrname[:-1]520 node.filename = self.filename521 todo.extend(node.getChildNodes())522 return nodes.Template(self.filename, body, self.extends)8 unmodified lines531 The test function is only called for the first token after a532 block tag. Variable tags are *not* aliases for {% print %} in533 that case.534 485- If drop_needle is True the needle_token is removed from the tokenstream.535+ If drop_needle is True the needle_token is removed from the536+ tokenstream.537 """538 def finish():539 """Helper function to remove unused nodelists."""540 if len(result) == 1:19 unmodified lines560 gen = self.tokenstream.fetch_until(end_of_block, True)561 try:562 lineno, token, data = gen.next()563 except StopIteration:513- raise TemplateSyntaxError('unexpected end of block', lineno)564+ raise TemplateSyntaxError('unexpected end of block',565+ lineno, self.filename)566 567 # first token *must* be a name token568 if token != 'name':569 raise TemplateSyntaxError('unexpected %r token (%r)' % (518- token, data), lineno)570+ token, data), lineno,571+ self.filename)572 573 # if a test function is passed to subparse we check if we574 # reached the end of such a requested block.575 if test is not None and test(lineno, token, data):6 unmodified lines582 # template syntax error.583 if data in self.directives:584 node = self.directives[data](lineno, gen)585 else:533- raise TemplateSyntaxError('unknown directive %r' % data, lineno)586+ raise TemplateSyntaxError('unknown directive %r' % data,587+ lineno, self.filename)588 # some tags like the extends tag do not output nodes.589 # so just skip that.590 if node is not None:591 result.append(node)5 unmodified lines597 result.append(nodes.Text(lineno, data))598 599 # so this should be unreachable code600 else:547- raise AssertionError('unexpected token %r (%r)' % (token, data))601+ raise AssertionError('unexpected token %r (%r)' % (token,602+ data))603 604 # still here and a test function is provided? raise and error605 if test is not None:551- raise TemplateSyntaxError('unexpected end of template', lineno)606+ raise TemplateSyntaxError('unexpected end of template', lineno,607+ self.filename)608 return finish()609 610 def close_remaining_block(self):611 """5 unmodified lines617 lineno = self.tokenstream.last[0]618 try:619 lineno, token, data = self.tokenstream.next()620 except StopIteration:565- raise TemplateSyntaxError('missing closing tag', lineno)621+ raise TemplateSyntaxError('missing closing tag', lineno,622+ self.filename)623 if token != 'block_end':567- raise TemplateSyntaxError('expected close tag, found %r' % token, lineno)624+ raise TemplateSyntaxError('expected close tag, found %r' % token,625+ lineno, self.filename)modified:jinja/utils.py+24 added-9 removed
15 unmodified lines16 import string17 from types import MethodType, FunctionType18 from compiler.ast import CallFunc, Name, Const19 from jinja.nodes import Trans20-from jinja.datastructure import Markup20+from jinja.datastructure import Markup, Context21 22 try:23 from collections import deque24 except ImportError:135 unmodified lines160 return capture_generator(f(*args, **kwargs))161 return wrapped162 163 164-def raise_template_exception(exception, filename, lineno, context):164+def fake_template_exception(exception, filename, lineno, context_or_env):165 """166 Raise an exception "in a template". Return a traceback167 object. This is used for runtime debugging, not compile time.168 """169 # some traceback systems allow to skip frames170 __traceback_hide__ = True171+ if isinstance(context_or_env, Context):172+ env = context_or_env.environment173+ namespace = context_or_env.to_dict()174+ else:175+ env = context_or_env176+ namespace = {}177 178 offset = '\n' * (lineno - 1)179 code = compile(offset + 'raise __exception_to_raise__', filename, 'exec')174- namespace = context.to_dict()180 globals = {181 '__name__': filename,182 '__file__': filename,178- '__loader__': TracebackLoader(context.environment,179- filename),183+ '__loader__': TracebackLoader(env, filename),184 '__exception_to_raise__': exception185 }186 try:187 exec code in globals, namespace188 except:185- traceback = sys.exc_info()[2]186- return traceback189+ return sys.exc_info()190 191 192 def translate_exception(template, exc_type, exc_value, traceback, context):193 """21 unmodified lines215 # no traceback information found, reraise unchanged216 if not filename:217 return traceback218 216- return raise_template_exception(exc_value, filename,217- lineno, context)219+ return fake_template_exception(exc_value, filename,220+ lineno, context)[2]221 222 223+def raise_syntax_error(exception, env):224+ """225+ This method raises an exception that includes more debugging226+ informations so that debugging works better. Unlike227+ `translate_exception` this method raises the exception with228+ the traceback.229+ """230+ exc_info = fake_template_exception(exception, exception.filename,231+ exception.lineno, env)232+ raise exc_info[0], exc_info[1], exc_info[2]233+234+235 def collect_translations(ast):236 """237 Collect all translatable strings for the given ast.238 """166 unmodified linesdeleted:tests/runtime/templates/error.html-6 removed
123456<ul><meta http-equiv="Content-Type" content="" />{% for item in items %} {% include "included_error.html" %}{% endfor %}</ul>modified:tests/runtime/exception.py+66 added-5 removed
1-from jinja import Environment, FileSystemLoader1+from jinja import Environment, DictLoader2+from jinja.exceptions import TemplateNotFound3 from colubrid.debug import DebuggedApplication4 from wsgiref.simple_server import make_server4-e = Environment(loader=FileSystemLoader('templates'))5 6-def test(*args):7- tmpl = e.loader.load('error.html')8- tmpl.render(items=range(10))6+e = Environment(loader=DictLoader({7+ '/': u'''8+<html>9+ <head>10+ <title>Various Broken Templates</title>11+ <style type="text/css">12+ body {13+ margin: 2em;14+ font-size: 1.5em;15+ font-family: sans-serif16+ }17+ a {18+ color: #d00;19+ }20+ </style>21+ </head>22+ <body>23+ <h1>Various Broken Templates</h1>24+ <p>25+ This small WSGI application serves some Jinja templates that26+ are just broken. It uses the colubrid traceback middleware to27+ render those errors including source code.28+ </p>29+ <ul>30+ <li><a href="syntax_error">syntax error</a></li>31+ <li><a href="runtime_error">runtime error</a></li>32+ <li><a href="nested_syntax_error">nested syntax error</a></li>33+ <li><a href="nested_runtime_error">nested runtime error</a></li>34+ </ul>35+ </body>36+</html>37+''',38+ '/syntax_error': u'''39+{% for item in foo %}40+ ...41+{% endif %}42+ ''',43+ '/runtime_error': u'''44+{% set foo = 1 / 0 %}45+ ''',46+ '/nested_runtime_error': u'''47+{% include 'runtime_broken' %}48+ ''',49+ '/nested_syntax_error': u'''50+{% include 'syntax_broken' %}51+ ''',52 53+ 'runtime_broken': '''\54+This is an included template55+{% set a = 1 / 0 %}''',56+ 'syntax_broken': '''\57+This is an included template58+{% raw %}just some foo'''59+}))60+61+62+def test(environ, start_response):63+ try:64+ tmpl = e.get_template(environ.get('PATH_INFO') or '/')65+ except TemplateNotFound:66+ start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])67+ return ['NOT FOUND']68+ start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])69+ return [tmpl.render().encode('utf-8')]70+71 make_server("localhost", 7000, DebuggedApplication(test)).serve_forever()