Skip to content
Myr

debug.py

This file

Path

jinja2/debug.py

308 lines · 9.7 KiB · Python

Last changed by

Merged in changes from 2.3.1Armin Ronacherbefore adoption9164d04

History of this file

Take it

The walk stopped after 200 commits: lines older than 4d5bdff point at it.

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 1–9why, one step back
1# -*- coding: utf-8 -*-
2"""3 jinja2.debug4 ~~~~~~~~~~~~56 Implements the debug interface for Jinja. This module does some pretty7 ugly stuff with the Python traceback system in order to achieve tracebacks8 with correct line numbers, locals and contents.9

It's a new yearArmin Ronacherbefore adoption55494e4

line 10why, one step back
10 :copyright: (c) 2010 by the Jinja Team.

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

line 11why, one step back
11 :license: BSD, see LICENSE for more details.

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 12–13why, one step back
12"""
13import sys

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

line 14why, one step back
14import traceback

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

line 15why, one step back
15from jinja2.utils import CodeType, missing, internal_code

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

line 16why, one step back
16from jinja2.exceptions import TemplateSyntaxError

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 17–18why, one step back
17
18

More Python 3 support.Armin Ronacherbefore adoptionbd35772

lines 19–27why, one step back
19# how does the raise helper look like?
20try:21 exec "raise TypeError, 'foo'"22except SyntaxError:23 raise_helper = 'raise __jinja_exception__[1]'24except TypeError:25 raise_helper = 'raise __jinja_exception__[0], __jinja_exception__[1]'2627

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 28–76why, one step back
28class TracebackFrameProxy(object):
29 """Proxies a traceback frame."""3031 def __init__(self, tb):32 self.tb = tb3334 def _set_tb_next(self, next):35 if tb_set_next is not None:36 tb_set_next(self.tb, next and next.tb or None)37 self._tb_next = next3839 def _get_tb_next(self):40 return self._tb_next4142 tb_next = property(_get_tb_next, _set_tb_next)43 del _get_tb_next, _set_tb_next4445 @property46 def is_jinja_frame(self):47 return '__jinja_template__' in self.tb.tb_frame.f_globals4849 def __getattr__(self, name):50 return getattr(self.tb, name)515253class ProcessedTraceback(object):54 """Holds a Jinja preprocessed traceback for priting or reraising."""5556 def __init__(self, exc_type, exc_value, frames):57 assert frames, 'no frames for this traceback?'58 self.exc_type = exc_type59 self.exc_value = exc_value60 self.frames = frames6162 def chain_frames(self):63 """Chains the frames. Requires ctypes or the speedups extension."""64 prev_tb = None65 for tb in self.frames:66 if prev_tb is not None:67 prev_tb.tb_next = tb68 prev_tb = tb69 prev_tb.tb_next = None7071 def render_as_text(self, limit=None):72 """Return a string with the traceback."""73 lines = traceback.format_exception(self.exc_type, self.exc_value,74 self.frames[0], limit=limit)75 return ''.join(lines).rstrip()76

Resolved conflictArmin Ronacherbefore adoptionf2b59c4

lines 77–84why, one step back
77 def render_as_html(self, full=False):
78 """Return a unicode string with the traceback as rendered HTML."""79 from jinja2.debugrenderer import render_traceback80 return u'%s\n\n<!--\n%s\n-->' % (81 render_traceback(self, full=full),82 self.render_as_text().decode('utf-8', 'replace')83 )84

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 85–105why, one step back
85 @property
86 def is_template_syntax_error(self):87 """`True` if this is a template syntax error."""88 return isinstance(self.exc_value, TemplateSyntaxError)8990 @property91 def exc_info(self):92 """Exception info tuple with a proxy around the frame objects."""93 return self.exc_type, self.exc_value, self.frames[0]9495 @property96 def standard_exc_info(self):97 """Standard python exc_info for re-raising"""98 return self.exc_type, self.exc_value, self.frames[0].tb99100101def make_traceback(exc_info, source_hint=None):102 """Creates a processed traceback object from the exc_info."""103 exc_type, exc_value, tb = exc_info104 if isinstance(exc_value, TemplateSyntaxError):105 exc_info = translate_syntax_error(exc_value, source_hint)

