blob: ce794e243b38e8ae558957c9e235eae2a7f48ade [file] [log] [blame]
Armin Ronacherba3757b2008-04-16 19:43:16 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.debug
4 ~~~~~~~~~~~~
5
Armin Ronacher187bde12008-05-01 18:19:16 +02006 Implements the debug interface for Jinja. This module does some pretty
7 ugly stuff with the Python traceback system in order to achieve tracebacks
8 with correct line numbers, locals and contents.
Armin Ronacherba3757b2008-04-16 19:43:16 +02009
Armin Ronacher62ccd1b2009-01-04 14:26:19 +010010 :copyright: (c) 2009 by the Jinja Team.
Armin Ronachere73e0972009-03-05 23:47:00 +010011 :license: BSD, see LICENSE for more details.
Armin Ronacherba3757b2008-04-16 19:43:16 +020012"""
Armin Ronacherba3757b2008-04-16 19:43:16 +020013import sys
Armin Ronachere73e0972009-03-05 23:47:00 +010014import traceback
Armin Ronacherd416a972009-02-24 22:58:00 +010015from jinja2.utils import CodeType, missing, internal_code
Armin Ronachere73e0972009-03-05 23:47:00 +010016from jinja2.exceptions import TemplateSyntaxError
17
18
19class TracebackFrameProxy(object):
20 """Proxies a traceback frame."""
21
22 def __init__(self, tb):
23 self.tb = tb
24
25 def _set_tb_next(self, next):
26 if tb_set_next is not None:
27 tb_set_next(self.tb, next and next.tb or None)
28 self._tb_next = next
29
30 def _get_tb_next(self):
31 return self._tb_next
32
33 tb_next = property(_get_tb_next, _set_tb_next)
34 del _get_tb_next, _set_tb_next
35
36 @property
37 def is_jinja_frame(self):
38 return '__jinja_template__' in self.tb.tb_frame.f_globals
39
40 def __getattr__(self, name):
41 return getattr(self.tb, name)
42
43
44class ProcessedTraceback(object):
45 """Holds a Jinja preprocessed traceback for priting or reraising."""
46
47 def __init__(self, exc_type, exc_value, frames):
48 assert frames, 'no frames for this traceback?'
49 self.exc_type = exc_type
50 self.exc_value = exc_value
51 self.frames = frames
52
53 def chain_frames(self):
54 """Chains the frames. Requires ctypes or the speedups extension."""
55 prev_tb = None
56 for tb in self.frames:
57 if prev_tb is not None:
58 prev_tb.tb_next = tb
59 prev_tb = tb
60 prev_tb.tb_next = None
61
62 def render_as_text(self, limit=None):
63 """Return a string with the traceback."""
64 lines = traceback.format_exception(self.exc_type, self.exc_value,
65 self.frames[0], limit=limit)
66 return ''.join(lines).rstrip()
67
68 @property
69 def is_template_syntax_error(self):
70 """`True` if this is a template syntax error."""
71 return isinstance(self.exc_value, TemplateSyntaxError)
72
73 @property
74 def exc_info(self):
75 """Exception info tuple with a proxy around the frame objects."""
76 return self.exc_type, self.exc_value, self.frames[0]
77
78 @property
79 def standard_exc_info(self):
80 """Standard python exc_info for re-raising"""
81 return self.exc_type, self.exc_value, self.frames[0].tb
82
83
84def make_traceback(exc_info, source_hint=None):
85 """Creates a processed traceback object from the exc_info."""
86 exc_type, exc_value, tb = exc_info
87 if isinstance(exc_value, TemplateSyntaxError):
88 exc_info = translate_syntax_error(exc_value, source_hint)
89 return translate_exception(exc_info)
Armin Ronacherd416a972009-02-24 22:58:00 +010090
91
92def translate_syntax_error(error, source=None):
93 """Rewrites a syntax error to please traceback systems."""
94 error.source = source
95 error.translated = True
96 exc_info = (type(error), error, None)
97 filename = error.filename
98 if filename is None:
99 filename = '<unknown>'
100 return fake_exc_info(exc_info, filename, error.lineno)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200101
102
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200103def translate_exception(exc_info):
104 """If passed an exc_info it will automatically rewrite the exceptions
105 all the way down to the correct line numbers and frames.
106 """
Armin Ronacher6cc8dd02008-04-16 23:15:15 +0200107 initial_tb = tb = exc_info[2].tb_next
Armin Ronachere73e0972009-03-05 23:47:00 +0100108 frames = []
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200109
110 while tb is not None:
Armin Ronacherd416a972009-02-24 22:58:00 +0100111 # skip frames decorated with @internalcode. These are internal
112 # calls we can't avoid and that are useless in template debugging
113 # output.
Armin Ronachere73e0972009-03-05 23:47:00 +0100114 if tb.tb_frame.f_code in internal_code:
Armin Ronacherd416a972009-02-24 22:58:00 +0100115 tb = tb.tb_next
116 continue
117
Armin Ronachere73e0972009-03-05 23:47:00 +0100118 # save a reference to the next frame if we override the current
119 # one with a faked one.
120 next = tb.tb_next
121
122 # fake template exceptions
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200123 template = tb.tb_frame.f_globals.get('__jinja_template__')
124 if template is not None:
125 lineno = template.get_corresponding_lineno(tb.tb_lineno)
126 tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,
Armin Ronachere73e0972009-03-05 23:47:00 +0100127 lineno)[2]
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200128
Armin Ronachere73e0972009-03-05 23:47:00 +0100129 frames.append(TracebackFrameProxy(tb))
130 tb = next
131
132 # if we don't have any exceptions in the frames left, we have to
133 # reraise it unchanged.
134 # XXX: can we backup here? when could this happen?
135 if not frames:
136 raise exc_info[0], exc_info[1], exc_info[2]
137
138 traceback = ProcessedTraceback(exc_info[0], exc_info[1], frames)
139 if tb_set_next is not None:
140 traceback.chain_frames()
141 return traceback
Armin Ronacherba3757b2008-04-16 19:43:16 +0200142
143
Armin Ronachere73e0972009-03-05 23:47:00 +0100144def fake_exc_info(exc_info, filename, lineno):
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200145 """Helper for `translate_exception`."""
Armin Ronacherba3757b2008-04-16 19:43:16 +0200146 exc_type, exc_value, tb = exc_info
147
148 # figure the real context out
Armin Ronacherd416a972009-02-24 22:58:00 +0100149 if tb is not None:
150 real_locals = tb.tb_frame.f_locals.copy()
151 ctx = real_locals.get('context')
152 if ctx:
153 locals = ctx.get_all()
154 else:
155 locals = {}
156 for name, value in real_locals.iteritems():
157 if name.startswith('l_') and value is not missing:
158 locals[name[2:]] = value
159
160 # if there is a local called __jinja_exception__, we get
161 # rid of it to not break the debug functionality.
162 locals.pop('__jinja_exception__', None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200163 else:
164 locals = {}
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200165
Armin Ronacherba3757b2008-04-16 19:43:16 +0200166 # assamble fake globals we need
167 globals = {
168 '__name__': filename,
169 '__file__': filename,
170 '__jinja_exception__': exc_info[:2]
171 }
172
173 # and fake the exception
174 code = compile('\n' * (lineno - 1) + 'raise __jinja_exception__[0], ' +
175 '__jinja_exception__[1]', filename, 'exec')
Armin Ronacher32a910f2008-04-26 23:21:03 +0200176
177 # if it's possible, change the name of the code. This won't work
178 # on some python environments such as google appengine
179 try:
Armin Ronacherd416a972009-02-24 22:58:00 +0100180 if tb is None:
Armin Ronacher32a910f2008-04-26 23:21:03 +0200181 location = 'template'
Armin Ronacherd416a972009-02-24 22:58:00 +0100182 else:
183 function = tb.tb_frame.f_code.co_name
184 if function == 'root':
185 location = 'top-level template code'
186 elif function.startswith('block_'):
187 location = 'block "%s"' % function[6:]
188 else:
189 location = 'template'
Armin Ronacher32a910f2008-04-26 23:21:03 +0200190 code = CodeType(0, code.co_nlocals, code.co_stacksize,
191 code.co_flags, code.co_code, code.co_consts,
192 code.co_names, code.co_varnames, filename,
193 location, code.co_firstlineno,
194 code.co_lnotab, (), ())
195 except:
196 pass
197
198 # execute the code and catch the new traceback
Armin Ronacherba3757b2008-04-16 19:43:16 +0200199 try:
200 exec code in globals, locals
201 except:
202 exc_info = sys.exc_info()
Armin Ronacher32a910f2008-04-26 23:21:03 +0200203 new_tb = exc_info[2].tb_next
Armin Ronacherba3757b2008-04-16 19:43:16 +0200204
Armin Ronacher6cc8dd02008-04-16 23:15:15 +0200205 # return without this frame
Armin Ronacher32a910f2008-04-26 23:21:03 +0200206 return exc_info[:2] + (new_tb,)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200207
208
Armin Ronacherba3757b2008-04-16 19:43:16 +0200209def _init_ugly_crap():
210 """This function implements a few ugly things so that we can patch the
211 traceback objects. The function returned allows resetting `tb_next` on
212 any python traceback object.
213 """
214 import ctypes
215 from types import TracebackType
216
217 # figure out side of _Py_ssize_t
218 if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):
219 _Py_ssize_t = ctypes.c_int64
220 else:
221 _Py_ssize_t = ctypes.c_int
222
223 # regular python
224 class _PyObject(ctypes.Structure):
225 pass
226 _PyObject._fields_ = [
227 ('ob_refcnt', _Py_ssize_t),
228 ('ob_type', ctypes.POINTER(_PyObject))
229 ]
230
231 # python with trace
232 if object.__basicsize__ != ctypes.sizeof(_PyObject):
233 class _PyObject(ctypes.Structure):
234 pass
235 _PyObject._fields_ = [
236 ('_ob_next', ctypes.POINTER(_PyObject)),
237 ('_ob_prev', ctypes.POINTER(_PyObject)),
238 ('ob_refcnt', _Py_ssize_t),
239 ('ob_type', ctypes.POINTER(_PyObject))
240 ]
241
242 class _Traceback(_PyObject):
243 pass
244 _Traceback._fields_ = [
245 ('tb_next', ctypes.POINTER(_Traceback)),
246 ('tb_frame', ctypes.POINTER(_PyObject)),
247 ('tb_lasti', ctypes.c_int),
248 ('tb_lineno', ctypes.c_int)
249 ]
250
251 def tb_set_next(tb, next):
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200252 """Set the tb_next attribute of a traceback object."""
Armin Ronacherba3757b2008-04-16 19:43:16 +0200253 if not (isinstance(tb, TracebackType) and
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200254 (next is None or isinstance(next, TracebackType))):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200255 raise TypeError('tb_set_next arguments must be traceback objects')
256 obj = _Traceback.from_address(id(tb))
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200257 if tb.tb_next is not None:
258 old = _Traceback.from_address(id(tb.tb_next))
259 old.ob_refcnt -= 1
260 if next is None:
261 obj.tb_next = ctypes.POINTER(_Traceback)()
262 else:
263 next = _Traceback.from_address(id(next))
264 next.ob_refcnt += 1
265 obj.tb_next = ctypes.pointer(next)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200266
267 return tb_set_next
268
269
Armin Ronacherbd33f112008-04-18 09:17:32 +0200270# try to get a tb_set_next implementation
Armin Ronacherba3757b2008-04-16 19:43:16 +0200271try:
Armin Ronacherbd33f112008-04-18 09:17:32 +0200272 from jinja2._speedups import tb_set_next
273except ImportError:
274 try:
275 tb_set_next = _init_ugly_crap()
276 except:
277 tb_set_next = None
Armin Ronacherba3757b2008-04-16 19:43:16 +0200278del _init_ugly_crap