blob: 7aeddcc10553db4f42bbc1a24b98ead882145f37 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001#include "Python.h"
2#include "code.h"
3#include "structmember.h"
4
5#define NAME_CHARS \
6 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
7
8/* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
9
10static int
11all_name_chars(unsigned char *s)
12{
13 static char ok_name_char[256];
14 static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
15
16 if (ok_name_char[*name_chars] == 0) {
17 unsigned char *p;
18 for (p = name_chars; *p; p++)
19 ok_name_char[*p] = 1;
20 }
21 while (*s) {
22 if (ok_name_char[*s++] == 0)
23 return 0;
24 }
25 return 1;
26}
27
28static void
29intern_strings(PyObject *tuple)
30{
Martin v. Löwis18e16552006-02-15 17:27:45 +000031 Py_ssize_t i;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000032
33 for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
34 PyObject *v = PyTuple_GET_ITEM(tuple, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +000035 if (v == NULL || !PyUnicode_CheckExact(v)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000036 Py_FatalError("non-string found in code slot");
37 }
Martin v. Löwis5b222132007-06-10 09:51:05 +000038 PyUnicode_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000039 }
40}
41
42
43PyCodeObject *
Guido van Rossum4f72a782006-10-27 23:31:49 +000044PyCode_New(int argcount, int kwonlyargcount,
45 int nlocals, int stacksize, int flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000046 PyObject *code, PyObject *consts, PyObject *names,
47 PyObject *varnames, PyObject *freevars, PyObject *cellvars,
48 PyObject *filename, PyObject *name, int firstlineno,
49 PyObject *lnotab)
50{
51 PyCodeObject *co;
Martin v. Löwis18e16552006-02-15 17:27:45 +000052 Py_ssize_t i;
Guido van Rossum00bc0e02007-10-15 02:52:41 +000053
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054 /* Check argument types */
55 if (argcount < 0 || nlocals < 0 ||
56 code == NULL ||
57 consts == NULL || !PyTuple_Check(consts) ||
58 names == NULL || !PyTuple_Check(names) ||
59 varnames == NULL || !PyTuple_Check(varnames) ||
60 freevars == NULL || !PyTuple_Check(freevars) ||
61 cellvars == NULL || !PyTuple_Check(cellvars) ||
Guido van Rossum00bc0e02007-10-15 02:52:41 +000062 name == NULL || !PyUnicode_Check(name) ||
63 filename == NULL || !PyUnicode_Check(filename) ||
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000064 lnotab == NULL || !PyString_Check(lnotab) ||
65 !PyObject_CheckReadBuffer(code)) {
66 PyErr_BadInternalCall();
67 return NULL;
68 }
Guido van Rossum00bc0e02007-10-15 02:52:41 +000069 Py_INCREF(name);
70 Py_INCREF(filename);
71
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000072 intern_strings(names);
73 intern_strings(varnames);
74 intern_strings(freevars);
75 intern_strings(cellvars);
76 /* Intern selected string constants */
77 for (i = PyTuple_Size(consts); --i >= 0; ) {
78 PyObject *v = PyTuple_GetItem(consts, i);
79 if (!PyString_Check(v))
80 continue;
81 if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
82 continue;
83 PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
84 }
85 co = PyObject_NEW(PyCodeObject, &PyCode_Type);
86 if (co != NULL) {
87 co->co_argcount = argcount;
Guido van Rossum4f72a782006-10-27 23:31:49 +000088 co->co_kwonlyargcount = kwonlyargcount;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000089 co->co_nlocals = nlocals;
90 co->co_stacksize = stacksize;
91 co->co_flags = flags;
92 Py_INCREF(code);
93 co->co_code = code;
94 Py_INCREF(consts);
95 co->co_consts = consts;
96 Py_INCREF(names);
97 co->co_names = names;
98 Py_INCREF(varnames);
99 co->co_varnames = varnames;
100 Py_INCREF(freevars);
101 co->co_freevars = freevars;
102 Py_INCREF(cellvars);
103 co->co_cellvars = cellvars;
104 Py_INCREF(filename);
105 co->co_filename = filename;
106 Py_INCREF(name);
107 co->co_name = name;
108 co->co_firstlineno = firstlineno;
109 Py_INCREF(lnotab);
110 co->co_lnotab = lnotab;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000111 co->co_zombieframe = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000112 }
Neal Norwitz41103bf2007-08-24 23:12:06 +0000113 Py_DECREF(name);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000114 return co;
115}
116
117
118#define OFF(x) offsetof(PyCodeObject, x)
119
120static PyMemberDef code_memberlist[] = {
121 {"co_argcount", T_INT, OFF(co_argcount), READONLY},
Guido van Rossum4f72a782006-10-27 23:31:49 +0000122 {"co_kwonlyargcount", T_INT, OFF(co_kwonlyargcount), READONLY},
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123 {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
124 {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
125 {"co_flags", T_INT, OFF(co_flags), READONLY},
126 {"co_code", T_OBJECT, OFF(co_code), READONLY},
127 {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
128 {"co_names", T_OBJECT, OFF(co_names), READONLY},
129 {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
130 {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
131 {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
132 {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
133 {"co_name", T_OBJECT, OFF(co_name), READONLY},
134 {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
135 {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
136 {NULL} /* Sentinel */
137};
138
139/* Helper for code_new: return a shallow copy of a tuple that is
140 guaranteed to contain exact strings, by converting string subclasses
141 to exact strings and complaining if a non-string is found. */
142static PyObject*
143validate_and_copy_tuple(PyObject *tup)
144{
145 PyObject *newtuple;
146 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +0000147 Py_ssize_t i, len;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000148
149 len = PyTuple_GET_SIZE(tup);
150 newtuple = PyTuple_New(len);
151 if (newtuple == NULL)
152 return NULL;
153
154 for (i = 0; i < len; i++) {
155 item = PyTuple_GET_ITEM(tup, i);
Martin v. Löwis5b222132007-06-10 09:51:05 +0000156 if (PyUnicode_CheckExact(item)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000157 Py_INCREF(item);
158 }
Martin v. Löwis5b222132007-06-10 09:51:05 +0000159 else if (!PyUnicode_Check(item)) {
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000160 PyErr_Format(
161 PyExc_TypeError,
162 "name tuples must contain only "
163 "strings, not '%.500s'",
164 item->ob_type->tp_name);
165 Py_DECREF(newtuple);
166 return NULL;
167 }
168 else {
Martin v. Löwis5b222132007-06-10 09:51:05 +0000169 item = PyUnicode_FromUnicode(
170 PyUnicode_AS_UNICODE(item),
171 PyUnicode_GET_SIZE(item));
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000172 if (item == NULL) {
173 Py_DECREF(newtuple);
174 return NULL;
175 }
176 }
177 PyTuple_SET_ITEM(newtuple, i, item);
178 }
179
180 return newtuple;
181}
182
183PyDoc_STRVAR(code_doc,
184"code(argcount, nlocals, stacksize, flags, codestring, constants, names,\n\
185 varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]])\n\
186\n\
187Create a code object. Not for the faint of heart.");
188
189static PyObject *
190code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
191{
192 int argcount;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000193 int kwonlyargcount;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000194 int nlocals;
195 int stacksize;
196 int flags;
197 PyObject *co = NULL;
198 PyObject *code;
199 PyObject *consts;
200 PyObject *names, *ournames = NULL;
201 PyObject *varnames, *ourvarnames = NULL;
202 PyObject *freevars = NULL, *ourfreevars = NULL;
203 PyObject *cellvars = NULL, *ourcellvars = NULL;
204 PyObject *filename;
205 PyObject *name;
206 int firstlineno;
207 PyObject *lnotab;
208
Guido van Rossum4f72a782006-10-27 23:31:49 +0000209 if (!PyArg_ParseTuple(args, "iiiiiSO!O!O!SSiS|O!O!:code",
210 &argcount, &kwonlyargcount,
211 &nlocals, &stacksize, &flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000212 &code,
213 &PyTuple_Type, &consts,
214 &PyTuple_Type, &names,
215 &PyTuple_Type, &varnames,
216 &filename, &name,
217 &firstlineno, &lnotab,
218 &PyTuple_Type, &freevars,
219 &PyTuple_Type, &cellvars))
220 return NULL;
221
222 if (argcount < 0) {
223 PyErr_SetString(
224 PyExc_ValueError,
225 "code: argcount must not be negative");
226 goto cleanup;
227 }
228
Guido van Rossum4f72a782006-10-27 23:31:49 +0000229 if (kwonlyargcount < 0) {
230 PyErr_SetString(
231 PyExc_ValueError,
232 "code: kwonlyargcount must not be negative");
233 goto cleanup;
234 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000235 if (nlocals < 0) {
236 PyErr_SetString(
237 PyExc_ValueError,
238 "code: nlocals must not be negative");
239 goto cleanup;
240 }
241
242 ournames = validate_and_copy_tuple(names);
243 if (ournames == NULL)
244 goto cleanup;
245 ourvarnames = validate_and_copy_tuple(varnames);
246 if (ourvarnames == NULL)
247 goto cleanup;
248 if (freevars)
249 ourfreevars = validate_and_copy_tuple(freevars);
250 else
251 ourfreevars = PyTuple_New(0);
252 if (ourfreevars == NULL)
253 goto cleanup;
254 if (cellvars)
255 ourcellvars = validate_and_copy_tuple(cellvars);
256 else
257 ourcellvars = PyTuple_New(0);
258 if (ourcellvars == NULL)
259 goto cleanup;
260
Guido van Rossum4f72a782006-10-27 23:31:49 +0000261 co = (PyObject *)PyCode_New(argcount, kwonlyargcount,
262 nlocals, stacksize, flags,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000263 code, consts, ournames, ourvarnames,
264 ourfreevars, ourcellvars, filename,
265 name, firstlineno, lnotab);
266 cleanup:
267 Py_XDECREF(ournames);
268 Py_XDECREF(ourvarnames);
269 Py_XDECREF(ourfreevars);
270 Py_XDECREF(ourcellvars);
271 return co;
272}
273
274static void
275code_dealloc(PyCodeObject *co)
276{
277 Py_XDECREF(co->co_code);
278 Py_XDECREF(co->co_consts);
279 Py_XDECREF(co->co_names);
280 Py_XDECREF(co->co_varnames);
281 Py_XDECREF(co->co_freevars);
282 Py_XDECREF(co->co_cellvars);
283 Py_XDECREF(co->co_filename);
284 Py_XDECREF(co->co_name);
285 Py_XDECREF(co->co_lnotab);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000286 if (co->co_zombieframe != NULL)
287 PyObject_GC_Del(co->co_zombieframe);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288 PyObject_DEL(co);
289}
290
291static PyObject *
292code_repr(PyCodeObject *co)
293{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000294 int lineno = -1;
295 char *filename = "???";
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000296
297 if (co->co_firstlineno != 0)
298 lineno = co->co_firstlineno;
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000299 if (co->co_filename && PyUnicode_Check(co->co_filename))
300 filename = PyUnicode_AsString(co->co_filename);
Walter Dörwald933daed2007-06-06 15:15:34 +0000301 return PyUnicode_FromFormat(
Neal Norwitz41103bf2007-08-24 23:12:06 +0000302 "<code object %.100U at %p, file \"%.300s\", line %d>",
303 co->co_name, co, filename, lineno);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000304}
305
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000306static PyObject *
307code_richcompare(PyObject *self, PyObject *other, int op)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308{
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000309 PyCodeObject *co, *cp;
310 int eq;
311 PyObject *res;
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000312
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000313 if ((op != Py_EQ && op != Py_NE) ||
314 !PyCode_Check(self) ||
315 !PyCode_Check(other)) {
316 Py_INCREF(Py_NotImplemented);
317 return Py_NotImplemented;
318 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000319
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000320 co = (PyCodeObject *)self;
321 cp = (PyCodeObject *)other;
322
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000323 eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000324 if (eq <= 0) goto unequal;
325 eq = co->co_argcount == cp->co_argcount;
326 if (!eq) goto unequal;
Guido van Rossum4f72a782006-10-27 23:31:49 +0000327 eq = co->co_kwonlyargcount == cp->co_kwonlyargcount;
328 if (!eq) goto unequal;
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000329 eq = co->co_nlocals == cp->co_nlocals;
330 if (!eq) goto unequal;
331 eq = co->co_flags == cp->co_flags;
332 if (!eq) goto unequal;
333 eq = co->co_firstlineno == cp->co_firstlineno;
334 if (!eq) goto unequal;
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000335 eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000336 if (eq <= 0) goto unequal;
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000337 eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000338 if (eq <= 0) goto unequal;
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000339 eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000340 if (eq <= 0) goto unequal;
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000341 eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000342 if (eq <= 0) goto unequal;
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000343 eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000344 if (eq <= 0) goto unequal;
Guido van Rossumf1624cd2006-08-24 23:43:52 +0000345 eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000346 if (eq <= 0) goto unequal;
347
348 if (op == Py_EQ)
349 res = Py_True;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000350 else
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000351 res = Py_False;
352 goto done;
353
354 unequal:
355 if (eq < 0)
356 return NULL;
357 if (op == Py_NE)
358 res = Py_True;
359 else
360 res = Py_False;
361
362 done:
363 Py_INCREF(res);
364 return res;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000365}
366
367static long
368code_hash(PyCodeObject *co)
369{
370 long h, h0, h1, h2, h3, h4, h5, h6;
371 h0 = PyObject_Hash(co->co_name);
372 if (h0 == -1) return -1;
373 h1 = PyObject_Hash(co->co_code);
374 if (h1 == -1) return -1;
375 h2 = PyObject_Hash(co->co_consts);
376 if (h2 == -1) return -1;
377 h3 = PyObject_Hash(co->co_names);
378 if (h3 == -1) return -1;
379 h4 = PyObject_Hash(co->co_varnames);
380 if (h4 == -1) return -1;
381 h5 = PyObject_Hash(co->co_freevars);
382 if (h5 == -1) return -1;
383 h6 = PyObject_Hash(co->co_cellvars);
384 if (h6 == -1) return -1;
385 h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
Guido van Rossum4f72a782006-10-27 23:31:49 +0000386 co->co_argcount ^ co->co_kwonlyargcount ^
387 co->co_nlocals ^ co->co_flags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000388 if (h == -1) h = -2;
389 return h;
390}
391
392/* XXX code objects need to participate in GC? */
393
394PyTypeObject PyCode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000395 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000396 "code",
397 sizeof(PyCodeObject),
398 0,
399 (destructor)code_dealloc, /* tp_dealloc */
400 0, /* tp_print */
401 0, /* tp_getattr */
402 0, /* tp_setattr */
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000403 0, /* tp_compare */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000404 (reprfunc)code_repr, /* tp_repr */
405 0, /* tp_as_number */
406 0, /* tp_as_sequence */
407 0, /* tp_as_mapping */
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000408 (hashfunc)code_hash, /* tp_hash */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000409 0, /* tp_call */
410 0, /* tp_str */
411 PyObject_GenericGetAttr, /* tp_getattro */
412 0, /* tp_setattro */
413 0, /* tp_as_buffer */
414 Py_TPFLAGS_DEFAULT, /* tp_flags */
415 code_doc, /* tp_doc */
416 0, /* tp_traverse */
417 0, /* tp_clear */
Guido van Rossumb6bb0c72006-08-24 04:12:18 +0000418 code_richcompare, /* tp_richcompare */
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000419 0, /* tp_weaklistoffset */
420 0, /* tp_iter */
421 0, /* tp_iternext */
422 0, /* tp_methods */
423 code_memberlist, /* tp_members */
424 0, /* tp_getset */
425 0, /* tp_base */
426 0, /* tp_dict */
427 0, /* tp_descr_get */
428 0, /* tp_descr_set */
429 0, /* tp_dictoffset */
430 0, /* tp_init */
431 0, /* tp_alloc */
432 code_new, /* tp_new */
433};
434
435/* All about c_lnotab.
436
437c_lnotab is an array of unsigned bytes disguised as a Python string. In -O
438mode, SET_LINENO opcodes aren't generated, and bytecode offsets are mapped
439to source code line #s (when needed for tracebacks) via c_lnotab instead.
440The array is conceptually a list of
441 (bytecode offset increment, line number increment)
442pairs. The details are important and delicate, best illustrated by example:
443
444 byte code offset source code line number
445 0 1
446 6 2
447 50 7
448 350 307
449 361 308
450
451The first trick is that these numbers aren't stored, only the increments
452from one row to the next (this doesn't really work, but it's a start):
453
454 0, 1, 6, 1, 44, 5, 300, 300, 11, 1
455
456The second trick is that an unsigned byte can't hold negative values, or
457values larger than 255, so (a) there's a deep assumption that byte code
458offsets and their corresponding line #s both increase monotonically, and (b)
459if at least one column jumps by more than 255 from one row to the next, more
460than one pair is written to the table. In case #b, there's no way to know
461from looking at the table later how many were written. That's the delicate
462part. A user of c_lnotab desiring to find the source line number
463corresponding to a bytecode address A should do something like this
464
465 lineno = addr = 0
466 for addr_incr, line_incr in c_lnotab:
467 addr += addr_incr
468 if addr > A:
469 return lineno
470 lineno += line_incr
471
472In order for this to work, when the addr field increments by more than 255,
473the line # increment in each pair generated must be 0 until the remaining addr
474increment is < 256. So, in the example above, com_set_lineno should not (as
475was actually done until 2.2) expand 300, 300 to 255, 255, 45, 45, but to
476255, 0, 45, 255, 0, 45.
477*/
478
479int
480PyCode_Addr2Line(PyCodeObject *co, int addrq)
481{
482 int size = PyString_Size(co->co_lnotab) / 2;
483 unsigned char *p = (unsigned char*)PyString_AsString(co->co_lnotab);
484 int line = co->co_firstlineno;
485 int addr = 0;
486 while (--size >= 0) {
487 addr += *p++;
488 if (addr > addrq)
489 break;
490 line += *p++;
491 }
492 return line;
493}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000494
495/*
496 Check whether the current instruction is at the start of a line.
497
498 */
499
500 /* The theory of SET_LINENO-less tracing.
501
502 In a nutshell, we use the co_lnotab field of the code object
503 to tell when execution has moved onto a different line.
504
505 As mentioned above, the basic idea is so set things up so
506 that
507
508 *instr_lb <= frame->f_lasti < *instr_ub
509
510 is true so long as execution does not change lines.
511
512 This is all fairly simple. Digging the information out of
513 co_lnotab takes some work, but is conceptually clear.
514
515 Somewhat harder to explain is why we don't *always* call the
516 line trace function when the above test fails.
517
518 Consider this code:
519
520 1: def f(a):
521 2: if a:
522 3: print 1
523 4: else:
524 5: print 2
525
526 which compiles to this:
527
528 2 0 LOAD_FAST 0 (a)
529 3 JUMP_IF_FALSE 9 (to 15)
530 6 POP_TOP
531
532 3 7 LOAD_CONST 1 (1)
533 10 PRINT_ITEM
534 11 PRINT_NEWLINE
535 12 JUMP_FORWARD 6 (to 21)
536 >> 15 POP_TOP
537
538 5 16 LOAD_CONST 2 (2)
539 19 PRINT_ITEM
540 20 PRINT_NEWLINE
541 >> 21 LOAD_CONST 0 (None)
542 24 RETURN_VALUE
543
544 If 'a' is false, execution will jump to instruction at offset
545 15 and the co_lnotab will claim that execution has moved to
546 line 3. This is at best misleading. In this case we could
547 associate the POP_TOP with line 4, but that doesn't make
548 sense in all cases (I think).
549
550 What we do is only call the line trace function if the co_lnotab
551 indicates we have jumped to the *start* of a line, i.e. if the
552 current instruction offset matches the offset given for the
553 start of a line by the co_lnotab.
554
555 This also takes care of the situation where 'a' is true.
556 Execution will jump from instruction offset 12 to offset 21.
557 Then the co_lnotab would imply that execution has moved to line
558 5, which is again misleading.
559
560 Why do we set f_lineno when tracing? Well, consider the code
561 above when 'a' is true. If stepping through this with 'n' in
562 pdb, you would stop at line 1 with a "call" type event, then
563 line events on lines 2 and 3, then a "return" type event -- but
564 you would be shown line 5 during this event. This is a change
565 from the behaviour in 2.2 and before, and I've found it
566 confusing in practice. By setting and using f_lineno when
567 tracing, one can report a line number different from that
568 suggested by f_lasti on this one occasion where it's desirable.
569 */
570
571
572int
573PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
574{
575 int size, addr, line;
576 unsigned char* p;
577
578 p = (unsigned char*)PyString_AS_STRING(co->co_lnotab);
579 size = PyString_GET_SIZE(co->co_lnotab) / 2;
580
581 addr = 0;
582 line = co->co_firstlineno;
583 assert(line > 0);
584
585 /* possible optimization: if f->f_lasti == instr_ub
586 (likely to be a common case) then we already know
587 instr_lb -- if we stored the matching value of p
588 somwhere we could skip the first while loop. */
589
590 /* see comments in compile.c for the description of
591 co_lnotab. A point to remember: increments to p
592 should come in pairs -- although we don't care about
593 the line increments here, treating them as byte
594 increments gets confusing, to say the least. */
595
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000596 bounds->ap_lower = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597 while (size > 0) {
598 if (addr + *p > lasti)
599 break;
600 addr += *p++;
601 if (*p)
602 bounds->ap_lower = addr;
603 line += *p++;
604 --size;
605 }
606
607 /* If lasti and addr don't match exactly, we don't want to
608 change the lineno slot on the frame or execute a trace
609 function. Return -1 instead.
610 */
611 if (addr != lasti)
612 line = -1;
613
614 if (size > 0) {
615 while (--size >= 0) {
616 addr += *p++;
617 if (*p++)
618 break;
619 }
620 bounds->ap_upper = addr;
621 }
622 else {
623 bounds->ap_upper = INT_MAX;
624 }
625
626 return line;
627}