Fixed a bug with template syntax errors not handled properly.Armin Ronacherbefore adoption2a79192

lines 106–109why, one step back
106 initial_skip = 0
107 else:108 initial_skip = 1109 return translate_exception(exc_info, initial_skip)

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 110–111why, one step back
110
111

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 112–115why, one step back
112def translate_syntax_error(error, source=None):
113 """Rewrites a syntax error to please traceback systems."""114 error.source = source115 error.translated = True

Merged in changes from 2.3.1Armin Ronacherbefore adoption9164d04

line 116why, one step back
116 exc_info = (error.__class__, error, None)

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 117–122why, one step back
117 filename = error.filename
118 if filename is None:119 filename = '<unknown>'120 return fake_exc_info(exc_info, filename, error.lineno)121122

Fixed a bug with template syntax errors not handled properly.Armin Ronacherbefore adoption2a79192

line 123why, one step back
123def translate_exception(exc_info, initial_skip=0):

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 124–126why, one step back
124 """If passed an exc_info it will automatically rewrite the exceptions
125 all the way down to the correct line numbers and frames.126 """

Fixed a bug with template syntax errors not handled properly.Armin Ronacherbefore adoption2a79192

line 127why, one step back
127 tb = exc_info[2]

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

line 128why, one step back
128 frames = []

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

line 129why, one step back
129

Fixed a bug with template syntax errors not handled properly.Armin Ronacherbefore adoption2a79192

lines 130–135why, one step back
130 # skip some internal frames if wanted
131 for x in xrange(initial_skip):132 if tb is not None:133 tb = tb.tb_next134 initial_tb = tb135

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

line 136why, one step back
136 while tb is not None:

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 137–139why, one step back
137 # skip frames decorated with @internalcode. These are internal
138 # calls we can't avoid and that are useless in template debugging139 # output.

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

line 140why, one step back
140 if tb.tb_frame.f_code in internal_code:

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 141–143why, one step back
141 tb = tb.tb_next
142 continue143

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 144–148why, one step back
144 # save a reference to the next frame if we override the current
145 # one with a faked one.146 next = tb.tb_next147148 # fake template exceptions

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 149–152why, one step back
149 template = tb.tb_frame.f_globals.get('__jinja_template__')
150 if template is not None:151 lineno = template.get_corresponding_lineno(tb.tb_lineno)152 tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

line 153why, one step back
153 lineno)[2]

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

line 154why, one step back
154

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 155–156why, one step back
155 frames.append(TracebackFrameProxy(tb))
156 tb = next

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

line 157why, one step back
157

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 158–162why, one step back
158 # if we don't have any exceptions in the frames left, we have to
159 # reraise it unchanged.160 # XXX: can we backup here? when could this happen?161 if not frames:162 raise exc_info[0], exc_info[1], exc_info[2]

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

line 163why, one step back
163

Started refactoring of debugging system for better AppEngine/Pylons support.Armin Ronacherbefore adoptiona18872d

lines 164–170why, one step back
164 traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)
165 if tb_set_next is not None:166 traceback.chain_frames()167 return traceback168169170def fake_exc_info(exc_info, filename, lineno):

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 171–174why, one step back
171 """Helper for `translate_exception`."""
172 exc_type, exc_value, tb = exc_info173174 # figure the real context out

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 175–188why, one step back
175 if tb is not None:
176 real_locals = tb.tb_frame.f_locals.copy()177 ctx = real_locals.get('context')178 if ctx:179 locals = ctx.get_all()180 else:181 locals = {}182 for name, value in real_locals.iteritems():183 if name.startswith('l_') and value is not missing:184 locals[name[2:]] = value185186 # if there is a local called __jinja_exception__, we get187 # rid of it to not break the debug functionality.188 locals.pop('__jinja_exception__', None)

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 189–195why, one step back
189 else:
190 locals = {}191192 # assamble fake globals we need193 globals = {194 '__name__': filename,195 '__file__': filename,

