Skip to content
Myr

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

9 files+189 added−663 removed

added:examples/cycle.py+13 added
1from jinja2 import Environment234env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}")567print 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
1from jinja2 import Environment23print 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 */1617#include <Python.h>181920/**21 * set the tb_next attribute of a traceback object22 */23static PyObject *24tb_set_next(PyObject *self, PyObject *args)25{26 PyTracebackObject *tb, *old;27 PyObject *next;2829 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);4041 old = tb->tb_next;42 tb->tb_next = (PyTracebackObject*)next;43 Py_XDECREF(old);4445 Py_INCREF(Py_None);46 return Py_None;47}484950static 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};5556#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */57#define PyMODINIT_FUNC void58#endif59PyMODINIT_FUNC60init_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 ~~~~~~~~~~~~~56 This module implements the native base classes in case of not7 having a jinja with the _speedups module compiled.89 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.1213 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16from jinja.datastructure import Deferred17from jinja.utils import deque181920class BaseContext(object):2122 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 = initial2829 self._push = self._stack.appendleft30 self._pop = self._stack.popleft3132 def stack(self):33 return list(self._stack)[::-1]34 stack = property(stack)3536 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 rv4142 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 data5152 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_singleton7071 def __setitem__(self, name, value):72 """Set a variable in the outermost layer."""73 self.current[name] = value7475 def __delitem__(self, name):76 """Delete a variable in the outermost layer."""77 if name in self.current:78 del self.current[name]7980 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 False
deleted: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 */1617#include <Python.h>18#include <structmember.h>1920/* Set by init_constants to real values */21static PyObject *Deferred;2223/**24 * Internal struct used by BaseContext to store the25 * stacked namespaces.26 */27struct StackLayer {28 PyObject *dict; /* current value, a dict */29 struct StackLayer *prev; /* lower struct layer or NULL */30};3132/**33 * BaseContext python class.34 */35typedef 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;4344/**45 * Called by init_speedups in order to retrieve references46 * to some exceptions and classes defined in jinja python modules47 */48static int49init_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}5859/**60 * GC Helper61 */62static int63BaseContext_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}7677/**78 * Deallocator for BaseContext.79 *80 * Frees the memory for the stack layers before freeing the object.81 */82static void83BaseContext_dealloc(BaseContext *self)84{85 BaseContext_clear(self);86 self->ob_type->tp_free((PyObject*)self);87}8889/**90 * GC Helper91 */92static int93BaseContext_traverse(BaseContext *self, visitproc visit, void *args)94{95 int vret;96 struct StackLayer *layer = self->current;9798 while (layer) {99 vret = visit(layer->dict, args);100 if (vret != 0)101 return vret;102 layer = layer->prev;103 }104105 return 0;106}107108/**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 */117static int118BaseContext_init(BaseContext *self, PyObject *args, PyObject *kwds)119{120 PyObject *undefined = NULL, *globals = NULL, *initial = NULL;121122 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 }128129 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;134135 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;140141 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;146147 self->undefined_singleton = undefined;148 Py_INCREF(undefined);149150 self->stacksize = 3;151 return 0;152}153154/**155 * Pop the highest layer from the stack and return it156 */157static PyObject*158BaseContext_pop(BaseContext *self)159{160 PyObject *result;161 struct StackLayer *tmp = self->current;162163 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}175176/**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 */181static PyObject*182BaseContext_push(BaseContext *self, PyObject *args)183{184 PyObject *value = NULL;185 struct StackLayer *new;186187 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}212213/**214 * Getter that creates a list representation of the internal215 * stack. Used for compatibility with the native python implementation.216 */217static PyObject*218BaseContext_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}233234/**235 * Getter that returns a reference to the current layer in the context.236 */237static PyObject*238BaseContext_getcurrent(BaseContext *self, void *closure)239{240 Py_INCREF(self->current->dict);241 return self->current->dict;242}243244/**245 * Getter that returns a reference to the initial layer in the context.246 */247static PyObject*248BaseContext_getinitial(BaseContext *self, void *closure)249{250 Py_INCREF(self->initial->dict);251 return self->initial->dict;252}253254/**255 * Getter that returns a reference to the global layer in the context.256 */257static PyObject*258BaseContext_getglobals(BaseContext *self, void *closure)259{260 Py_INCREF(self->globals->dict);261 return self->globals->dict;262}263264/**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 */271static PyObject*272BaseContext_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;287288 /* disallow access to internal jinja values */289 name = PyString_AS_STRING(item);290 if (name[0] == ':' && name[1] == ':')291 goto missing;292293 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;309310 /* 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 }323324missing:325 Py_INCREF(self->undefined_singleton);326 return self->undefined_singleton;327}328329/**330 * Check if the context contains a given value.331 */332static int333BaseContext_contains(BaseContext *self, PyObject *item)334{335 char *name;336 struct StackLayer *current = self->current;337338 /* 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;346347 name = PyString_AS_STRING(item);348 if (name[0] == ':' && name[1] == ':')349 return 0;350351 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 }359360 return 0;361}362363/**364 * Set an value in the highest layer or delete one.365 */366static int367BaseContext_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);382383error:384 PyErr_SetString(PyExc_TypeError, "expected string argument");385 return -1;386}387388389static 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};400401static 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};411412static 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};424425static PyMappingMethods BaseContext_as_mapping = {426 NULL,427 (binaryfunc)BaseContext_getitem,428 (objobjargproc)BaseContext_setitem429};430431static 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};473474static PyMethodDef module_methods[] = {475 {NULL, NULL, 0, NULL} /* Sentinel */476};477478#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */479#define PyMODINIT_FUNC void480#endif481PyMODINIT_FUNC482init_speedups(void)483{484 PyObject *module;485486 BaseContextType.tp_new = (newfunc)PyType_GenericNew;487 if (PyType_Ready(&BaseContextType) < 0)488 return;489490 if (!init_constants())491 return;492493 module = Py_InitModule3("_speedups", module_methods, "");494 if (!module)495 return;496497 Py_INCREF(&BaseContextType);498 PyModule_AddObject(module, "BaseContext", (PyObject*)&BaseContextType);499}
modified:jinja2/compiler.py+16 added-5 removed
245 unmodified lines
246 # can safely assume that we're a child template and do some247 # more optimizations.248 self.has_known_extends = False249250 # the current line number251 self.lineno = 1252253 # the debug information254 self.debug_info = []255256 # the number of new lines before the next write()257 self._new_lines = 0258259 # the line number of the last written statement
45 unmodified lines
305 """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 lines
320 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))325326 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 be
114 unmodified lines
443444 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)448449 # 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 None
51 unmodified lines
503 self.pull_locals(block_frame)504 self.blockvisit(block.body, block_frame)505506 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)509510 # 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)514515 def visit_Block(self, node, frame):516 """Call a block and register it for the template."""517 level = 1518 if frame.toplevel:
527 unmodified lines
added:jinja2/debug.py+129 added
1# -*- coding: utf-8 -*-2"""3 jinja2.debug4 ~~~~~~~~~~~~56 Implements the debug interface for Jinja.78 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11import re12import sys13from jinja2.exceptions import TemplateNotFound141516_line_re = re.compile(r'^\s*# line: (\d+)\s*$')171819def fake_exc_info(exc_info, filename, lineno, tb_back=None):20 exc_type, exc_value, tb = exc_info2122 # 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:]] = value2829 # assamble fake globals we need30 globals = {31 '__name__': filename,32 '__file__': filename,33 '__jinja_exception__': exc_info[:2]34 }3536 # 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()4344 # 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_info515253def translate_exception(exc_info):54 result_tb = prev_tb = None55 initial_tb = tb = exc_info[2]5657 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_next6869 return exc_info[:2] + (result_tb or initial_tb,)707172def _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 TracebackType7980 # 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_int8586 # regular python87 class _PyObject(ctypes.Structure):88 pass89 _PyObject._fields_ = [90 ('ob_refcnt', _Py_ssize_t),91 ('ob_type', ctypes.POINTER(_PyObject))92 ]9394 # 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 ]104105 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 ]113114 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)))120121 return tb_set_next122123124# no ctypes, no fun125try:126 tb_set_next = _init_ugly_crap()127except:128 tb_set_next = None129del _init_ugly_crap
modified:jinja2/environment.py+28 added-7 removed
6 unmodified lines
78 :copyright: 2007 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import sys12from jinja2.lexer import Lexer13from jinja2.parser import Parser14from jinja2.optimizer import optimize15from jinja2.compiler import generate16from jinja2.runtime import Undefined17from jinja2.debug import translate_exception18from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE192021class Environment(object):
93 unmodified lines
115 return obj[argument]116 except (TypeError, LookupError):117 return self.undefined(obj, argument)118117 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()126125 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)132133 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)136137 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 lines
183 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 = globals192193 # debug helpers194 self._get_debug_info = namespace['get_debug_info']195 namespace['__jinja_template__'] = self196197 def render(self, *args, **kwargs):198 return u''.join(self.generate(*args, **kwargs))199200 def stream(self, *args, **kwargs):
18 unmodified lines
219 (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 gen223224 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]230231 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 1239240 def __repr__(self):241 return '<%s %r>' % (242 self.__class__.__name__,243 self.name
48 unmodified lines
modified:jinja2/loaders.py+2 added-2 removed
17 unmodified lines
1819 def get_source(self, environment, template):20 raise TemplateNotFound()2122 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 {})2627
32 unmodified lines