added new python only debug hack
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 577ad38 · Browse files · 9 files·+189 added−663 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+189 added−663 removed
- other:+189 added−663 removed
Provenance
- Commit
ba3757b- Tree
a9afe57- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
577ad38
9 files changed+189 added−663 removed
added:examples/cycle.py+13 added
1+from jinja2 import Environment2+3+4+env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}")5+6+7+print env.from_string("""\8+<ul>9+# for item in range(10)10+ <li class="${loop.cycle('odd', 'even')}">${item}</li>11+# endfor12+</ul>\13+""").render()modified:examples/translate.py+1 added
1 from jinja2 import Environment2 3 print Environment().from_string("""\4+{{ foo.bar }}5 {% trans %}Hello {{ user }}!{% endtrans %}6 {% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %}7 """).render(user="someone")deleted:jinja2/_debugger.c-65 removed
1-/**2- * Jinja Extended Debugger3- * ~~~~~~~~~~~~~~~~~~~~~~~4- *5- * this module allows the jinja debugger to set the tb_next flag6- * on traceback objects. This is required to inject a traceback into7- * another one.8- *9- * For better windows support (not everybody has a visual studio 200310- * at home) it would be a good thing to have a ctypes implementation, but11- * because the struct is not exported there is currently no sane way.12- *13- * :copyright: 2007 by Armin Ronacher.14- * :license: BSD, see LICENSE for more details.15- */16-17-#include <Python.h>18-19-20-/**21- * set the tb_next attribute of a traceback object22- */23-static PyObject *24-tb_set_next(PyObject *self, PyObject *args)25-{26- PyTracebackObject *tb, *old;27- PyObject *next;28-29- if (!PyArg_ParseTuple(args, "O!O:tb_set_next", &PyTraceBack_Type, &tb, &next))30- return NULL;31- if (next == Py_None)32- next = NULL;33- else if (!PyTraceBack_Check(next)) {34- PyErr_SetString(PyExc_TypeError,35- "tb_set_next arg 2 must be traceback or None");36- return NULL;37- }38- else39- Py_INCREF(next);40-41- old = tb->tb_next;42- tb->tb_next = (PyTracebackObject*)next;43- Py_XDECREF(old);44-45- Py_INCREF(Py_None);46- return Py_None;47-}48-49-50-static PyMethodDef module_methods[] = {51- {"tb_set_next", (PyCFunction)tb_set_next, METH_VARARGS,52- "Set the tb_next member of a traceback object."},53- {NULL, NULL, 0, NULL} /* Sentinel */54-};55-56-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */57-#define PyMODINIT_FUNC void58-#endif59-PyMODINIT_FUNC60-init_debugger(void)61-{62- PyObject *module = Py_InitModule3("jinja._debugger", module_methods, "");63- if (!module)64- return;65-}deleted:jinja2/_native.py-85 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja._native4- ~~~~~~~~~~~~~5-6- This module implements the native base classes in case of not7- having a jinja with the _speedups module compiled.8-9- Note that if you change semantics here you have to edit the10- _speedups.c file to in order to support those changes for jinja11- setups with enabled speedup module.12-13- :copyright: 2007 by Armin Ronacher.14- :license: BSD, see LICENSE for more details.15-"""16-from jinja.datastructure import Deferred17-from jinja.utils import deque18-19-20-class BaseContext(object):21-22- def __init__(self, undefined_singleton, globals, initial):23- self._undefined_singleton = undefined_singleton24- self.current = current = {}25- self._stack = deque([current, initial, globals])26- self.globals = globals27- self.initial = initial28-29- self._push = self._stack.appendleft30- self._pop = self._stack.popleft31-32- def stack(self):33- return list(self._stack)[::-1]34- stack = property(stack)35-36- def pop(self):37- """Pop the last layer from the stack and return it."""38- rv = self._pop()39- self.current = self._stack[0]40- return rv41-42- def push(self, data=None):43- """44- Push one layer to the stack and return it. Layer must be45- a dict or omitted.46- """47- data = data or {}48- self._push(data)49- self.current = self._stack[0]50- return data51-52- def __getitem__(self, name):53- """54- Resolve one item. Restrict the access to internal variables55- such as ``'::cycle1'``. Resolve deferreds.56- """57- if not name.startswith('::'):58- for d in self._stack:59- if name in d:60- rv = d[name]61- if rv.__class__ is Deferred:62- rv = rv(self, name)63- # never touch the globals!64- if d is self.globals:65- self.initial[name] = rv66- else:67- d[name] = rv68- return rv69- return self._undefined_singleton70-71- def __setitem__(self, name, value):72- """Set a variable in the outermost layer."""73- self.current[name] = value74-75- def __delitem__(self, name):76- """Delete a variable in the outermost layer."""77- if name in self.current:78- del self.current[name]79-80- def __contains__(self, name):81- """ Check if the context contains a given variable."""82- for layer in self._stack:83- if name in layer:84- return True85- return Falsedeleted:jinja2/_speedups.c-499 removed
1-/**2- * jinja._speedups3- * ~~~~~~~~~~~~~~~4- *5- * This module implements the BaseContext, a c implementation of the6- * Context baseclass. If this extension is not compiled the datastructure7- * module implements a class in python.8- *9- * Note that if you change semantics here you have to edit the _native.py10- * to in order to support those changes for jinja setups without the11- * speedup module too.12- *13- * :copyright: 2007 by Armin Ronacher.14- * :license: BSD, see LICENSE for more details.15- */16-17-#include <Python.h>18-#include <structmember.h>19-20-/* Set by init_constants to real values */21-static PyObject *Deferred;22-23-/**24- * Internal struct used by BaseContext to store the25- * stacked namespaces.26- */27-struct StackLayer {28- PyObject *dict; /* current value, a dict */29- struct StackLayer *prev; /* lower struct layer or NULL */30-};31-32-/**33- * BaseContext python class.34- */35-typedef struct {36- PyObject_HEAD37- struct StackLayer *globals; /* the dict for the globals */38- struct StackLayer *initial; /* initial values */39- struct StackLayer *current; /* current values */40- long stacksize; /* current size of the stack */41- PyObject *undefined_singleton; /* the singleton returned on missing values */42-} BaseContext;43-44-/**45- * Called by init_speedups in order to retrieve references46- * to some exceptions and classes defined in jinja python modules47- */48-static int49-init_constants(void)50-{51- PyObject *datastructure = PyImport_ImportModule("jinja.datastructure");52- if (!datastructure)53- return 0;54- Deferred = PyObject_GetAttrString(datastructure, "Deferred");55- Py_DECREF(datastructure);56- return 1;57-}58-59-/**60- * GC Helper61- */62-static int63-BaseContext_clear(BaseContext *self)64-{65- struct StackLayer *current = self->current, *tmp;66- while (current) {67- tmp = current;68- Py_XDECREF(current->dict);69- current->dict = NULL;70- current = tmp->prev;71- PyMem_Free(tmp);72- }73- self->current = NULL;74- return 0;75-}76-77-/**78- * Deallocator for BaseContext.79- *80- * Frees the memory for the stack layers before freeing the object.81- */82-static void83-BaseContext_dealloc(BaseContext *self)84-{85- BaseContext_clear(self);86- self->ob_type->tp_free((PyObject*)self);87-}88-89-/**90- * GC Helper91- */92-static int93-BaseContext_traverse(BaseContext *self, visitproc visit, void *args)94-{95- int vret;96- struct StackLayer *layer = self->current;97-98- while (layer) {99- vret = visit(layer->dict, args);100- if (vret != 0)101- return vret;102- layer = layer->prev;103- }104-105- return 0;106-}107-108-/**109- * Initializes the BaseContext.110- *111- * Like the native python class it takes a reference to the undefined112- * singleton which will be used for undefined values.113- * The other two arguments are the global namespace and the initial114- * namespace which usually contains the values passed to the render115- * function of the template. Both must be dicts.116- */117-static int118-BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)119-{120- PyObject *undefined = NULL, *globals = NULL, *initial = NULL;121-122- if (!PyArg_ParseTuple(args, "OOO", &undefined, &globals, &initial))123- return -1;124- if (!PyDict_Check(globals) || !PyDict_Check(initial)) {125- PyErr_SetString(PyExc_TypeError, "stack layers must be dicts.");126- return -1;127- }128-129- self->current = PyMem_Malloc(sizeof(struct StackLayer));130- self->current->prev = NULL;131- self->current->dict = PyDict_New();132- if (!self->current->dict)133- return -1;134-135- self->initial = PyMem_Malloc(sizeof(struct StackLayer));136- self->initial->prev = NULL;137- self->initial->dict = initial;138- Py_INCREF(initial);139- self->current->prev = self->initial;140-141- self->globals = PyMem_Malloc(sizeof(struct StackLayer));142- self->globals->prev = NULL;143- self->globals->dict = globals;144- Py_INCREF(globals);145- self->initial->prev = self->globals;146-147- self->undefined_singleton = undefined;148- Py_INCREF(undefined);149-150- self->stacksize = 3;151- return 0;152-}153-154-/**155- * Pop the highest layer from the stack and return it156- */157-static PyObject*158-BaseContext_pop(BaseContext *self)159-{160- PyObject *result;161- struct StackLayer *tmp = self->current;162-163- if (self->stacksize <= 3) {164- PyErr_SetString(PyExc_IndexError, "stack too small.");165- return NULL;166- }167- result = self->current->dict;168- assert(result);169- self->current = tmp->prev;170- PyMem_Free(tmp);171- self->stacksize--;172- /* Took the reference to result from the struct. */173- return result;174-}175-176-/**177- * Push a new layer to the stack and return it. If no parameter178- * is provided an empty dict is created. Otherwise the dict passed179- * to it is used as new layer.180- */181-static PyObject*182-BaseContext_push(BaseContext *self, PyObject *args)183-{184- PyObject *value = NULL;185- struct StackLayer *new;186-187- if (!PyArg_ParseTuple(args, "|O:push", &value))188- return NULL;189- if (!value) {190- value = PyDict_New();191- if (!value)192- return NULL;193- }194- else if (!PyDict_Check(value)) {195- PyErr_SetString(PyExc_TypeError, "dict required.");196- return NULL;197- }198- else199- Py_INCREF(value);200- new = PyMem_Malloc(sizeof(struct StackLayer));201- if (!new) {202- Py_DECREF(value);203- return NULL;204- }205- new->dict = value;206- new->prev = self->current;207- self->current = new;208- self->stacksize++;209- Py_INCREF(value);210- return value;211-}212-213-/**214- * Getter that creates a list representation of the internal215- * stack. Used for compatibility with the native python implementation.216- */217-static PyObject*218-BaseContext_getstack(BaseContext *self, void *closure)219-{220- int idx = 0;221- struct StackLayer *current = self->current;222- PyObject *result = PyList_New(self->stacksize);223- if (!result)224- return NULL;225- while (current) {226- Py_INCREF(current->dict);227- PyList_SET_ITEM(result, idx++, current->dict);228- current = current->prev;229- }230- PyList_Reverse(result);231- return result;232-}233-234-/**235- * Getter that returns a reference to the current layer in the context.236- */237-static PyObject*238-BaseContext_getcurrent(BaseContext *self, void *closure)239-{240- Py_INCREF(self->current->dict);241- return self->current->dict;242-}243-244-/**245- * Getter that returns a reference to the initial layer in the context.246- */247-static PyObject*248-BaseContext_getinitial(BaseContext *self, void *closure)249-{250- Py_INCREF(self->initial->dict);251- return self->initial->dict;252-}253-254-/**255- * Getter that returns a reference to the global layer in the context.256- */257-static PyObject*258-BaseContext_getglobals(BaseContext *self, void *closure)259-{260- Py_INCREF(self->globals->dict);261- return self->globals->dict;262-}263-264-/**265- * Implements the context lookup.266- *267- * This works exactly like the native implementation but a lot268- * faster. It disallows access to internal names (names that start269- * with "::") and resolves Deferred values.270- */271-static PyObject*272-BaseContext_getitem(BaseContext *self, PyObject *item)273-{274- PyObject *result;275- char *name = NULL;276- int isdeferred;277- struct StackLayer *current = self->current;278- 279- /* allow unicode keys as long as they are ascii keys */280- if (PyUnicode_CheckExact(item)) {281- item = PyUnicode_AsASCIIString(item);282- if (!item)283- goto missing;284- }285- else if (!PyString_Check(item))286- goto missing;287-288- /* disallow access to internal jinja values */289- name = PyString_AS_STRING(item);290- if (name[0] == ':' && name[1] == ':')291- goto missing;292-293- while (current) {294- /* GetItemString just builds a new string from "name" again... */295- result = PyDict_GetItem(current->dict, item);296- if (!result) {297- current = current->prev;298- continue;299- }300- isdeferred = PyObject_IsInstance(result, Deferred);301- if (isdeferred == -1)302- return NULL;303- else if (isdeferred) {304- PyObject *namespace;305- PyObject *resolved = PyObject_CallFunctionObjArgs(306- result, self, item, NULL);307- if (!resolved)308- return NULL;309-310- /* never touch the globals */311- if (current == self->globals)312- namespace = self->initial->dict;313- else314- namespace = current->dict;315- if (PyDict_SetItem(namespace, item, resolved) < 0)316- return NULL;317- Py_INCREF(resolved);318- return resolved;319- }320- Py_INCREF(result);321- return result;322- }323-324-missing:325- Py_INCREF(self->undefined_singleton);326- return self->undefined_singleton;327-}328-329-/**330- * Check if the context contains a given value.331- */332-static int333-BaseContext_contains(BaseContext *self, PyObject *item)334-{335- char *name;336- struct StackLayer *current = self->current;337-338- /* allow unicode objects as keys as long as they are ASCII */339- if (PyUnicode_CheckExact(item)) {340- item = PyUnicode_AsASCIIString(item);341- if (!item)342- return 0;343- }344- else if (!PyString_Check(item))345- return 0;346-347- name = PyString_AS_STRING(item);348- if (name[0] == ':' && name[1] == ':')349- return 0;350-351- while (current) {352- /* XXX: for 2.4 and newer, use PyDict_Contains */353- if (!PyMapping_HasKey(current->dict, item)) {354- current = current->prev;355- continue;356- }357- return 1;358- }359-360- return 0;361-}362-363-/**364- * Set an value in the highest layer or delete one.365- */366-static int367-BaseContext_setitem(BaseContext *self, PyObject *item, PyObject *value)368-{369- /* allow unicode objects as keys as long as they are ASCII */370- if (PyUnicode_CheckExact(item)) {371- item = PyUnicode_AsASCIIString(item);372- if (!item) {373- PyErr_Clear();374- goto error;375- }376- }377- else if (!PyString_Check(item))378- goto error;379- if (!value)380- return PyDict_DelItem(self->current->dict, item);381- return PyDict_SetItem(self->current->dict, item, value);382-383-error:384- PyErr_SetString(PyExc_TypeError, "expected string argument");385- return -1;386-}387-388-389-static PyGetSetDef BaseContext_getsetters[] = {390- {"stack", (getter)BaseContext_getstack, NULL,391- "a read only copy of the internal stack", NULL},392- {"current", (getter)BaseContext_getcurrent, NULL,393- "reference to the current layer on the stack", NULL},394- {"initial", (getter)BaseContext_getinitial, NULL,395- "reference to the initial layer on the stack", NULL},396- {"globals", (getter)BaseContext_getglobals, NULL,397- "reference to the global layer on the stack", NULL},398- {NULL} /* Sentinel */399-};400-401-static PyMethodDef BaseContext_methods[] = {402- {"pop", (PyCFunction)BaseContext_pop, METH_NOARGS,403- "ctx.pop() -> dict\n\n"404- "Pop the last layer from the stack and return it."},405- {"push", (PyCFunction)BaseContext_push, METH_VARARGS,406- "ctx.push([layer]) -> layer\n\n"407- "Push one layer to the stack. Layer must be a dict "408- "or omitted."},409- {NULL} /* Sentinel */410-};411-412-static PySequenceMethods BaseContext_as_sequence = {413- 0, /* sq_length */414- 0, /* sq_concat */415- 0, /* sq_repeat */416- 0, /* sq_item */417- 0, /* sq_slice */418- 0, /* sq_ass_item */419- 0, /* sq_ass_slice */420- (objobjproc)BaseContext_contains,/* sq_contains */421- 0, /* sq_inplace_concat */422- 0 /* sq_inplace_repeat */423-};424-425-static PyMappingMethods BaseContext_as_mapping = {426- NULL,427- (binaryfunc)BaseContext_getitem,428- (objobjargproc)BaseContext_setitem429-};430-431-static PyTypeObject BaseContextType = {432- PyObject_HEAD_INIT(NULL)433- 0, /* ob_size */434- "jinja._speedups.BaseContext", /* tp_name */435- sizeof(BaseContext), /* tp_basicsize */436- 0, /* tp_itemsize */437- (destructor)BaseContext_dealloc,/* tp_dealloc */438- 0, /* tp_print */439- 0, /* tp_getattr */440- 0, /* tp_setattr */441- 0, /* tp_compare */442- 0, /* tp_repr */443- 0, /* tp_as_number */444- &BaseContext_as_sequence, /* tp_as_sequence */445- &BaseContext_as_mapping, /* tp_as_mapping */446- 0, /* tp_hash */447- 0, /* tp_call */448- 0, /* tp_str */449- 0, /* tp_getattro */450- 0, /* tp_setattro */451- 0, /* tp_as_buffer */452- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,453- /*tp_flags*/454- "", /* tp_doc */455- (traverseproc)BaseContext_traverse, /* tp_traverse */456- (inquiry)BaseContext_clear, /* tp_clear */457- 0, /* tp_richcompare */458- 0, /* tp_weaklistoffset */459- 0, /* tp_iter */460- 0, /* tp_iternext */461- BaseContext_methods, /* tp_methods */462- 0, /* tp_members */463- BaseContext_getsetters, /* tp_getset */464- 0, /* tp_base */465- 0, /* tp_dict */466- 0, /* tp_descr_get */467- 0, /* tp_descr_set */468- 0, /* tp_dictoffset */469- (initproc)BaseContext_init, /* tp_init */470- 0, /* tp_alloc */471- 0 /* tp_new */472-};473-474-static PyMethodDef module_methods[] = {475- {NULL, NULL, 0, NULL} /* Sentinel */476-};477-478-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */479-#define PyMODINIT_FUNC void480-#endif481-PyMODINIT_FUNC482-init_speedups(void)483-{484- PyObject *module;485-486- BaseContextType.tp_new = (newfunc)PyType_GenericNew;487- if (PyType_Ready(&BaseContextType) < 0)488- return;489-490- if (!init_constants())491- return;492-493- module = Py_InitModule3("_speedups", module_methods, "");494- if (!module)495- return;496-497- Py_INCREF(&BaseContextType);498- PyModule_AddObject(module, "BaseContext", (PyObject*)&BaseContextType);499-}modified:jinja2/compiler.py+16 added-5 removed
245 unmodified lines246 # can safely assume that we're a child template and do some247 # more optimizations.248 self.has_known_extends = False249 250+ # the current line number251+ self.lineno = 1252+253+ # the debug information254+ self.debug_info = []255+256 # the number of new lines before the next write()257 self._new_lines = 0258 259 # the line number of the last written statement45 unmodified lines305 """Write a string into the output stream."""306 if self._new_lines:307 if not self._first_write:308 self.stream.write('\n' * self._new_lines)309+ self.lineno += self._new_lines310 self._first_write = False311 self.stream.write(' ' * self._indentation)312 self._new_lines = 0313 self.stream.write(x)6 unmodified lines320 def newline(self, node=None, extra=0):321 """Add one or more newlines before the next write."""322 self._new_lines = max(self._new_lines, 1 + extra)323 if node is not None and node.lineno != self._last_line:317- self.write('# line: %s' % node.lineno)318- self._new_lines = 1319- self._last_line = node.lineno324+ self.debug_info.append((node.lineno, self.lineno))325 326 def signature(self, node, frame, have_comma=True, extra_kwargs=None):327 """Writes a function call to the stream for the current node.328 Per default it will write a leading comma but this can be114 unmodified lines443 444 def visit_Template(self, node, frame=None):445 assert frame is None, 'no root frame allowed'446 self.writeline('from jinja2.runtime import *')442- self.writeline('filename = %r' % self.filename)447+ self.writeline('name = %r' % self.filename)448 449 # do we have an extends tag at all? If not, we can save some450 # overhead by just not processing any inheritance code.451 have_extends = node.find(nodes.Extends) is not None51 unmodified lines503 self.pull_locals(block_frame)504 self.blockvisit(block.body, block_frame)505 506 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)502- for x in self.blocks), extra=1)507+ for x in self.blocks),508+ extra=1)509 510+ # add a function that returns the debug info511+ self.writeline('def get_debug_info():', extra=1)512+ self.indent()513+ self.writeline('return %r' % self.debug_info)514+515 def visit_Block(self, node, frame):516 """Call a block and register it for the template."""517 level = 1518 if frame.toplevel:527 unmodified linesadded:jinja2/debug.py+129 added
1+# -*- coding: utf-8 -*-2+"""3+ jinja2.debug4+ ~~~~~~~~~~~~5+6+ Implements the debug interface for Jinja.7+8+ :copyright: Copyright 2008 by Armin Ronacher.9+ :license: BSD.10+"""11+import re12+import sys13+from jinja2.exceptions import TemplateNotFound14+15+16+_line_re = re.compile(r'^\s*# line: (\d+)\s*$')17+18+19+def fake_exc_info(exc_info, filename, lineno, tb_back=None):20+ exc_type, exc_value, tb = exc_info21+22+ # figure the real context out23+ real_locals = tb.tb_frame.f_locals.copy()24+ locals = dict(real_locals.get('context', {}))25+ for name, value in real_locals.iteritems():26+ if name.startswith('l_'):27+ locals[name[2:]] = value28+29+ # assamble fake globals we need30+ globals = {31+ '__name__': filename,32+ '__file__': filename,33+ '__jinja_exception__': exc_info[:2]34+ }35+36+ # and fake the exception37+ code = compile('\n' * (lineno - 1) + 'raise __jinja_exception__[0], ' +38+ '__jinja_exception__[1]', filename, 'exec')39+ try:40+ exec code in globals, locals41+ except:42+ exc_info = sys.exc_info()43+44+ # now we can patch the exc info accordingly45+ if tb_set_next is not None:46+ if tb_back is not None:47+ tb_set_next(tb_back, exc_info[2])48+ if tb is not None:49+ tb_set_next(exc_info[2].tb_next, tb.tb_next)50+ return exc_info51+52+53+def translate_exception(exc_info):54+ result_tb = prev_tb = None55+ initial_tb = tb = exc_info[2]56+57+ while tb is not None:58+ template = tb.tb_frame.f_globals.get('__jinja_template__')59+ if template is not None:60+ # TODO: inject faked exception with correct line number61+ lineno = template.get_corresponding_lineno(tb.tb_lineno)62+ tb = fake_exc_info(exc_info[:2] + (tb,), template.filename,63+ lineno, prev_tb)[2]64+ if result_tb is None:65+ result_tb = tb66+ prev_tb = tb67+ tb = tb.tb_next68+69+ return exc_info[:2] + (result_tb or initial_tb,)70+71+72+def _init_ugly_crap():73+ """This function implements a few ugly things so that we can patch the74+ traceback objects. The function returned allows resetting `tb_next` on75+ any python traceback object.76+ """77+ import ctypes78+ from types import TracebackType79+80+ # figure out side of _Py_ssize_t81+ if hasattr(ctypes.pythonapi, 'Py_InitModule4_64'):82+ _Py_ssize_t = ctypes.c_int6483+ else:84+ _Py_ssize_t = ctypes.c_int85+86+ # regular python87+ class _PyObject(ctypes.Structure):88+ pass89+ _PyObject._fields_ = [90+ ('ob_refcnt', _Py_ssize_t),91+ ('ob_type', ctypes.POINTER(_PyObject))92+ ]93+94+ # python with trace95+ if object.__basicsize__ != ctypes.sizeof(_PyObject):96+ class _PyObject(ctypes.Structure):97+ pass98+ _PyObject._fields_ = [99+ ('_ob_next', ctypes.POINTER(_PyObject)),100+ ('_ob_prev', ctypes.POINTER(_PyObject)),101+ ('ob_refcnt', _Py_ssize_t),102+ ('ob_type', ctypes.POINTER(_PyObject))103+ ]104+105+ class _Traceback(_PyObject):106+ pass107+ _Traceback._fields_ = [108+ ('tb_next', ctypes.POINTER(_Traceback)),109+ ('tb_frame', ctypes.POINTER(_PyObject)),110+ ('tb_lasti', ctypes.c_int),111+ ('tb_lineno', ctypes.c_int)112+ ]113+114+ def tb_set_next(tb, next):115+ if not (isinstance(tb, TracebackType) and116+ isinstance(next, TracebackType)):117+ raise TypeError('tb_set_next arguments must be traceback objects')118+ obj = _Traceback.from_address(id(tb))119+ obj.tb_next = ctypes.pointer(_Traceback.from_address(id(next)))120+121+ return tb_set_next122+123+124+# no ctypes, no fun125+try:126+ tb_set_next = _init_ugly_crap()127+except:128+ tb_set_next = None129+del _init_ugly_crapmodified:jinja2/environment.py+28 added-7 removed
6 unmodified lines7 8 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11+import sys12 from jinja2.lexer import Lexer13 from jinja2.parser import Parser14 from jinja2.optimizer import optimize15 from jinja2.compiler import generate16 from jinja2.runtime import Undefined17+from jinja2.debug import translate_exception18 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19 20 21 class Environment(object):93 unmodified lines115 return obj[argument]116 except (TypeError, LookupError):117 return self.undefined(obj, argument)118 117- def parse(self, source, filename=None):119+ def parse(self, source, name=None):120 """Parse the sourcecode and return the abstract syntax tree. This tree121 of nodes is used by the compiler to convert the template into122 executable source- or bytecode.123 """122- parser = Parser(self, source, filename)124+ parser = Parser(self, source, name)125 return parser.parse()126 125- def lex(self, source, filename=None):127+ def lex(self, source, name=None):128 """Lex the given sourcecode and return a generator that yields tokens.129 The stream returned is not usable for Jinja but can be used if130 Jinja templates should be processed by other tools (for example131 syntax highlighting etc)132 133 The tuples are returned in the form ``(lineno, token, value)``.134 """133- return self.lexer.tokeniter(source, filename)135+ return self.lexer.tokeniter(source, name)136 137 def compile(self, source, filename=None, raw=False, globals=None):138 """Compile a node or source."""139 if isinstance(source, basestring):140 source = self.parse(source, filename)141 if self.optimized:142 node = optimize(source, self, globals or {})143 source = generate(node, self, filename)142- print source144 if raw:145 return source146 if filename is None:147 filename = '<from_string>'35 unmodified lines183 def __init__(self, environment, code, globals):184 namespace = {'environment': environment}185 exec code in namespace186 self.environment = environment186- self.name = namespace['filename']187+ self.name = namespace['name']188+ self.filename = code.co_filename189 self.root_render_func = namespace['root']190 self.blocks = namespace['blocks']191 self.globals = globals192 193+ # debug helpers194+ self._get_debug_info = namespace['get_debug_info']195+ namespace['__jinja_template__'] = self196+197 def render(self, *args, **kwargs):198 return u''.join(self.generate(*args, **kwargs))199 200 def stream(self, *args, **kwargs):18 unmodified lines219 (plural, ', '.join(overrides), plural or ' a', plural))220 gen = self.root_render_func(dict(self.globals, **context))221 # skip the first item which is a reference to the context222 gen.next()217- return gen223 224+ try:225+ for event in gen:226+ yield event227+ except:228+ exc_info = translate_exception(sys.exc_info())229+ raise exc_info[0], exc_info[1], exc_info[2]230+231+ def get_corresponding_lineno(self, lineno):232+ """Return the source line number of a line number in the233+ generated bytecode as they are not in sync.234+ """235+ for template_line, code_line in reversed(self._get_debug_info()):236+ if code_line <= lineno:237+ return template_line238+ return 1239+240 def __repr__(self):241 return '<%s %r>' % (242 self.__class__.__name__,243 self.name48 unmodified linesmodified:jinja2/loaders.py+2 added-2 removed
17 unmodified lines18 19 def get_source(self, environment, template):20 raise TemplateNotFound()21 22- def load(self, environment, template, globals=None):23- source, filename = self.get_source(environment, template)22+ def load(self, environment, name, globals=None):23+ source, filename = self.get_source(environment, name)24 code = environment.compile(source, filename, globals=globals)25 return Template(environment, code, globals or {})26 27 32 unmodified lines