Fixed a bug in jinja2/debug (second time, forgot to merge and threw away changes -.-)Armin Ronacherbefore adoption94ee6aa

lines 196–201why, one step back
196 '__jinja_exception__': exc_info[:2],
197198 # we don't want to keep the reference to the template around199 # to not cause circular dependencies, but we mark it as Jinja200 # frame for the ProcessedTraceback201 '__jinja_template__': None

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 202–204why, one step back
202 }
203204 # and fake the exception

More Python 3 support.Armin Ronacherbefore adoptionbd35772

line 205why, one step back
205 code = compile('\n' * (lineno - 1) + raise_helper, filename, 'exec')

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 206–209why, one step back
206
207 # if it's possible, change the name of the code. This won't work208 # on some python environments such as google appengine209 try:

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

line 210why, one step back
210 if tb is None:

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

line 211why, one step back
211 location = 'template'

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 212–219why, one step back
212 else:
213 function = tb.tb_frame.f_code.co_name214 if function == 'root':215 location = 'top-level template code'216 elif function.startswith('block_'):217 location = 'block "%s"' % function[6:]218 else:219 location = 'template'

Added experimental and undocumented bytecode cache supportArmin Ronacherbefore adoption4d5bdff

lines 220–308why, one step back
220 code = CodeType(0, code.co_nlocals, code.co_stacksize,
221 code.co_flags, code.co_code, code.co_consts,222 code.co_names, code.co_varnames, filename,223 location, code.co_firstlineno,224 code.co_lnotab, (), ())225 except:226 pass227228 # execute the code and catch the new traceback229 try:230 exec code in globals, locals231 except:232 exc_info = sys.exc_info()233 new_tb = exc_info[2].tb_next234235 # return without this frame236 return exc_info[:2] + (new_tb,)237238239def _init_ugly_crap():240 """This function implements a few ugly things so that we can patch the241 traceback objects. The function returned allows resetting `tb_next` on242 any python traceback object.243 """244 import ctypes245 from types import TracebackType246247 # figure out side of _Py_ssize_t248 if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):249 _Py_ssize_t = ctypes.c_int64250 else:251 _Py_ssize_t = ctypes.c_int252253 # regular python254 class _PyObject(ctypes.Structure):255 pass256 _PyObject._fields_ = [257 ('ob_refcnt', _Py_ssize_t),258 ('ob_type', ctypes.POINTER(_PyObject))259 ]260261 # python with trace262 if object.__basicsize__ != ctypes.sizeof(_PyObject):263 class _PyObject(ctypes.Structure):264 pass265 _PyObject._fields_ = [266 ('_ob_next', ctypes.POINTER(_PyObject)),267 ('_ob_prev', ctypes.POINTER(_PyObject)),268 ('ob_refcnt', _Py_ssize_t),269 ('ob_type', ctypes.POINTER(_PyObject))270 ]271272 class _Traceback(_PyObject):273 pass274 _Traceback._fields_ = [275 ('tb_next', ctypes.POINTER(_Traceback)),276 ('tb_frame', ctypes.POINTER(_PyObject)),277 ('tb_lasti', ctypes.c_int),278 ('tb_lineno', ctypes.c_int)279 ]280281 def tb_set_next(tb, next):282 """Set the tb_next attribute of a traceback object."""283 if not (isinstance(tb, TracebackType) and284 (next is None or isinstance(next, TracebackType))):285 raise TypeError('tb_set_next arguments must be traceback objects')286 obj = _Traceback.from_address(id(tb))287 if tb.tb_next is not None:288 old = _Traceback.from_address(id(tb.tb_next))289 old.ob_refcnt -= 1290 if next is None:291 obj.tb_next = ctypes.POINTER(_Traceback)()292 else:293 next = _Traceback.from_address(id(next))294 next.ob_refcnt += 1295 obj.tb_next = ctypes.pointer(next)296297 return tb_set_next298299300# try to get a tb_set_next implementation301try:302 from jinja2._speedups import tb_set_next303except ImportError:304 try:305 tb_set_next = _init_ugly_crap()306 except:307 tb_set_next = None308del _init_ugly_crap