_make_boundary(): Fix for SF bug #745478, broken boundary calculation
[python/dscho.git] / Python / ceval.c
blobabefd32f12a9bf83a8066ccfd44771a49f224022
2 /* Execute compiled code */
4 /* XXX TO DO:
5 XXX speed up searching for keywords by using a dictionary
6 XXX document it!
7 */
9 #include "Python.h"
11 #include "compile.h"
12 #include "frameobject.h"
13 #include "eval.h"
14 #include "opcode.h"
15 #include "structmember.h"
17 #ifdef macintosh
18 #include "macglue.h"
19 #endif
21 #include <ctype.h>
23 /* Turn this on if your compiler chokes on the big switch: */
24 /* #define CASE_TOO_BIG 1 */
26 #ifdef Py_DEBUG
27 /* For debugging the interpreter: */
28 #define LLTRACE 1 /* Low-level trace feature */
29 #define CHECKEXC 1 /* Double-check exception checking */
30 #endif
32 typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *);
34 /* Forward declarations */
35 static PyObject *eval_frame(PyFrameObject *);
36 static PyObject *call_function(PyObject ***, int);
37 static PyObject *fast_function(PyObject *, PyObject ***, int, int, int);
38 static PyObject *do_call(PyObject *, PyObject ***, int, int);
39 static PyObject *ext_do_call(PyObject *, PyObject ***, int, int, int);
40 static PyObject *update_keyword_args(PyObject *, int, PyObject ***,PyObject *);
41 static PyObject *update_star_args(int, int, PyObject *, PyObject ***);
42 static PyObject *load_args(PyObject ***, int);
43 #define CALL_FLAG_VAR 1
44 #define CALL_FLAG_KW 2
46 #ifdef LLTRACE
47 static int prtrace(PyObject *, char *);
48 #endif
49 static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *,
50 int, PyObject *);
51 static void call_trace_protected(Py_tracefunc, PyObject *,
52 PyFrameObject *, int);
53 static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
54 static int maybe_call_line_trace(Py_tracefunc, PyObject *,
55 PyFrameObject *, int *, int *);
57 static PyObject *apply_slice(PyObject *, PyObject *, PyObject *);
58 static int assign_slice(PyObject *, PyObject *,
59 PyObject *, PyObject *);
60 static PyObject *cmp_outcome(int, PyObject *, PyObject *);
61 static PyObject *import_from(PyObject *, PyObject *);
62 static int import_all_from(PyObject *, PyObject *);
63 static PyObject *build_class(PyObject *, PyObject *, PyObject *);
64 static int exec_statement(PyFrameObject *,
65 PyObject *, PyObject *, PyObject *);
66 static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
67 static void reset_exc_info(PyThreadState *);
68 static void format_exc_check_arg(PyObject *, char *, PyObject *);
70 #define NAME_ERROR_MSG \
71 "name '%.200s' is not defined"
72 #define GLOBAL_NAME_ERROR_MSG \
73 "global name '%.200s' is not defined"
74 #define UNBOUNDLOCAL_ERROR_MSG \
75 "local variable '%.200s' referenced before assignment"
76 #define UNBOUNDFREE_ERROR_MSG \
77 "free variable '%.200s' referenced before assignment" \
78 " in enclosing scope"
80 /* Dynamic execution profile */
81 #ifdef DYNAMIC_EXECUTION_PROFILE
82 #ifdef DXPAIRS
83 static long dxpairs[257][256];
84 #define dxp dxpairs[256]
85 #else
86 static long dxp[256];
87 #endif
88 #endif
90 /* Function call profile */
91 #ifdef CALL_PROFILE
92 #define PCALL_NUM 11
93 static int pcall[PCALL_NUM];
95 #define PCALL_ALL 0
96 #define PCALL_FUNCTION 1
97 #define PCALL_FAST_FUNCTION 2
98 #define PCALL_FASTER_FUNCTION 3
99 #define PCALL_METHOD 4
100 #define PCALL_BOUND_METHOD 5
101 #define PCALL_CFUNCTION 6
102 #define PCALL_TYPE 7
103 #define PCALL_GENERATOR 8
104 #define PCALL_OTHER 9
105 #define PCALL_POP 10
107 /* Notes about the statistics
109 PCALL_FAST stats
111 FAST_FUNCTION means no argument tuple needs to be created.
112 FASTER_FUNCTION means that the fast-path frame setup code is used.
114 If there is a method call where the call can be optimized by changing
115 the argument tuple and calling the function directly, it gets recorded
116 twice.
118 As a result, the relationship among the statistics appears to be
119 PCALL_ALL == PCALL_FUNCTION + PCALL_METHOD - PCALL_BOUND_METHOD +
120 PCALL_CFUNCTION + PCALL_TYPE + PCALL_GENERATOR + PCALL_OTHER
121 PCALL_FUNCTION > PCALL_FAST_FUNCTION > PCALL_FASTER_FUNCTION
122 PCALL_METHOD > PCALL_BOUND_METHOD
125 #define PCALL(POS) pcall[POS]++
127 PyObject *
128 PyEval_GetCallStats(PyObject *self)
130 return Py_BuildValue("iiiiiiiiii",
131 pcall[0], pcall[1], pcall[2], pcall[3],
132 pcall[4], pcall[5], pcall[6], pcall[7],
133 pcall[8], pcall[9]);
135 #else
136 #define PCALL(O)
138 PyObject *
139 PyEval_GetCallStats(PyObject *self)
141 Py_INCREF(Py_None);
142 return Py_None;
144 #endif
146 static PyTypeObject gentype;
148 typedef struct {
149 PyObject_HEAD
150 /* The gi_ prefix is intended to remind of generator-iterator. */
152 PyFrameObject *gi_frame;
154 /* True if generator is being executed. */
155 int gi_running;
157 /* List of weak reference. */
158 PyObject *gi_weakreflist;
159 } genobject;
161 static PyObject *
162 gen_new(PyFrameObject *f)
164 genobject *gen = PyObject_GC_New(genobject, &gentype);
165 if (gen == NULL) {
166 Py_DECREF(f);
167 return NULL;
169 gen->gi_frame = f;
170 gen->gi_running = 0;
171 gen->gi_weakreflist = NULL;
172 _PyObject_GC_TRACK(gen);
173 return (PyObject *)gen;
176 static int
177 gen_traverse(genobject *gen, visitproc visit, void *arg)
179 return visit((PyObject *)gen->gi_frame, arg);
182 static void
183 gen_dealloc(genobject *gen)
185 _PyObject_GC_UNTRACK(gen);
186 if (gen->gi_weakreflist != NULL)
187 PyObject_ClearWeakRefs((PyObject *) gen);
188 Py_DECREF(gen->gi_frame);
189 PyObject_GC_Del(gen);
192 static PyObject *
193 gen_iternext(genobject *gen)
195 PyThreadState *tstate = PyThreadState_GET();
196 PyFrameObject *f = gen->gi_frame;
197 PyObject *result;
199 if (gen->gi_running) {
200 PyErr_SetString(PyExc_ValueError,
201 "generator already executing");
202 return NULL;
204 if (f->f_stacktop == NULL)
205 return NULL;
207 /* Generators always return to their most recent caller, not
208 * necessarily their creator. */
209 Py_XINCREF(tstate->frame);
210 assert(f->f_back == NULL);
211 f->f_back = tstate->frame;
213 gen->gi_running = 1;
214 result = eval_frame(f);
215 gen->gi_running = 0;
217 /* Don't keep the reference to f_back any longer than necessary. It
218 * may keep a chain of frames alive or it could create a reference
219 * cycle. */
220 Py_XDECREF(f->f_back);
221 f->f_back = NULL;
223 /* If the generator just returned (as opposed to yielding), signal
224 * that the generator is exhausted. */
225 if (result == Py_None && f->f_stacktop == NULL) {
226 Py_DECREF(result);
227 result = NULL;
230 return result;
233 static PyObject *
234 gen_getiter(PyObject *gen)
236 Py_INCREF(gen);
237 return gen;
240 static PyMemberDef gen_memberlist[] = {
241 {"gi_frame", T_OBJECT, offsetof(genobject, gi_frame), RO},
242 {"gi_running", T_INT, offsetof(genobject, gi_running), RO},
243 {NULL} /* Sentinel */
246 static PyTypeObject gentype = {
247 PyObject_HEAD_INIT(&PyType_Type)
248 0, /* ob_size */
249 "generator", /* tp_name */
250 sizeof(genobject), /* tp_basicsize */
251 0, /* tp_itemsize */
252 /* methods */
253 (destructor)gen_dealloc, /* tp_dealloc */
254 0, /* tp_print */
255 0, /* tp_getattr */
256 0, /* tp_setattr */
257 0, /* tp_compare */
258 0, /* tp_repr */
259 0, /* tp_as_number */
260 0, /* tp_as_sequence */
261 0, /* tp_as_mapping */
262 0, /* tp_hash */
263 0, /* tp_call */
264 0, /* tp_str */
265 PyObject_GenericGetAttr, /* tp_getattro */
266 0, /* tp_setattro */
267 0, /* tp_as_buffer */
268 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
269 0, /* tp_doc */
270 (traverseproc)gen_traverse, /* tp_traverse */
271 0, /* tp_clear */
272 0, /* tp_richcompare */
273 offsetof(genobject, gi_weakreflist), /* tp_weaklistoffset */
274 (getiterfunc)gen_getiter, /* tp_iter */
275 (iternextfunc)gen_iternext, /* tp_iternext */
276 0, /* tp_methods */
277 gen_memberlist, /* tp_members */
278 0, /* tp_getset */
279 0, /* tp_base */
280 0, /* tp_dict */
284 #ifdef WITH_THREAD
286 #ifndef DONT_HAVE_ERRNO_H
287 #include <errno.h>
288 #endif
289 #include "pythread.h"
291 extern int _PyThread_Started; /* Flag for Py_Exit */
293 static PyThread_type_lock interpreter_lock = 0;
294 static long main_thread = 0;
296 void
297 PyEval_InitThreads(void)
299 if (interpreter_lock)
300 return;
301 _PyThread_Started = 1;
302 interpreter_lock = PyThread_allocate_lock();
303 PyThread_acquire_lock(interpreter_lock, 1);
304 main_thread = PyThread_get_thread_ident();
307 void
308 PyEval_AcquireLock(void)
310 PyThread_acquire_lock(interpreter_lock, 1);
313 void
314 PyEval_ReleaseLock(void)
316 PyThread_release_lock(interpreter_lock);
319 void
320 PyEval_AcquireThread(PyThreadState *tstate)
322 if (tstate == NULL)
323 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
324 /* Check someone has called PyEval_InitThreads() to create the lock */
325 assert(interpreter_lock);
326 PyThread_acquire_lock(interpreter_lock, 1);
327 if (PyThreadState_Swap(tstate) != NULL)
328 Py_FatalError(
329 "PyEval_AcquireThread: non-NULL old thread state");
332 void
333 PyEval_ReleaseThread(PyThreadState *tstate)
335 if (tstate == NULL)
336 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
337 if (PyThreadState_Swap(NULL) != tstate)
338 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
339 PyThread_release_lock(interpreter_lock);
342 /* This function is called from PyOS_AfterFork to ensure that newly
343 created child processes don't hold locks referring to threads which
344 are not running in the child process. (This could also be done using
345 pthread_atfork mechanism, at least for the pthreads implementation.) */
347 void
348 PyEval_ReInitThreads(void)
350 if (!interpreter_lock)
351 return;
352 /*XXX Can't use PyThread_free_lock here because it does too
353 much error-checking. Doing this cleanly would require
354 adding a new function to each thread_*.h. Instead, just
355 create a new lock and waste a little bit of memory */
356 interpreter_lock = PyThread_allocate_lock();
357 PyThread_acquire_lock(interpreter_lock, 1);
358 main_thread = PyThread_get_thread_ident();
360 #endif
362 /* Functions save_thread and restore_thread are always defined so
363 dynamically loaded modules needn't be compiled separately for use
364 with and without threads: */
366 PyThreadState *
367 PyEval_SaveThread(void)
369 PyThreadState *tstate = PyThreadState_Swap(NULL);
370 if (tstate == NULL)
371 Py_FatalError("PyEval_SaveThread: NULL tstate");
372 #ifdef WITH_THREAD
373 if (interpreter_lock)
374 PyThread_release_lock(interpreter_lock);
375 #endif
376 return tstate;
379 void
380 PyEval_RestoreThread(PyThreadState *tstate)
382 if (tstate == NULL)
383 Py_FatalError("PyEval_RestoreThread: NULL tstate");
384 #ifdef WITH_THREAD
385 if (interpreter_lock) {
386 int err = errno;
387 PyThread_acquire_lock(interpreter_lock, 1);
388 errno = err;
390 #endif
391 PyThreadState_Swap(tstate);
395 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
396 signal handlers or Mac I/O completion routines) can schedule calls
397 to a function to be called synchronously.
398 The synchronous function is called with one void* argument.
399 It should return 0 for success or -1 for failure -- failure should
400 be accompanied by an exception.
402 If registry succeeds, the registry function returns 0; if it fails
403 (e.g. due to too many pending calls) it returns -1 (without setting
404 an exception condition).
406 Note that because registry may occur from within signal handlers,
407 or other asynchronous events, calling malloc() is unsafe!
409 #ifdef WITH_THREAD
410 Any thread can schedule pending calls, but only the main thread
411 will execute them.
412 #endif
414 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
415 There are two possible race conditions:
416 (1) nested asynchronous registry calls;
417 (2) registry calls made while pending calls are being processed.
418 While (1) is very unlikely, (2) is a real possibility.
419 The current code is safe against (2), but not against (1).
420 The safety against (2) is derived from the fact that only one
421 thread (the main thread) ever takes things out of the queue.
423 XXX Darn! With the advent of thread state, we should have an array
424 of pending calls per thread in the thread state! Later...
427 #define NPENDINGCALLS 32
428 static struct {
429 int (*func)(void *);
430 void *arg;
431 } pendingcalls[NPENDINGCALLS];
432 static volatile int pendingfirst = 0;
433 static volatile int pendinglast = 0;
434 static volatile int things_to_do = 0;
437 Py_AddPendingCall(int (*func)(void *), void *arg)
439 static int busy = 0;
440 int i, j;
441 /* XXX Begin critical section */
442 /* XXX If you want this to be safe against nested
443 XXX asynchronous calls, you'll have to work harder! */
444 if (busy)
445 return -1;
446 busy = 1;
447 i = pendinglast;
448 j = (i + 1) % NPENDINGCALLS;
449 if (j == pendingfirst) {
450 busy = 0;
451 return -1; /* Queue full */
453 pendingcalls[i].func = func;
454 pendingcalls[i].arg = arg;
455 pendinglast = j;
457 _Py_Ticker = 0;
458 things_to_do = 1; /* Signal main loop */
459 busy = 0;
460 /* XXX End critical section */
461 return 0;
465 Py_MakePendingCalls(void)
467 static int busy = 0;
468 #ifdef WITH_THREAD
469 if (main_thread && PyThread_get_thread_ident() != main_thread)
470 return 0;
471 #endif
472 if (busy)
473 return 0;
474 busy = 1;
475 things_to_do = 0;
476 for (;;) {
477 int i;
478 int (*func)(void *);
479 void *arg;
480 i = pendingfirst;
481 if (i == pendinglast)
482 break; /* Queue empty */
483 func = pendingcalls[i].func;
484 arg = pendingcalls[i].arg;
485 pendingfirst = (i + 1) % NPENDINGCALLS;
486 if (func(arg) < 0) {
487 busy = 0;
488 things_to_do = 1; /* We're not done yet */
489 return -1;
492 busy = 0;
493 return 0;
497 /* The interpreter's recursion limit */
499 static int recursion_limit = 1000;
502 Py_GetRecursionLimit(void)
504 return recursion_limit;
507 void
508 Py_SetRecursionLimit(int new_limit)
510 recursion_limit = new_limit;
513 /* Status code for main loop (reason for stack unwind) */
515 enum why_code {
516 WHY_NOT, /* No error */
517 WHY_EXCEPTION, /* Exception occurred */
518 WHY_RERAISE, /* Exception re-raised by 'finally' */
519 WHY_RETURN, /* 'return' statement */
520 WHY_BREAK, /* 'break' statement */
521 WHY_CONTINUE, /* 'continue' statement */
522 WHY_YIELD /* 'yield' operator */
525 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
526 static int unpack_iterable(PyObject *, int, PyObject **);
528 /* for manipulating the thread switch and periodic "stuff" - used to be
529 per thread, now just a pair o' globals */
530 int _Py_CheckInterval = 100;
531 volatile int _Py_Ticker = 100;
533 PyObject *
534 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
536 /* XXX raise SystemError if globals is NULL */
537 return PyEval_EvalCodeEx(co,
538 globals, locals,
539 (PyObject **)NULL, 0,
540 (PyObject **)NULL, 0,
541 (PyObject **)NULL, 0,
542 NULL);
546 /* Interpreter main loop */
548 static PyObject *
549 eval_frame(PyFrameObject *f)
551 #ifdef DXPAIRS
552 int lastopcode = 0;
553 #endif
554 PyObject **stack_pointer; /* Next free slot in value stack */
555 register unsigned char *next_instr;
556 register int opcode=0; /* Current opcode */
557 register int oparg=0; /* Current opcode argument, if any */
558 register enum why_code why; /* Reason for block stack unwind */
559 register int err; /* Error status -- nonzero if error */
560 register PyObject *x; /* Result object -- NULL if error */
561 register PyObject *v; /* Temporary objects popped off stack */
562 register PyObject *w;
563 register PyObject *u;
564 register PyObject *t;
565 register PyObject *stream = NULL; /* for PRINT opcodes */
566 register PyObject **fastlocals, **freevars;
567 PyObject *retval = NULL; /* Return value */
568 PyThreadState *tstate = PyThreadState_GET();
569 PyCodeObject *co;
571 /* when tracing we set things up so that
573 not (instr_lb <= current_bytecode_offset < instr_ub)
575 is true when the line being executed has changed. The
576 initial values are such as to make this false the first
577 time it is tested. */
578 int instr_ub = -1, instr_lb = 0;
580 unsigned char *first_instr;
581 PyObject *names;
582 PyObject *consts;
583 #ifdef LLTRACE
584 int lltrace;
585 #endif
586 #if defined(Py_DEBUG) || defined(LLTRACE)
587 /* Make it easier to find out where we are with a debugger */
588 char *filename;
589 #endif
591 /* Tuple access macros */
593 #ifndef Py_DEBUG
594 #define GETITEM(v, i) PyTuple_GET_ITEM((PyTupleObject *)(v), (i))
595 #else
596 #define GETITEM(v, i) PyTuple_GetItem((v), (i))
597 #endif
599 /* Code access macros */
601 #define INSTR_OFFSET() (next_instr - first_instr)
602 #define NEXTOP() (*next_instr++)
603 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
604 #define JUMPTO(x) (next_instr = first_instr + (x))
605 #define JUMPBY(x) (next_instr += (x))
607 /* OpCode prediction macros
608 Some opcodes tend to come in pairs thus making it possible to predict
609 the second code when the first is run. For example, COMPARE_OP is often
610 followed by JUMP_IF_FALSE or JUMP_IF_TRUE. And, those opcodes are often
611 followed by a POP_TOP.
613 Verifying the prediction costs a single high-speed test of register
614 variable against a constant. If the pairing was good, then the
615 processor has a high likelihood of making its own successful branch
616 prediction which results in a nearly zero overhead transition to the
617 next opcode.
619 A successful prediction saves a trip through the eval-loop including
620 its two unpredictable branches, the HASARG test and the switch-case.
623 #define PREDICT(op) if (*next_instr == op) goto PRED_##op
624 #define PREDICTED(op) PRED_##op: next_instr++
625 #define PREDICTED_WITH_ARG(op) PRED_##op: oparg = (next_instr[2]<<8) + \
626 next_instr[1]; next_instr += 3
628 /* Stack manipulation macros */
630 #define STACK_LEVEL() (stack_pointer - f->f_valuestack)
631 #define EMPTY() (STACK_LEVEL() == 0)
632 #define TOP() (stack_pointer[-1])
633 #define SECOND() (stack_pointer[-2])
634 #define THIRD() (stack_pointer[-3])
635 #define FOURTH() (stack_pointer[-4])
636 #define SET_TOP(v) (stack_pointer[-1] = (v))
637 #define SET_SECOND(v) (stack_pointer[-2] = (v))
638 #define SET_THIRD(v) (stack_pointer[-3] = (v))
639 #define SET_FOURTH(v) (stack_pointer[-4] = (v))
640 #define BASIC_STACKADJ(n) (stack_pointer += n)
641 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
642 #define BASIC_POP() (*--stack_pointer)
644 #ifdef LLTRACE
645 #define PUSH(v) { (void)(BASIC_PUSH(v), \
646 lltrace && prtrace(TOP(), "push")); \
647 assert(STACK_LEVEL() <= f->f_stacksize); }
648 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP())
649 #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
650 lltrace && prtrace(TOP(), "stackadj")); \
651 assert(STACK_LEVEL() <= f->f_stacksize); }
652 #else
653 #define PUSH(v) BASIC_PUSH(v)
654 #define POP() BASIC_POP()
655 #define STACKADJ(n) BASIC_STACKADJ(n)
656 #endif
658 /* Local variable macros */
660 #define GETLOCAL(i) (fastlocals[i])
662 /* The SETLOCAL() macro must not DECREF the local variable in-place and
663 then store the new value; it must copy the old value to a temporary
664 value, then store the new value, and then DECREF the temporary value.
665 This is because it is possible that during the DECREF the frame is
666 accessed by other code (e.g. a __del__ method or gc.collect()) and the
667 variable would be pointing to already-freed memory. */
668 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
669 GETLOCAL(i) = value; \
670 Py_XDECREF(tmp); } while (0)
672 /* Start of code */
674 if (f == NULL)
675 return NULL;
677 #ifdef USE_STACKCHECK
678 if (tstate->recursion_depth%10 == 0 && PyOS_CheckStack()) {
679 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
680 return NULL;
682 #endif
684 /* push frame */
685 if (++tstate->recursion_depth > recursion_limit) {
686 --tstate->recursion_depth;
687 PyErr_SetString(PyExc_RuntimeError,
688 "maximum recursion depth exceeded");
689 tstate->frame = f->f_back;
690 return NULL;
693 tstate->frame = f;
695 if (tstate->use_tracing) {
696 if (tstate->c_tracefunc != NULL) {
697 /* tstate->c_tracefunc, if defined, is a
698 function that will be called on *every* entry
699 to a code block. Its return value, if not
700 None, is a function that will be called at
701 the start of each executed line of code.
702 (Actually, the function must return itself
703 in order to continue tracing.) The trace
704 functions are called with three arguments:
705 a pointer to the current frame, a string
706 indicating why the function is called, and
707 an argument which depends on the situation.
708 The global trace function is also called
709 whenever an exception is detected. */
710 if (call_trace(tstate->c_tracefunc, tstate->c_traceobj,
711 f, PyTrace_CALL, Py_None)) {
712 /* Trace function raised an error */
713 --tstate->recursion_depth;
714 tstate->frame = f->f_back;
715 return NULL;
718 if (tstate->c_profilefunc != NULL) {
719 /* Similar for c_profilefunc, except it needn't
720 return itself and isn't called for "line" events */
721 if (call_trace(tstate->c_profilefunc,
722 tstate->c_profileobj,
723 f, PyTrace_CALL, Py_None)) {
724 /* Profile function raised an error */
725 --tstate->recursion_depth;
726 tstate->frame = f->f_back;
727 return NULL;
732 co = f->f_code;
733 names = co->co_names;
734 consts = co->co_consts;
735 fastlocals = f->f_localsplus;
736 freevars = f->f_localsplus + f->f_nlocals;
737 _PyCode_GETCODEPTR(co, &first_instr);
738 /* An explanation is in order for the next line.
740 f->f_lasti now refers to the index of the last instruction
741 executed. You might think this was obvious from the name, but
742 this wasn't always true before 2.3! PyFrame_New now sets
743 f->f_lasti to -1 (i.e. the index *before* the first instruction)
744 and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
745 does work. Promise. */
746 next_instr = first_instr + f->f_lasti + 1;
747 stack_pointer = f->f_stacktop;
748 assert(stack_pointer != NULL);
749 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
751 #ifdef LLTRACE
752 lltrace = PyDict_GetItemString(f->f_globals,"__lltrace__") != NULL;
753 #endif
754 #if defined(Py_DEBUG) || defined(LLTRACE)
755 filename = PyString_AsString(co->co_filename);
756 #endif
758 why = WHY_NOT;
759 err = 0;
760 x = Py_None; /* Not a reference, just anything non-NULL */
761 w = NULL;
763 for (;;) {
764 assert(stack_pointer >= f->f_valuestack); /* else underflow */
765 assert(STACK_LEVEL() <= f->f_stacksize); /* else overflow */
767 /* Do periodic things. Doing this every time through
768 the loop would add too much overhead, so we do it
769 only every Nth instruction. We also do it if
770 ``things_to_do'' is set, i.e. when an asynchronous
771 event needs attention (e.g. a signal handler or
772 async I/O handler); see Py_AddPendingCall() and
773 Py_MakePendingCalls() above. */
775 if (--_Py_Ticker < 0) {
776 _Py_Ticker = _Py_CheckInterval;
777 tstate->tick_counter++;
778 if (things_to_do) {
779 if (Py_MakePendingCalls() < 0) {
780 why = WHY_EXCEPTION;
781 goto on_error;
784 #if !defined(HAVE_SIGNAL_H) || defined(macintosh)
785 /* If we have true signals, the signal handler
786 will call Py_AddPendingCall() so we don't
787 have to call PyErr_CheckSignals(). On the
788 Mac and DOS, alas, we have to call it. */
789 if (PyErr_CheckSignals()) {
790 why = WHY_EXCEPTION;
791 goto on_error;
793 #endif
795 #ifdef WITH_THREAD
796 if (interpreter_lock) {
797 /* Give another thread a chance */
799 if (PyThreadState_Swap(NULL) != tstate)
800 Py_FatalError("ceval: tstate mix-up");
801 PyThread_release_lock(interpreter_lock);
803 /* Other threads may run now */
805 PyThread_acquire_lock(interpreter_lock, 1);
806 if (PyThreadState_Swap(tstate) != NULL)
807 Py_FatalError("ceval: orphan tstate");
809 #endif
812 fast_next_opcode:
813 f->f_lasti = INSTR_OFFSET();
815 /* line-by-line tracing support */
817 if (tstate->c_tracefunc != NULL && !tstate->tracing) {
818 /* see maybe_call_line_trace
819 for expository comments */
820 f->f_stacktop = stack_pointer;
822 err = maybe_call_line_trace(tstate->c_tracefunc,
823 tstate->c_traceobj,
824 f, &instr_lb, &instr_ub);
825 /* Reload possibly changed frame fields */
826 JUMPTO(f->f_lasti);
827 if (f->f_stacktop != NULL) {
828 stack_pointer = f->f_stacktop;
829 f->f_stacktop = NULL;
831 if (err) {
832 /* trace function raised an exception */
833 goto on_error;
837 /* Extract opcode and argument */
839 opcode = NEXTOP();
840 if (HAS_ARG(opcode))
841 oparg = NEXTARG();
842 dispatch_opcode:
843 #ifdef DYNAMIC_EXECUTION_PROFILE
844 #ifdef DXPAIRS
845 dxpairs[lastopcode][opcode]++;
846 lastopcode = opcode;
847 #endif
848 dxp[opcode]++;
849 #endif
851 #ifdef LLTRACE
852 /* Instruction tracing */
854 if (lltrace) {
855 if (HAS_ARG(opcode)) {
856 printf("%d: %d, %d\n",
857 f->f_lasti, opcode, oparg);
859 else {
860 printf("%d: %d\n",
861 f->f_lasti, opcode);
864 #endif
866 /* Main switch on opcode */
868 switch (opcode) {
870 /* BEWARE!
871 It is essential that any operation that fails sets either
872 x to NULL, err to nonzero, or why to anything but WHY_NOT,
873 and that no operation that succeeds does this! */
875 /* case STOP_CODE: this is an error! */
877 case LOAD_FAST:
878 x = GETLOCAL(oparg);
879 if (x != NULL) {
880 Py_INCREF(x);
881 PUSH(x);
882 goto fast_next_opcode;
884 format_exc_check_arg(PyExc_UnboundLocalError,
885 UNBOUNDLOCAL_ERROR_MSG,
886 PyTuple_GetItem(co->co_varnames, oparg));
887 break;
889 case LOAD_CONST:
890 x = GETITEM(consts, oparg);
891 Py_INCREF(x);
892 PUSH(x);
893 goto fast_next_opcode;
895 PREDICTED_WITH_ARG(STORE_FAST);
896 case STORE_FAST:
897 v = POP();
898 SETLOCAL(oparg, v);
899 goto fast_next_opcode;
901 PREDICTED(POP_TOP);
902 case POP_TOP:
903 v = POP();
904 Py_DECREF(v);
905 goto fast_next_opcode;
907 case ROT_TWO:
908 v = TOP();
909 w = SECOND();
910 SET_TOP(w);
911 SET_SECOND(v);
912 goto fast_next_opcode;
914 case ROT_THREE:
915 v = TOP();
916 w = SECOND();
917 x = THIRD();
918 SET_TOP(w);
919 SET_SECOND(x);
920 SET_THIRD(v);
921 goto fast_next_opcode;
923 case ROT_FOUR:
924 u = TOP();
925 v = SECOND();
926 w = THIRD();
927 x = FOURTH();
928 SET_TOP(v);
929 SET_SECOND(w);
930 SET_THIRD(x);
931 SET_FOURTH(u);
932 goto fast_next_opcode;
934 case DUP_TOP:
935 v = TOP();
936 Py_INCREF(v);
937 PUSH(v);
938 goto fast_next_opcode;
940 case DUP_TOPX:
941 if (oparg == 2) {
942 x = TOP();
943 Py_INCREF(x);
944 w = SECOND();
945 Py_INCREF(w);
946 STACKADJ(2);
947 SET_TOP(x);
948 SET_SECOND(w);
949 goto fast_next_opcode;
950 } else if (oparg == 3) {
951 x = TOP();
952 Py_INCREF(x);
953 w = SECOND();
954 Py_INCREF(w);
955 v = THIRD();
956 Py_INCREF(v);
957 STACKADJ(3);
958 SET_TOP(x);
959 SET_SECOND(w);
960 SET_THIRD(v);
961 goto fast_next_opcode;
963 Py_FatalError("invalid argument to DUP_TOPX"
964 " (bytecode corruption?)");
965 break;
967 case UNARY_POSITIVE:
968 v = TOP();
969 x = PyNumber_Positive(v);
970 Py_DECREF(v);
971 SET_TOP(x);
972 if (x != NULL) continue;
973 break;
975 case UNARY_NEGATIVE:
976 v = TOP();
977 x = PyNumber_Negative(v);
978 Py_DECREF(v);
979 SET_TOP(x);
980 if (x != NULL) continue;
981 break;
983 case UNARY_NOT:
984 v = TOP();
985 err = PyObject_IsTrue(v);
986 Py_DECREF(v);
987 if (err == 0) {
988 Py_INCREF(Py_True);
989 SET_TOP(Py_True);
990 continue;
992 else if (err > 0) {
993 Py_INCREF(Py_False);
994 SET_TOP(Py_False);
995 err = 0;
996 continue;
998 STACKADJ(-1);
999 break;
1001 case UNARY_CONVERT:
1002 v = TOP();
1003 x = PyObject_Repr(v);
1004 Py_DECREF(v);
1005 SET_TOP(x);
1006 if (x != NULL) continue;
1007 break;
1009 case UNARY_INVERT:
1010 v = TOP();
1011 x = PyNumber_Invert(v);
1012 Py_DECREF(v);
1013 SET_TOP(x);
1014 if (x != NULL) continue;
1015 break;
1017 case BINARY_POWER:
1018 w = POP();
1019 v = TOP();
1020 x = PyNumber_Power(v, w, Py_None);
1021 Py_DECREF(v);
1022 Py_DECREF(w);
1023 SET_TOP(x);
1024 if (x != NULL) continue;
1025 break;
1027 case BINARY_MULTIPLY:
1028 w = POP();
1029 v = TOP();
1030 x = PyNumber_Multiply(v, w);
1031 Py_DECREF(v);
1032 Py_DECREF(w);
1033 SET_TOP(x);
1034 if (x != NULL) continue;
1035 break;
1037 case BINARY_DIVIDE:
1038 if (!_Py_QnewFlag) {
1039 w = POP();
1040 v = TOP();
1041 x = PyNumber_Divide(v, w);
1042 Py_DECREF(v);
1043 Py_DECREF(w);
1044 SET_TOP(x);
1045 if (x != NULL) continue;
1046 break;
1048 /* -Qnew is in effect: fall through to
1049 BINARY_TRUE_DIVIDE */
1050 case BINARY_TRUE_DIVIDE:
1051 w = POP();
1052 v = TOP();
1053 x = PyNumber_TrueDivide(v, w);
1054 Py_DECREF(v);
1055 Py_DECREF(w);
1056 SET_TOP(x);
1057 if (x != NULL) continue;
1058 break;
1060 case BINARY_FLOOR_DIVIDE:
1061 w = POP();
1062 v = TOP();
1063 x = PyNumber_FloorDivide(v, w);
1064 Py_DECREF(v);
1065 Py_DECREF(w);
1066 SET_TOP(x);
1067 if (x != NULL) continue;
1068 break;
1070 case BINARY_MODULO:
1071 w = POP();
1072 v = TOP();
1073 x = PyNumber_Remainder(v, w);
1074 Py_DECREF(v);
1075 Py_DECREF(w);
1076 SET_TOP(x);
1077 if (x != NULL) continue;
1078 break;
1080 case BINARY_ADD:
1081 w = POP();
1082 v = TOP();
1083 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1084 /* INLINE: int + int */
1085 register long a, b, i;
1086 a = PyInt_AS_LONG(v);
1087 b = PyInt_AS_LONG(w);
1088 i = a + b;
1089 if ((i^a) < 0 && (i^b) < 0)
1090 goto slow_add;
1091 x = PyInt_FromLong(i);
1093 else {
1094 slow_add:
1095 x = PyNumber_Add(v, w);
1097 Py_DECREF(v);
1098 Py_DECREF(w);
1099 SET_TOP(x);
1100 if (x != NULL) continue;
1101 break;
1103 case BINARY_SUBTRACT:
1104 w = POP();
1105 v = TOP();
1106 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1107 /* INLINE: int - int */
1108 register long a, b, i;
1109 a = PyInt_AS_LONG(v);
1110 b = PyInt_AS_LONG(w);
1111 i = a - b;
1112 if ((i^a) < 0 && (i^~b) < 0)
1113 goto slow_sub;
1114 x = PyInt_FromLong(i);
1116 else {
1117 slow_sub:
1118 x = PyNumber_Subtract(v, w);
1120 Py_DECREF(v);
1121 Py_DECREF(w);
1122 SET_TOP(x);
1123 if (x != NULL) continue;
1124 break;
1126 case BINARY_SUBSCR:
1127 w = POP();
1128 v = TOP();
1129 if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
1130 /* INLINE: list[int] */
1131 long i = PyInt_AsLong(w);
1132 if (i < 0)
1133 i += PyList_GET_SIZE(v);
1134 if (i < 0 ||
1135 i >= PyList_GET_SIZE(v)) {
1136 PyErr_SetString(PyExc_IndexError,
1137 "list index out of range");
1138 x = NULL;
1140 else {
1141 x = PyList_GET_ITEM(v, i);
1142 Py_INCREF(x);
1145 else
1146 x = PyObject_GetItem(v, w);
1147 Py_DECREF(v);
1148 Py_DECREF(w);
1149 SET_TOP(x);
1150 if (x != NULL) continue;
1151 break;
1153 case BINARY_LSHIFT:
1154 w = POP();
1155 v = TOP();
1156 x = PyNumber_Lshift(v, w);
1157 Py_DECREF(v);
1158 Py_DECREF(w);
1159 SET_TOP(x);
1160 if (x != NULL) continue;
1161 break;
1163 case BINARY_RSHIFT:
1164 w = POP();
1165 v = TOP();
1166 x = PyNumber_Rshift(v, w);
1167 Py_DECREF(v);
1168 Py_DECREF(w);
1169 SET_TOP(x);
1170 if (x != NULL) continue;
1171 break;
1173 case BINARY_AND:
1174 w = POP();
1175 v = TOP();
1176 x = PyNumber_And(v, w);
1177 Py_DECREF(v);
1178 Py_DECREF(w);
1179 SET_TOP(x);
1180 if (x != NULL) continue;
1181 break;
1183 case BINARY_XOR:
1184 w = POP();
1185 v = TOP();
1186 x = PyNumber_Xor(v, w);
1187 Py_DECREF(v);
1188 Py_DECREF(w);
1189 SET_TOP(x);
1190 if (x != NULL) continue;
1191 break;
1193 case BINARY_OR:
1194 w = POP();
1195 v = TOP();
1196 x = PyNumber_Or(v, w);
1197 Py_DECREF(v);
1198 Py_DECREF(w);
1199 SET_TOP(x);
1200 if (x != NULL) continue;
1201 break;
1203 case INPLACE_POWER:
1204 w = POP();
1205 v = TOP();
1206 x = PyNumber_InPlacePower(v, w, Py_None);
1207 Py_DECREF(v);
1208 Py_DECREF(w);
1209 SET_TOP(x);
1210 if (x != NULL) continue;
1211 break;
1213 case INPLACE_MULTIPLY:
1214 w = POP();
1215 v = TOP();
1216 x = PyNumber_InPlaceMultiply(v, w);
1217 Py_DECREF(v);
1218 Py_DECREF(w);
1219 SET_TOP(x);
1220 if (x != NULL) continue;
1221 break;
1223 case INPLACE_DIVIDE:
1224 if (!_Py_QnewFlag) {
1225 w = POP();
1226 v = TOP();
1227 x = PyNumber_InPlaceDivide(v, w);
1228 Py_DECREF(v);
1229 Py_DECREF(w);
1230 SET_TOP(x);
1231 if (x != NULL) continue;
1232 break;
1234 /* -Qnew is in effect: fall through to
1235 INPLACE_TRUE_DIVIDE */
1236 case INPLACE_TRUE_DIVIDE:
1237 w = POP();
1238 v = TOP();
1239 x = PyNumber_InPlaceTrueDivide(v, w);
1240 Py_DECREF(v);
1241 Py_DECREF(w);
1242 SET_TOP(x);
1243 if (x != NULL) continue;
1244 break;
1246 case INPLACE_FLOOR_DIVIDE:
1247 w = POP();
1248 v = TOP();
1249 x = PyNumber_InPlaceFloorDivide(v, w);
1250 Py_DECREF(v);
1251 Py_DECREF(w);
1252 SET_TOP(x);
1253 if (x != NULL) continue;
1254 break;
1256 case INPLACE_MODULO:
1257 w = POP();
1258 v = TOP();
1259 x = PyNumber_InPlaceRemainder(v, w);
1260 Py_DECREF(v);
1261 Py_DECREF(w);
1262 SET_TOP(x);
1263 if (x != NULL) continue;
1264 break;
1266 case INPLACE_ADD:
1267 w = POP();
1268 v = TOP();
1269 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1270 /* INLINE: int + int */
1271 register long a, b, i;
1272 a = PyInt_AS_LONG(v);
1273 b = PyInt_AS_LONG(w);
1274 i = a + b;
1275 if ((i^a) < 0 && (i^b) < 0)
1276 goto slow_iadd;
1277 x = PyInt_FromLong(i);
1279 else {
1280 slow_iadd:
1281 x = PyNumber_InPlaceAdd(v, w);
1283 Py_DECREF(v);
1284 Py_DECREF(w);
1285 SET_TOP(x);
1286 if (x != NULL) continue;
1287 break;
1289 case INPLACE_SUBTRACT:
1290 w = POP();
1291 v = TOP();
1292 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1293 /* INLINE: int - int */
1294 register long a, b, i;
1295 a = PyInt_AS_LONG(v);
1296 b = PyInt_AS_LONG(w);
1297 i = a - b;
1298 if ((i^a) < 0 && (i^~b) < 0)
1299 goto slow_isub;
1300 x = PyInt_FromLong(i);
1302 else {
1303 slow_isub:
1304 x = PyNumber_InPlaceSubtract(v, w);
1306 Py_DECREF(v);
1307 Py_DECREF(w);
1308 SET_TOP(x);
1309 if (x != NULL) continue;
1310 break;
1312 case INPLACE_LSHIFT:
1313 w = POP();
1314 v = TOP();
1315 x = PyNumber_InPlaceLshift(v, w);
1316 Py_DECREF(v);
1317 Py_DECREF(w);
1318 SET_TOP(x);
1319 if (x != NULL) continue;
1320 break;
1322 case INPLACE_RSHIFT:
1323 w = POP();
1324 v = TOP();
1325 x = PyNumber_InPlaceRshift(v, w);
1326 Py_DECREF(v);
1327 Py_DECREF(w);
1328 SET_TOP(x);
1329 if (x != NULL) continue;
1330 break;
1332 case INPLACE_AND:
1333 w = POP();
1334 v = TOP();
1335 x = PyNumber_InPlaceAnd(v, w);
1336 Py_DECREF(v);
1337 Py_DECREF(w);
1338 SET_TOP(x);
1339 if (x != NULL) continue;
1340 break;
1342 case INPLACE_XOR:
1343 w = POP();
1344 v = TOP();
1345 x = PyNumber_InPlaceXor(v, w);
1346 Py_DECREF(v);
1347 Py_DECREF(w);
1348 SET_TOP(x);
1349 if (x != NULL) continue;
1350 break;
1352 case INPLACE_OR:
1353 w = POP();
1354 v = TOP();
1355 x = PyNumber_InPlaceOr(v, w);
1356 Py_DECREF(v);
1357 Py_DECREF(w);
1358 SET_TOP(x);
1359 if (x != NULL) continue;
1360 break;
1362 case SLICE+0:
1363 case SLICE+1:
1364 case SLICE+2:
1365 case SLICE+3:
1366 if ((opcode-SLICE) & 2)
1367 w = POP();
1368 else
1369 w = NULL;
1370 if ((opcode-SLICE) & 1)
1371 v = POP();
1372 else
1373 v = NULL;
1374 u = TOP();
1375 x = apply_slice(u, v, w);
1376 Py_DECREF(u);
1377 Py_XDECREF(v);
1378 Py_XDECREF(w);
1379 SET_TOP(x);
1380 if (x != NULL) continue;
1381 break;
1383 case STORE_SLICE+0:
1384 case STORE_SLICE+1:
1385 case STORE_SLICE+2:
1386 case STORE_SLICE+3:
1387 if ((opcode-STORE_SLICE) & 2)
1388 w = POP();
1389 else
1390 w = NULL;
1391 if ((opcode-STORE_SLICE) & 1)
1392 v = POP();
1393 else
1394 v = NULL;
1395 u = POP();
1396 t = POP();
1397 err = assign_slice(u, v, w, t); /* u[v:w] = t */
1398 Py_DECREF(t);
1399 Py_DECREF(u);
1400 Py_XDECREF(v);
1401 Py_XDECREF(w);
1402 if (err == 0) continue;
1403 break;
1405 case DELETE_SLICE+0:
1406 case DELETE_SLICE+1:
1407 case DELETE_SLICE+2:
1408 case DELETE_SLICE+3:
1409 if ((opcode-DELETE_SLICE) & 2)
1410 w = POP();
1411 else
1412 w = NULL;
1413 if ((opcode-DELETE_SLICE) & 1)
1414 v = POP();
1415 else
1416 v = NULL;
1417 u = POP();
1418 err = assign_slice(u, v, w, (PyObject *)NULL);
1419 /* del u[v:w] */
1420 Py_DECREF(u);
1421 Py_XDECREF(v);
1422 Py_XDECREF(w);
1423 if (err == 0) continue;
1424 break;
1426 case STORE_SUBSCR:
1427 w = TOP();
1428 v = SECOND();
1429 u = THIRD();
1430 STACKADJ(-3);
1431 /* v[w] = u */
1432 err = PyObject_SetItem(v, w, u);
1433 Py_DECREF(u);
1434 Py_DECREF(v);
1435 Py_DECREF(w);
1436 if (err == 0) continue;
1437 break;
1439 case DELETE_SUBSCR:
1440 w = TOP();
1441 v = SECOND();
1442 STACKADJ(-2);
1443 /* del v[w] */
1444 err = PyObject_DelItem(v, w);
1445 Py_DECREF(v);
1446 Py_DECREF(w);
1447 if (err == 0) continue;
1448 break;
1450 case PRINT_EXPR:
1451 v = POP();
1452 w = PySys_GetObject("displayhook");
1453 if (w == NULL) {
1454 PyErr_SetString(PyExc_RuntimeError,
1455 "lost sys.displayhook");
1456 err = -1;
1457 x = NULL;
1459 if (err == 0) {
1460 x = Py_BuildValue("(O)", v);
1461 if (x == NULL)
1462 err = -1;
1464 if (err == 0) {
1465 w = PyEval_CallObject(w, x);
1466 Py_XDECREF(w);
1467 if (w == NULL)
1468 err = -1;
1470 Py_DECREF(v);
1471 Py_XDECREF(x);
1472 break;
1474 case PRINT_ITEM_TO:
1475 w = stream = POP();
1476 /* fall through to PRINT_ITEM */
1478 case PRINT_ITEM:
1479 v = POP();
1480 if (stream == NULL || stream == Py_None) {
1481 w = PySys_GetObject("stdout");
1482 if (w == NULL) {
1483 PyErr_SetString(PyExc_RuntimeError,
1484 "lost sys.stdout");
1485 err = -1;
1488 if (w != NULL && PyFile_SoftSpace(w, 0))
1489 err = PyFile_WriteString(" ", w);
1490 if (err == 0)
1491 err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
1492 if (err == 0) {
1493 /* XXX move into writeobject() ? */
1494 if (PyString_Check(v)) {
1495 char *s = PyString_AS_STRING(v);
1496 int len = PyString_GET_SIZE(v);
1497 if (len == 0 ||
1498 !isspace(Py_CHARMASK(s[len-1])) ||
1499 s[len-1] == ' ')
1500 PyFile_SoftSpace(w, 1);
1502 #ifdef Py_USING_UNICODE
1503 else if (PyUnicode_Check(v)) {
1504 Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
1505 int len = PyUnicode_GET_SIZE(v);
1506 if (len == 0 ||
1507 !Py_UNICODE_ISSPACE(s[len-1]) ||
1508 s[len-1] == ' ')
1509 PyFile_SoftSpace(w, 1);
1511 #endif
1512 else
1513 PyFile_SoftSpace(w, 1);
1515 Py_DECREF(v);
1516 Py_XDECREF(stream);
1517 stream = NULL;
1518 if (err == 0)
1519 continue;
1520 break;
1522 case PRINT_NEWLINE_TO:
1523 w = stream = POP();
1524 /* fall through to PRINT_NEWLINE */
1526 case PRINT_NEWLINE:
1527 if (stream == NULL || stream == Py_None) {
1528 w = PySys_GetObject("stdout");
1529 if (w == NULL)
1530 PyErr_SetString(PyExc_RuntimeError,
1531 "lost sys.stdout");
1533 if (w != NULL) {
1534 err = PyFile_WriteString("\n", w);
1535 if (err == 0)
1536 PyFile_SoftSpace(w, 0);
1538 Py_XDECREF(stream);
1539 stream = NULL;
1540 break;
1543 #ifdef CASE_TOO_BIG
1544 default: switch (opcode) {
1545 #endif
1546 case BREAK_LOOP:
1547 why = WHY_BREAK;
1548 break;
1550 case CONTINUE_LOOP:
1551 retval = PyInt_FromLong(oparg);
1552 why = WHY_CONTINUE;
1553 break;
1555 case RAISE_VARARGS:
1556 u = v = w = NULL;
1557 switch (oparg) {
1558 case 3:
1559 u = POP(); /* traceback */
1560 /* Fallthrough */
1561 case 2:
1562 v = POP(); /* value */
1563 /* Fallthrough */
1564 case 1:
1565 w = POP(); /* exc */
1566 case 0: /* Fallthrough */
1567 why = do_raise(w, v, u);
1568 break;
1569 default:
1570 PyErr_SetString(PyExc_SystemError,
1571 "bad RAISE_VARARGS oparg");
1572 why = WHY_EXCEPTION;
1573 break;
1575 break;
1577 case LOAD_LOCALS:
1578 if ((x = f->f_locals) == NULL) {
1579 PyErr_SetString(PyExc_SystemError,
1580 "no locals");
1581 break;
1583 Py_INCREF(x);
1584 PUSH(x);
1585 break;
1587 case RETURN_VALUE:
1588 retval = POP();
1589 why = WHY_RETURN;
1590 break;
1592 case YIELD_VALUE:
1593 retval = POP();
1594 f->f_stacktop = stack_pointer;
1595 why = WHY_YIELD;
1596 break;
1599 case EXEC_STMT:
1600 w = TOP();
1601 v = SECOND();
1602 u = THIRD();
1603 STACKADJ(-3);
1604 err = exec_statement(f, u, v, w);
1605 Py_DECREF(u);
1606 Py_DECREF(v);
1607 Py_DECREF(w);
1608 break;
1610 case POP_BLOCK:
1612 PyTryBlock *b = PyFrame_BlockPop(f);
1613 while (STACK_LEVEL() > b->b_level) {
1614 v = POP();
1615 Py_DECREF(v);
1618 break;
1620 case END_FINALLY:
1621 v = POP();
1622 if (PyInt_Check(v)) {
1623 why = (enum why_code) PyInt_AS_LONG(v);
1624 if (why == WHY_RETURN ||
1625 why == WHY_YIELD ||
1626 why == WHY_CONTINUE)
1627 retval = POP();
1629 else if (PyString_Check(v) || PyClass_Check(v)) {
1630 w = POP();
1631 u = POP();
1632 PyErr_Restore(v, w, u);
1633 why = WHY_RERAISE;
1634 break;
1636 else if (v != Py_None) {
1637 PyErr_SetString(PyExc_SystemError,
1638 "'finally' pops bad exception");
1639 why = WHY_EXCEPTION;
1641 Py_DECREF(v);
1642 break;
1644 case BUILD_CLASS:
1645 u = TOP();
1646 v = SECOND();
1647 w = THIRD();
1648 STACKADJ(-2);
1649 x = build_class(u, v, w);
1650 SET_TOP(x);
1651 Py_DECREF(u);
1652 Py_DECREF(v);
1653 Py_DECREF(w);
1654 break;
1656 case STORE_NAME:
1657 w = GETITEM(names, oparg);
1658 v = POP();
1659 if ((x = f->f_locals) == NULL) {
1660 PyErr_Format(PyExc_SystemError,
1661 "no locals found when storing %s",
1662 PyObject_REPR(w));
1663 break;
1665 err = PyDict_SetItem(x, w, v);
1666 Py_DECREF(v);
1667 break;
1669 case DELETE_NAME:
1670 w = GETITEM(names, oparg);
1671 if ((x = f->f_locals) == NULL) {
1672 PyErr_Format(PyExc_SystemError,
1673 "no locals when deleting %s",
1674 PyObject_REPR(w));
1675 break;
1677 if ((err = PyDict_DelItem(x, w)) != 0)
1678 format_exc_check_arg(PyExc_NameError,
1679 NAME_ERROR_MSG ,w);
1680 break;
1682 PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
1683 case UNPACK_SEQUENCE:
1684 v = POP();
1685 if (PyTuple_CheckExact(v)) {
1686 if (PyTuple_Size(v) != oparg) {
1687 PyErr_SetString(PyExc_ValueError,
1688 "unpack tuple of wrong size");
1689 why = WHY_EXCEPTION;
1691 else {
1692 for (; --oparg >= 0; ) {
1693 w = PyTuple_GET_ITEM(v, oparg);
1694 Py_INCREF(w);
1695 PUSH(w);
1699 else if (PyList_CheckExact(v)) {
1700 if (PyList_Size(v) != oparg) {
1701 PyErr_SetString(PyExc_ValueError,
1702 "unpack list of wrong size");
1703 why = WHY_EXCEPTION;
1705 else {
1706 for (; --oparg >= 0; ) {
1707 w = PyList_GET_ITEM(v, oparg);
1708 Py_INCREF(w);
1709 PUSH(w);
1713 else if (unpack_iterable(v, oparg,
1714 stack_pointer + oparg))
1715 stack_pointer += oparg;
1716 else {
1717 if (PyErr_ExceptionMatches(PyExc_TypeError))
1718 PyErr_SetString(PyExc_TypeError,
1719 "unpack non-sequence");
1720 why = WHY_EXCEPTION;
1722 Py_DECREF(v);
1723 break;
1725 case STORE_ATTR:
1726 w = GETITEM(names, oparg);
1727 v = TOP();
1728 u = SECOND();
1729 STACKADJ(-2);
1730 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1731 Py_DECREF(v);
1732 Py_DECREF(u);
1733 break;
1735 case DELETE_ATTR:
1736 w = GETITEM(names, oparg);
1737 v = POP();
1738 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
1739 /* del v.w */
1740 Py_DECREF(v);
1741 break;
1743 case STORE_GLOBAL:
1744 w = GETITEM(names, oparg);
1745 v = POP();
1746 err = PyDict_SetItem(f->f_globals, w, v);
1747 Py_DECREF(v);
1748 break;
1750 case DELETE_GLOBAL:
1751 w = GETITEM(names, oparg);
1752 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
1753 format_exc_check_arg(
1754 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
1755 break;
1757 case LOAD_NAME:
1758 w = GETITEM(names, oparg);
1759 if ((x = f->f_locals) == NULL) {
1760 PyErr_Format(PyExc_SystemError,
1761 "no locals when loading %s",
1762 PyObject_REPR(w));
1763 break;
1765 x = PyDict_GetItem(x, w);
1766 if (x == NULL) {
1767 x = PyDict_GetItem(f->f_globals, w);
1768 if (x == NULL) {
1769 x = PyDict_GetItem(f->f_builtins, w);
1770 if (x == NULL) {
1771 format_exc_check_arg(
1772 PyExc_NameError,
1773 NAME_ERROR_MSG ,w);
1774 break;
1778 Py_INCREF(x);
1779 PUSH(x);
1780 break;
1782 case LOAD_GLOBAL:
1783 w = GETITEM(names, oparg);
1784 if (PyString_CheckExact(w)) {
1785 /* Inline the PyDict_GetItem() calls.
1786 WARNING: this is an extreme speed hack.
1787 Do not try this at home. */
1788 long hash = ((PyStringObject *)w)->ob_shash;
1789 if (hash != -1) {
1790 PyDictObject *d;
1791 d = (PyDictObject *)(f->f_globals);
1792 x = d->ma_lookup(d, w, hash)->me_value;
1793 if (x != NULL) {
1794 Py_INCREF(x);
1795 PUSH(x);
1796 continue;
1798 d = (PyDictObject *)(f->f_builtins);
1799 x = d->ma_lookup(d, w, hash)->me_value;
1800 if (x != NULL) {
1801 Py_INCREF(x);
1802 PUSH(x);
1803 continue;
1805 goto load_global_error;
1808 /* This is the un-inlined version of the code above */
1809 x = PyDict_GetItem(f->f_globals, w);
1810 if (x == NULL) {
1811 x = PyDict_GetItem(f->f_builtins, w);
1812 if (x == NULL) {
1813 load_global_error:
1814 format_exc_check_arg(
1815 PyExc_NameError,
1816 GLOBAL_NAME_ERROR_MSG, w);
1817 break;
1820 Py_INCREF(x);
1821 PUSH(x);
1822 break;
1824 case DELETE_FAST:
1825 x = GETLOCAL(oparg);
1826 if (x == NULL) {
1827 format_exc_check_arg(
1828 PyExc_UnboundLocalError,
1829 UNBOUNDLOCAL_ERROR_MSG,
1830 PyTuple_GetItem(co->co_varnames, oparg)
1832 break;
1834 SETLOCAL(oparg, NULL);
1835 continue;
1837 case LOAD_CLOSURE:
1838 x = freevars[oparg];
1839 Py_INCREF(x);
1840 PUSH(x);
1841 break;
1843 case LOAD_DEREF:
1844 x = freevars[oparg];
1845 w = PyCell_Get(x);
1846 if (w == NULL) {
1847 err = -1;
1848 /* Don't stomp existing exception */
1849 if (PyErr_Occurred())
1850 break;
1851 if (oparg < f->f_ncells) {
1852 v = PyTuple_GetItem(co->co_cellvars,
1853 oparg);
1854 format_exc_check_arg(
1855 PyExc_UnboundLocalError,
1856 UNBOUNDLOCAL_ERROR_MSG,
1858 } else {
1859 v = PyTuple_GetItem(
1860 co->co_freevars,
1861 oparg - f->f_ncells);
1862 format_exc_check_arg(
1863 PyExc_NameError,
1864 UNBOUNDFREE_ERROR_MSG,
1867 break;
1869 PUSH(w);
1870 break;
1872 case STORE_DEREF:
1873 w = POP();
1874 x = freevars[oparg];
1875 PyCell_Set(x, w);
1876 Py_DECREF(w);
1877 continue;
1879 case BUILD_TUPLE:
1880 x = PyTuple_New(oparg);
1881 if (x != NULL) {
1882 for (; --oparg >= 0;) {
1883 w = POP();
1884 PyTuple_SET_ITEM(x, oparg, w);
1886 PUSH(x);
1887 continue;
1889 break;
1891 case BUILD_LIST:
1892 x = PyList_New(oparg);
1893 if (x != NULL) {
1894 for (; --oparg >= 0;) {
1895 w = POP();
1896 PyList_SET_ITEM(x, oparg, w);
1898 PUSH(x);
1899 continue;
1901 break;
1903 case BUILD_MAP:
1904 x = PyDict_New();
1905 PUSH(x);
1906 if (x != NULL) continue;
1907 break;
1909 case LOAD_ATTR:
1910 w = GETITEM(names, oparg);
1911 v = TOP();
1912 x = PyObject_GetAttr(v, w);
1913 Py_DECREF(v);
1914 SET_TOP(x);
1915 if (x != NULL) continue;
1916 break;
1918 case COMPARE_OP:
1919 w = POP();
1920 v = TOP();
1921 if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) {
1922 /* INLINE: cmp(int, int) */
1923 register long a, b;
1924 register int res;
1925 a = PyInt_AS_LONG(v);
1926 b = PyInt_AS_LONG(w);
1927 switch (oparg) {
1928 case PyCmp_LT: res = a < b; break;
1929 case PyCmp_LE: res = a <= b; break;
1930 case PyCmp_EQ: res = a == b; break;
1931 case PyCmp_NE: res = a != b; break;
1932 case PyCmp_GT: res = a > b; break;
1933 case PyCmp_GE: res = a >= b; break;
1934 case PyCmp_IS: res = v == w; break;
1935 case PyCmp_IS_NOT: res = v != w; break;
1936 default: goto slow_compare;
1938 x = res ? Py_True : Py_False;
1939 Py_INCREF(x);
1941 else {
1942 slow_compare:
1943 x = cmp_outcome(oparg, v, w);
1945 Py_DECREF(v);
1946 Py_DECREF(w);
1947 SET_TOP(x);
1948 if (x == NULL) break;
1949 PREDICT(JUMP_IF_FALSE);
1950 PREDICT(JUMP_IF_TRUE);
1951 continue;
1953 case IMPORT_NAME:
1954 w = GETITEM(names, oparg);
1955 x = PyDict_GetItemString(f->f_builtins, "__import__");
1956 if (x == NULL) {
1957 PyErr_SetString(PyExc_ImportError,
1958 "__import__ not found");
1959 break;
1961 u = TOP();
1962 w = Py_BuildValue("(OOOO)",
1964 f->f_globals,
1965 f->f_locals == NULL ?
1966 Py_None : f->f_locals,
1968 Py_DECREF(u);
1969 if (w == NULL) {
1970 u = POP();
1971 x = NULL;
1972 break;
1974 x = PyEval_CallObject(x, w);
1975 Py_DECREF(w);
1976 SET_TOP(x);
1977 if (x != NULL) continue;
1978 break;
1980 case IMPORT_STAR:
1981 v = POP();
1982 PyFrame_FastToLocals(f);
1983 if ((x = f->f_locals) == NULL) {
1984 PyErr_SetString(PyExc_SystemError,
1985 "no locals found during 'import *'");
1986 break;
1988 err = import_all_from(x, v);
1989 PyFrame_LocalsToFast(f, 0);
1990 Py_DECREF(v);
1991 if (err == 0) continue;
1992 break;
1994 case IMPORT_FROM:
1995 w = GETITEM(names, oparg);
1996 v = TOP();
1997 x = import_from(v, w);
1998 PUSH(x);
1999 if (x != NULL) continue;
2000 break;
2002 case JUMP_FORWARD:
2003 JUMPBY(oparg);
2004 goto fast_next_opcode;
2006 PREDICTED_WITH_ARG(JUMP_IF_FALSE);
2007 case JUMP_IF_FALSE:
2008 w = TOP();
2009 if (w == Py_True) {
2010 PREDICT(POP_TOP);
2011 goto fast_next_opcode;
2013 if (w == Py_False) {
2014 JUMPBY(oparg);
2015 goto fast_next_opcode;
2017 err = PyObject_IsTrue(w);
2018 if (err > 0)
2019 err = 0;
2020 else if (err == 0)
2021 JUMPBY(oparg);
2022 else
2023 break;
2024 continue;
2026 PREDICTED_WITH_ARG(JUMP_IF_TRUE);
2027 case JUMP_IF_TRUE:
2028 w = TOP();
2029 if (w == Py_False) {
2030 PREDICT(POP_TOP);
2031 goto fast_next_opcode;
2033 if (w == Py_True) {
2034 JUMPBY(oparg);
2035 goto fast_next_opcode;
2037 err = PyObject_IsTrue(w);
2038 if (err > 0) {
2039 err = 0;
2040 JUMPBY(oparg);
2042 else if (err == 0)
2044 else
2045 break;
2046 continue;
2048 case JUMP_ABSOLUTE:
2049 JUMPTO(oparg);
2050 goto fast_next_opcode;
2052 case GET_ITER:
2053 /* before: [obj]; after [getiter(obj)] */
2054 v = TOP();
2055 x = PyObject_GetIter(v);
2056 Py_DECREF(v);
2057 if (x != NULL) {
2058 SET_TOP(x);
2059 PREDICT(FOR_ITER);
2060 continue;
2062 STACKADJ(-1);
2063 break;
2065 PREDICTED_WITH_ARG(FOR_ITER);
2066 case FOR_ITER:
2067 /* before: [iter]; after: [iter, iter()] *or* [] */
2068 v = TOP();
2069 x = PyIter_Next(v);
2070 if (x != NULL) {
2071 PUSH(x);
2072 PREDICT(STORE_FAST);
2073 PREDICT(UNPACK_SEQUENCE);
2074 continue;
2076 if (!PyErr_Occurred()) {
2077 /* iterator ended normally */
2078 x = v = POP();
2079 Py_DECREF(v);
2080 JUMPBY(oparg);
2081 continue;
2083 break;
2085 case SETUP_LOOP:
2086 case SETUP_EXCEPT:
2087 case SETUP_FINALLY:
2088 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
2089 STACK_LEVEL());
2090 continue;
2092 case CALL_FUNCTION:
2093 PCALL(PCALL_ALL);
2094 x = call_function(&stack_pointer, oparg);
2095 PUSH(x);
2096 if (x != NULL)
2097 continue;
2098 break;
2100 case CALL_FUNCTION_VAR:
2101 case CALL_FUNCTION_KW:
2102 case CALL_FUNCTION_VAR_KW:
2104 int na = oparg & 0xff;
2105 int nk = (oparg>>8) & 0xff;
2106 int flags = (opcode - CALL_FUNCTION) & 3;
2107 int n = na + 2 * nk;
2108 PyObject **pfunc, *func;
2109 PCALL(PCALL_ALL);
2110 if (flags & CALL_FLAG_VAR)
2111 n++;
2112 if (flags & CALL_FLAG_KW)
2113 n++;
2114 pfunc = stack_pointer - n - 1;
2115 func = *pfunc;
2117 if (PyMethod_Check(func)
2118 && PyMethod_GET_SELF(func) != NULL) {
2119 PyObject *self = PyMethod_GET_SELF(func);
2120 Py_INCREF(self);
2121 func = PyMethod_GET_FUNCTION(func);
2122 Py_INCREF(func);
2123 Py_DECREF(*pfunc);
2124 *pfunc = self;
2125 na++;
2126 n++;
2127 } else
2128 Py_INCREF(func);
2129 x = ext_do_call(func, &stack_pointer, flags, na, nk);
2130 Py_DECREF(func);
2132 while (stack_pointer > pfunc) {
2133 w = POP();
2134 Py_DECREF(w);
2136 PUSH(x);
2137 if (x != NULL)
2138 continue;
2139 break;
2142 case MAKE_FUNCTION:
2143 v = POP(); /* code object */
2144 x = PyFunction_New(v, f->f_globals);
2145 Py_DECREF(v);
2146 /* XXX Maybe this should be a separate opcode? */
2147 if (x != NULL && oparg > 0) {
2148 v = PyTuple_New(oparg);
2149 if (v == NULL) {
2150 Py_DECREF(x);
2151 x = NULL;
2152 break;
2154 while (--oparg >= 0) {
2155 w = POP();
2156 PyTuple_SET_ITEM(v, oparg, w);
2158 err = PyFunction_SetDefaults(x, v);
2159 Py_DECREF(v);
2161 PUSH(x);
2162 break;
2164 case MAKE_CLOSURE:
2166 int nfree;
2167 v = POP(); /* code object */
2168 x = PyFunction_New(v, f->f_globals);
2169 nfree = PyCode_GetNumFree((PyCodeObject *)v);
2170 Py_DECREF(v);
2171 /* XXX Maybe this should be a separate opcode? */
2172 if (x != NULL && nfree > 0) {
2173 v = PyTuple_New(nfree);
2174 if (v == NULL) {
2175 Py_DECREF(x);
2176 x = NULL;
2177 break;
2179 while (--nfree >= 0) {
2180 w = POP();
2181 PyTuple_SET_ITEM(v, nfree, w);
2183 err = PyFunction_SetClosure(x, v);
2184 Py_DECREF(v);
2186 if (x != NULL && oparg > 0) {
2187 v = PyTuple_New(oparg);
2188 if (v == NULL) {
2189 Py_DECREF(x);
2190 x = NULL;
2191 break;
2193 while (--oparg >= 0) {
2194 w = POP();
2195 PyTuple_SET_ITEM(v, oparg, w);
2197 err = PyFunction_SetDefaults(x, v);
2198 Py_DECREF(v);
2200 PUSH(x);
2201 break;
2204 case BUILD_SLICE:
2205 if (oparg == 3)
2206 w = POP();
2207 else
2208 w = NULL;
2209 v = POP();
2210 u = TOP();
2211 x = PySlice_New(u, v, w);
2212 Py_DECREF(u);
2213 Py_DECREF(v);
2214 Py_XDECREF(w);
2215 SET_TOP(x);
2216 if (x != NULL) continue;
2217 break;
2219 case EXTENDED_ARG:
2220 opcode = NEXTOP();
2221 oparg = oparg<<16 | NEXTARG();
2222 goto dispatch_opcode;
2224 default:
2225 fprintf(stderr,
2226 "XXX lineno: %d, opcode: %d\n",
2227 PyCode_Addr2Line(f->f_code, f->f_lasti),
2228 opcode);
2229 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2230 why = WHY_EXCEPTION;
2231 break;
2233 #ifdef CASE_TOO_BIG
2235 #endif
2237 } /* switch */
2239 on_error:
2241 /* Quickly continue if no error occurred */
2243 if (why == WHY_NOT) {
2244 if (err == 0 && x != NULL) {
2245 #ifdef CHECKEXC
2246 /* This check is expensive! */
2247 if (PyErr_Occurred())
2248 fprintf(stderr,
2249 "XXX undetected error\n");
2250 else
2251 #endif
2252 continue; /* Normal, fast path */
2254 why = WHY_EXCEPTION;
2255 x = Py_None;
2256 err = 0;
2259 /* Double-check exception status */
2261 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2262 if (!PyErr_Occurred()) {
2263 PyErr_SetString(PyExc_SystemError,
2264 "error return without exception set");
2265 why = WHY_EXCEPTION;
2268 #ifdef CHECKEXC
2269 else {
2270 /* This check is expensive! */
2271 if (PyErr_Occurred()) {
2272 fprintf(stderr,
2273 "XXX undetected error (why=%d)\n",
2274 why);
2275 why = WHY_EXCEPTION;
2278 #endif
2280 /* Log traceback info if this is a real exception */
2282 if (why == WHY_EXCEPTION) {
2283 PyTraceBack_Here(f);
2285 if (tstate->c_tracefunc != NULL)
2286 call_exc_trace(tstate->c_tracefunc,
2287 tstate->c_traceobj, f);
2290 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2292 if (why == WHY_RERAISE)
2293 why = WHY_EXCEPTION;
2295 /* Unwind stacks if a (pseudo) exception occurred */
2297 while (why != WHY_NOT && why != WHY_YIELD && f->f_iblock > 0) {
2298 PyTryBlock *b = PyFrame_BlockPop(f);
2300 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2301 /* For a continue inside a try block,
2302 don't pop the block for the loop. */
2303 PyFrame_BlockSetup(f, b->b_type, b->b_handler,
2304 b->b_level);
2305 why = WHY_NOT;
2306 JUMPTO(PyInt_AS_LONG(retval));
2307 Py_DECREF(retval);
2308 break;
2311 while (STACK_LEVEL() > b->b_level) {
2312 v = POP();
2313 Py_XDECREF(v);
2315 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2316 why = WHY_NOT;
2317 JUMPTO(b->b_handler);
2318 break;
2320 if (b->b_type == SETUP_FINALLY ||
2321 (b->b_type == SETUP_EXCEPT &&
2322 why == WHY_EXCEPTION)) {
2323 if (why == WHY_EXCEPTION) {
2324 PyObject *exc, *val, *tb;
2325 PyErr_Fetch(&exc, &val, &tb);
2326 if (val == NULL) {
2327 val = Py_None;
2328 Py_INCREF(val);
2330 /* Make the raw exception data
2331 available to the handler,
2332 so a program can emulate the
2333 Python main loop. Don't do
2334 this for 'finally'. */
2335 if (b->b_type == SETUP_EXCEPT) {
2336 PyErr_NormalizeException(
2337 &exc, &val, &tb);
2338 set_exc_info(tstate,
2339 exc, val, tb);
2341 if (tb == NULL) {
2342 Py_INCREF(Py_None);
2343 PUSH(Py_None);
2344 } else
2345 PUSH(tb);
2346 PUSH(val);
2347 PUSH(exc);
2349 else {
2350 if (why == WHY_RETURN ||
2351 why == WHY_CONTINUE)
2352 PUSH(retval);
2353 v = PyInt_FromLong((long)why);
2354 PUSH(v);
2356 why = WHY_NOT;
2357 JUMPTO(b->b_handler);
2358 break;
2360 } /* unwind stack */
2362 /* End the loop if we still have an error (or return) */
2364 if (why != WHY_NOT)
2365 break;
2367 } /* main loop */
2369 if (why != WHY_YIELD) {
2370 /* Pop remaining stack entries -- but when yielding */
2371 while (!EMPTY()) {
2372 v = POP();
2373 Py_XDECREF(v);
2377 if (why != WHY_RETURN && why != WHY_YIELD)
2378 retval = NULL;
2380 if (tstate->use_tracing) {
2381 if (tstate->c_tracefunc
2382 && (why == WHY_RETURN || why == WHY_YIELD)) {
2383 if (call_trace(tstate->c_tracefunc,
2384 tstate->c_traceobj, f,
2385 PyTrace_RETURN, retval)) {
2386 Py_XDECREF(retval);
2387 retval = NULL;
2388 why = WHY_EXCEPTION;
2391 if (tstate->c_profilefunc) {
2392 if (why == WHY_EXCEPTION)
2393 call_trace_protected(tstate->c_profilefunc,
2394 tstate->c_profileobj, f,
2395 PyTrace_RETURN);
2396 else if (call_trace(tstate->c_profilefunc,
2397 tstate->c_profileobj, f,
2398 PyTrace_RETURN, retval)) {
2399 Py_XDECREF(retval);
2400 retval = NULL;
2401 why = WHY_EXCEPTION;
2406 reset_exc_info(tstate);
2408 /* pop frame */
2409 --tstate->recursion_depth;
2410 tstate->frame = f->f_back;
2412 return retval;
2415 PyObject *
2416 PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals,
2417 PyObject **args, int argcount, PyObject **kws, int kwcount,
2418 PyObject **defs, int defcount, PyObject *closure)
2420 register PyFrameObject *f;
2421 register PyObject *retval = NULL;
2422 register PyObject **fastlocals, **freevars;
2423 PyThreadState *tstate = PyThreadState_GET();
2424 PyObject *x, *u;
2426 if (globals == NULL) {
2427 PyErr_SetString(PyExc_SystemError,
2428 "PyEval_EvalCodeEx: NULL globals");
2429 return NULL;
2432 assert(globals != NULL);
2433 f = PyFrame_New(tstate, co, globals, locals);
2434 if (f == NULL)
2435 return NULL;
2437 fastlocals = f->f_localsplus;
2438 freevars = f->f_localsplus + f->f_nlocals;
2440 if (co->co_argcount > 0 ||
2441 co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
2442 int i;
2443 int n = argcount;
2444 PyObject *kwdict = NULL;
2445 if (co->co_flags & CO_VARKEYWORDS) {
2446 kwdict = PyDict_New();
2447 if (kwdict == NULL)
2448 goto fail;
2449 i = co->co_argcount;
2450 if (co->co_flags & CO_VARARGS)
2451 i++;
2452 SETLOCAL(i, kwdict);
2454 if (argcount > co->co_argcount) {
2455 if (!(co->co_flags & CO_VARARGS)) {
2456 PyErr_Format(PyExc_TypeError,
2457 "%.200s() takes %s %d "
2458 "%sargument%s (%d given)",
2459 PyString_AsString(co->co_name),
2460 defcount ? "at most" : "exactly",
2461 co->co_argcount,
2462 kwcount ? "non-keyword " : "",
2463 co->co_argcount == 1 ? "" : "s",
2464 argcount);
2465 goto fail;
2467 n = co->co_argcount;
2469 for (i = 0; i < n; i++) {
2470 x = args[i];
2471 Py_INCREF(x);
2472 SETLOCAL(i, x);
2474 if (co->co_flags & CO_VARARGS) {
2475 u = PyTuple_New(argcount - n);
2476 if (u == NULL)
2477 goto fail;
2478 SETLOCAL(co->co_argcount, u);
2479 for (i = n; i < argcount; i++) {
2480 x = args[i];
2481 Py_INCREF(x);
2482 PyTuple_SET_ITEM(u, i-n, x);
2485 for (i = 0; i < kwcount; i++) {
2486 PyObject *keyword = kws[2*i];
2487 PyObject *value = kws[2*i + 1];
2488 int j;
2489 if (keyword == NULL || !PyString_Check(keyword)) {
2490 PyErr_Format(PyExc_TypeError,
2491 "%.200s() keywords must be strings",
2492 PyString_AsString(co->co_name));
2493 goto fail;
2495 /* XXX slow -- speed up using dictionary? */
2496 for (j = 0; j < co->co_argcount; j++) {
2497 PyObject *nm = PyTuple_GET_ITEM(
2498 co->co_varnames, j);
2499 int cmp = PyObject_RichCompareBool(
2500 keyword, nm, Py_EQ);
2501 if (cmp > 0)
2502 break;
2503 else if (cmp < 0)
2504 goto fail;
2506 /* Check errors from Compare */
2507 if (PyErr_Occurred())
2508 goto fail;
2509 if (j >= co->co_argcount) {
2510 if (kwdict == NULL) {
2511 PyErr_Format(PyExc_TypeError,
2512 "%.200s() got an unexpected "
2513 "keyword argument '%.400s'",
2514 PyString_AsString(co->co_name),
2515 PyString_AsString(keyword));
2516 goto fail;
2518 PyDict_SetItem(kwdict, keyword, value);
2520 else {
2521 if (GETLOCAL(j) != NULL) {
2522 PyErr_Format(PyExc_TypeError,
2523 "%.200s() got multiple "
2524 "values for keyword "
2525 "argument '%.400s'",
2526 PyString_AsString(co->co_name),
2527 PyString_AsString(keyword));
2528 goto fail;
2530 Py_INCREF(value);
2531 SETLOCAL(j, value);
2534 if (argcount < co->co_argcount) {
2535 int m = co->co_argcount - defcount;
2536 for (i = argcount; i < m; i++) {
2537 if (GETLOCAL(i) == NULL) {
2538 PyErr_Format(PyExc_TypeError,
2539 "%.200s() takes %s %d "
2540 "%sargument%s (%d given)",
2541 PyString_AsString(co->co_name),
2542 ((co->co_flags & CO_VARARGS) ||
2543 defcount) ? "at least"
2544 : "exactly",
2545 m, kwcount ? "non-keyword " : "",
2546 m == 1 ? "" : "s", i);
2547 goto fail;
2550 if (n > m)
2551 i = n - m;
2552 else
2553 i = 0;
2554 for (; i < defcount; i++) {
2555 if (GETLOCAL(m+i) == NULL) {
2556 PyObject *def = defs[i];
2557 Py_INCREF(def);
2558 SETLOCAL(m+i, def);
2563 else {
2564 if (argcount > 0 || kwcount > 0) {
2565 PyErr_Format(PyExc_TypeError,
2566 "%.200s() takes no arguments (%d given)",
2567 PyString_AsString(co->co_name),
2568 argcount + kwcount);
2569 goto fail;
2572 /* Allocate and initialize storage for cell vars, and copy free
2573 vars into frame. This isn't too efficient right now. */
2574 if (f->f_ncells) {
2575 int i = 0, j = 0, nargs, found;
2576 char *cellname, *argname;
2577 PyObject *c;
2579 nargs = co->co_argcount;
2580 if (co->co_flags & CO_VARARGS)
2581 nargs++;
2582 if (co->co_flags & CO_VARKEYWORDS)
2583 nargs++;
2585 /* Check for cells that shadow args */
2586 for (i = 0; i < f->f_ncells && j < nargs; ++i) {
2587 cellname = PyString_AS_STRING(
2588 PyTuple_GET_ITEM(co->co_cellvars, i));
2589 found = 0;
2590 while (j < nargs) {
2591 argname = PyString_AS_STRING(
2592 PyTuple_GET_ITEM(co->co_varnames, j));
2593 if (strcmp(cellname, argname) == 0) {
2594 c = PyCell_New(GETLOCAL(j));
2595 if (c == NULL)
2596 goto fail;
2597 GETLOCAL(f->f_nlocals + i) = c;
2598 found = 1;
2599 break;
2601 j++;
2603 if (found == 0) {
2604 c = PyCell_New(NULL);
2605 if (c == NULL)
2606 goto fail;
2607 SETLOCAL(f->f_nlocals + i, c);
2610 /* Initialize any that are left */
2611 while (i < f->f_ncells) {
2612 c = PyCell_New(NULL);
2613 if (c == NULL)
2614 goto fail;
2615 SETLOCAL(f->f_nlocals + i, c);
2616 i++;
2619 if (f->f_nfreevars) {
2620 int i;
2621 for (i = 0; i < f->f_nfreevars; ++i) {
2622 PyObject *o = PyTuple_GET_ITEM(closure, i);
2623 Py_INCREF(o);
2624 freevars[f->f_ncells + i] = o;
2628 if (co->co_flags & CO_GENERATOR) {
2629 /* Don't need to keep the reference to f_back, it will be set
2630 * when the generator is resumed. */
2631 Py_XDECREF(f->f_back);
2632 f->f_back = NULL;
2634 PCALL(PCALL_GENERATOR);
2636 /* Create a new generator that owns the ready to run frame
2637 * and return that as the value. */
2638 return gen_new(f);
2641 retval = eval_frame(f);
2643 fail: /* Jump here from prelude on failure */
2645 /* decref'ing the frame can cause __del__ methods to get invoked,
2646 which can call back into Python. While we're done with the
2647 current Python frame (f), the associated C stack is still in use,
2648 so recursion_depth must be boosted for the duration.
2650 assert(tstate != NULL);
2651 ++tstate->recursion_depth;
2652 Py_DECREF(f);
2653 --tstate->recursion_depth;
2654 return retval;
2658 /* Implementation notes for set_exc_info() and reset_exc_info():
2660 - Below, 'exc_ZZZ' stands for 'exc_type', 'exc_value' and
2661 'exc_traceback'. These always travel together.
2663 - tstate->curexc_ZZZ is the "hot" exception that is set by
2664 PyErr_SetString(), cleared by PyErr_Clear(), and so on.
2666 - Once an exception is caught by an except clause, it is transferred
2667 from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info()
2668 can pick it up. This is the primary task of set_exc_info().
2670 - Now let me explain the complicated dance with frame->f_exc_ZZZ.
2672 Long ago, when none of this existed, there were just a few globals:
2673 one set corresponding to the "hot" exception, and one set
2674 corresponding to sys.exc_ZZZ. (Actually, the latter weren't C
2675 globals; they were simply stored as sys.exc_ZZZ. For backwards
2676 compatibility, they still are!) The problem was that in code like
2677 this:
2679 try:
2680 "something that may fail"
2681 except "some exception":
2682 "do something else first"
2683 "print the exception from sys.exc_ZZZ."
2685 if "do something else first" invoked something that raised and caught
2686 an exception, sys.exc_ZZZ were overwritten. That was a frequent
2687 cause of subtle bugs. I fixed this by changing the semantics as
2688 follows:
2690 - Within one frame, sys.exc_ZZZ will hold the last exception caught
2691 *in that frame*.
2693 - But initially, and as long as no exception is caught in a given
2694 frame, sys.exc_ZZZ will hold the last exception caught in the
2695 previous frame (or the frame before that, etc.).
2697 The first bullet fixed the bug in the above example. The second
2698 bullet was for backwards compatibility: it was (and is) common to
2699 have a function that is called when an exception is caught, and to
2700 have that function access the caught exception via sys.exc_ZZZ.
2701 (Example: traceback.print_exc()).
2703 At the same time I fixed the problem that sys.exc_ZZZ weren't
2704 thread-safe, by introducing sys.exc_info() which gets it from tstate;
2705 but that's really a separate improvement.
2707 The reset_exc_info() function in ceval.c restores the tstate->exc_ZZZ
2708 variables to what they were before the current frame was called. The
2709 set_exc_info() function saves them on the frame so that
2710 reset_exc_info() can restore them. The invariant is that
2711 frame->f_exc_ZZZ is NULL iff the current frame never caught an
2712 exception (where "catching" an exception applies only to successful
2713 except clauses); and if the current frame ever caught an exception,
2714 frame->f_exc_ZZZ is the exception that was stored in tstate->exc_ZZZ
2715 at the start of the current frame.
2719 static void
2720 set_exc_info(PyThreadState *tstate,
2721 PyObject *type, PyObject *value, PyObject *tb)
2723 PyFrameObject *frame;
2724 PyObject *tmp_type, *tmp_value, *tmp_tb;
2726 frame = tstate->frame;
2727 if (frame->f_exc_type == NULL) {
2728 /* This frame didn't catch an exception before */
2729 /* Save previous exception of this thread in this frame */
2730 if (tstate->exc_type == NULL) {
2731 Py_INCREF(Py_None);
2732 tstate->exc_type = Py_None;
2734 tmp_type = frame->f_exc_type;
2735 tmp_value = frame->f_exc_value;
2736 tmp_tb = frame->f_exc_traceback;
2737 Py_XINCREF(tstate->exc_type);
2738 Py_XINCREF(tstate->exc_value);
2739 Py_XINCREF(tstate->exc_traceback);
2740 frame->f_exc_type = tstate->exc_type;
2741 frame->f_exc_value = tstate->exc_value;
2742 frame->f_exc_traceback = tstate->exc_traceback;
2743 Py_XDECREF(tmp_type);
2744 Py_XDECREF(tmp_value);
2745 Py_XDECREF(tmp_tb);
2747 /* Set new exception for this thread */
2748 tmp_type = tstate->exc_type;
2749 tmp_value = tstate->exc_value;
2750 tmp_tb = tstate->exc_traceback;
2751 Py_XINCREF(type);
2752 Py_XINCREF(value);
2753 Py_XINCREF(tb);
2754 tstate->exc_type = type;
2755 tstate->exc_value = value;
2756 tstate->exc_traceback = tb;
2757 Py_XDECREF(tmp_type);
2758 Py_XDECREF(tmp_value);
2759 Py_XDECREF(tmp_tb);
2760 /* For b/w compatibility */
2761 PySys_SetObject("exc_type", type);
2762 PySys_SetObject("exc_value", value);
2763 PySys_SetObject("exc_traceback", tb);
2766 static void
2767 reset_exc_info(PyThreadState *tstate)
2769 PyFrameObject *frame;
2770 PyObject *tmp_type, *tmp_value, *tmp_tb;
2771 frame = tstate->frame;
2772 if (frame->f_exc_type != NULL) {
2773 /* This frame caught an exception */
2774 tmp_type = tstate->exc_type;
2775 tmp_value = tstate->exc_value;
2776 tmp_tb = tstate->exc_traceback;
2777 Py_XINCREF(frame->f_exc_type);
2778 Py_XINCREF(frame->f_exc_value);
2779 Py_XINCREF(frame->f_exc_traceback);
2780 tstate->exc_type = frame->f_exc_type;
2781 tstate->exc_value = frame->f_exc_value;
2782 tstate->exc_traceback = frame->f_exc_traceback;
2783 Py_XDECREF(tmp_type);
2784 Py_XDECREF(tmp_value);
2785 Py_XDECREF(tmp_tb);
2786 /* For b/w compatibility */
2787 PySys_SetObject("exc_type", frame->f_exc_type);
2788 PySys_SetObject("exc_value", frame->f_exc_value);
2789 PySys_SetObject("exc_traceback", frame->f_exc_traceback);
2791 tmp_type = frame->f_exc_type;
2792 tmp_value = frame->f_exc_value;
2793 tmp_tb = frame->f_exc_traceback;
2794 frame->f_exc_type = NULL;
2795 frame->f_exc_value = NULL;
2796 frame->f_exc_traceback = NULL;
2797 Py_XDECREF(tmp_type);
2798 Py_XDECREF(tmp_value);
2799 Py_XDECREF(tmp_tb);
2802 /* Logic for the raise statement (too complicated for inlining).
2803 This *consumes* a reference count to each of its arguments. */
2804 static enum why_code
2805 do_raise(PyObject *type, PyObject *value, PyObject *tb)
2807 if (type == NULL) {
2808 /* Reraise */
2809 PyThreadState *tstate = PyThreadState_Get();
2810 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
2811 value = tstate->exc_value;
2812 tb = tstate->exc_traceback;
2813 Py_XINCREF(type);
2814 Py_XINCREF(value);
2815 Py_XINCREF(tb);
2818 /* We support the following forms of raise:
2819 raise <class>, <classinstance>
2820 raise <class>, <argument tuple>
2821 raise <class>, None
2822 raise <class>, <argument>
2823 raise <classinstance>, None
2824 raise <string>, <object>
2825 raise <string>, None
2827 An omitted second argument is the same as None.
2829 In addition, raise <tuple>, <anything> is the same as
2830 raising the tuple's first item (and it better have one!);
2831 this rule is applied recursively.
2833 Finally, an optional third argument can be supplied, which
2834 gives the traceback to be substituted (useful when
2835 re-raising an exception after examining it). */
2837 /* First, check the traceback argument, replacing None with
2838 NULL. */
2839 if (tb == Py_None) {
2840 Py_DECREF(tb);
2841 tb = NULL;
2843 else if (tb != NULL && !PyTraceBack_Check(tb)) {
2844 PyErr_SetString(PyExc_TypeError,
2845 "raise: arg 3 must be a traceback or None");
2846 goto raise_error;
2849 /* Next, replace a missing value with None */
2850 if (value == NULL) {
2851 value = Py_None;
2852 Py_INCREF(value);
2855 /* Next, repeatedly, replace a tuple exception with its first item */
2856 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
2857 PyObject *tmp = type;
2858 type = PyTuple_GET_ITEM(type, 0);
2859 Py_INCREF(type);
2860 Py_DECREF(tmp);
2863 if (PyString_CheckExact(type))
2864 /* Raising builtin string is deprecated but still allowed --
2865 * do nothing. Raising an instance of a new-style str
2866 * subclass is right out. */
2867 PyErr_Warn(PyExc_PendingDeprecationWarning,
2868 "raising a string exception is deprecated");
2870 else if (PyClass_Check(type))
2871 PyErr_NormalizeException(&type, &value, &tb);
2873 else if (PyInstance_Check(type)) {
2874 /* Raising an instance. The value should be a dummy. */
2875 if (value != Py_None) {
2876 PyErr_SetString(PyExc_TypeError,
2877 "instance exception may not have a separate value");
2878 goto raise_error;
2880 else {
2881 /* Normalize to raise <class>, <instance> */
2882 Py_DECREF(value);
2883 value = type;
2884 type = (PyObject*) ((PyInstanceObject*)type)->in_class;
2885 Py_INCREF(type);
2888 else {
2889 /* Not something you can raise. You get an exception
2890 anyway, just not what you specified :-) */
2891 PyErr_Format(PyExc_TypeError,
2892 "exceptions must be classes, instances, or "
2893 "strings (deprecated), not %s",
2894 type->ob_type->tp_name);
2895 goto raise_error;
2897 PyErr_Restore(type, value, tb);
2898 if (tb == NULL)
2899 return WHY_EXCEPTION;
2900 else
2901 return WHY_RERAISE;
2902 raise_error:
2903 Py_XDECREF(value);
2904 Py_XDECREF(type);
2905 Py_XDECREF(tb);
2906 return WHY_EXCEPTION;
2909 /* Iterate v argcnt times and store the results on the stack (via decreasing
2910 sp). Return 1 for success, 0 if error. */
2912 static int
2913 unpack_iterable(PyObject *v, int argcnt, PyObject **sp)
2915 int i = 0;
2916 PyObject *it; /* iter(v) */
2917 PyObject *w;
2919 assert(v != NULL);
2921 it = PyObject_GetIter(v);
2922 if (it == NULL)
2923 goto Error;
2925 for (; i < argcnt; i++) {
2926 w = PyIter_Next(it);
2927 if (w == NULL) {
2928 /* Iterator done, via error or exhaustion. */
2929 if (!PyErr_Occurred()) {
2930 PyErr_Format(PyExc_ValueError,
2931 "need more than %d value%s to unpack",
2932 i, i == 1 ? "" : "s");
2934 goto Error;
2936 *--sp = w;
2939 /* We better have exhausted the iterator now. */
2940 w = PyIter_Next(it);
2941 if (w == NULL) {
2942 if (PyErr_Occurred())
2943 goto Error;
2944 Py_DECREF(it);
2945 return 1;
2947 Py_DECREF(w);
2948 PyErr_SetString(PyExc_ValueError, "too many values to unpack");
2949 /* fall through */
2950 Error:
2951 for (; i > 0; i--, sp++)
2952 Py_DECREF(*sp);
2953 Py_XDECREF(it);
2954 return 0;
2958 #ifdef LLTRACE
2959 static int
2960 prtrace(PyObject *v, char *str)
2962 printf("%s ", str);
2963 if (PyObject_Print(v, stdout, 0) != 0)
2964 PyErr_Clear(); /* Don't know what else to do */
2965 printf("\n");
2966 return 1;
2968 #endif
2970 static void
2971 call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
2973 PyObject *type, *value, *traceback, *arg;
2974 int err;
2975 PyErr_Fetch(&type, &value, &traceback);
2976 if (value == NULL) {
2977 value = Py_None;
2978 Py_INCREF(value);
2980 arg = Py_BuildValue("(OOO)", type, value, traceback);
2981 if (arg == NULL) {
2982 PyErr_Restore(type, value, traceback);
2983 return;
2985 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
2986 Py_DECREF(arg);
2987 if (err == 0)
2988 PyErr_Restore(type, value, traceback);
2989 else {
2990 Py_XDECREF(type);
2991 Py_XDECREF(value);
2992 Py_XDECREF(traceback);
2996 static void
2997 call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
2998 int what)
3000 PyObject *type, *value, *traceback;
3001 int err;
3002 PyErr_Fetch(&type, &value, &traceback);
3003 err = call_trace(func, obj, frame, what, NULL);
3004 if (err == 0)
3005 PyErr_Restore(type, value, traceback);
3006 else {
3007 Py_XDECREF(type);
3008 Py_XDECREF(value);
3009 Py_XDECREF(traceback);
3013 static int
3014 call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
3015 int what, PyObject *arg)
3017 register PyThreadState *tstate = frame->f_tstate;
3018 int result;
3019 if (tstate->tracing)
3020 return 0;
3021 tstate->tracing++;
3022 tstate->use_tracing = 0;
3023 result = func(obj, frame, what, arg);
3024 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3025 || (tstate->c_profilefunc != NULL));
3026 tstate->tracing--;
3027 return result;
3030 PyObject *
3031 _PyEval_CallTracing(PyObject *func, PyObject *args)
3033 PyFrameObject *frame = PyEval_GetFrame();
3034 PyThreadState *tstate = frame->f_tstate;
3035 int save_tracing = tstate->tracing;
3036 int save_use_tracing = tstate->use_tracing;
3037 PyObject *result;
3039 tstate->tracing = 0;
3040 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
3041 || (tstate->c_profilefunc != NULL));
3042 result = PyObject_Call(func, args, NULL);
3043 tstate->tracing = save_tracing;
3044 tstate->use_tracing = save_use_tracing;
3045 return result;
3048 static int
3049 maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
3050 PyFrameObject *frame, int *instr_lb, int *instr_ub)
3052 /* The theory of SET_LINENO-less tracing.
3054 In a nutshell, we use the co_lnotab field of the code object
3055 to tell when execution has moved onto a different line.
3057 As mentioned above, the basic idea is so set things up so
3058 that
3060 *instr_lb <= frame->f_lasti < *instr_ub
3062 is true so long as execution does not change lines.
3064 This is all fairly simple. Digging the information out of
3065 co_lnotab takes some work, but is conceptually clear.
3067 Somewhat harder to explain is why we don't *always* call the
3068 line trace function when the above test fails.
3070 Consider this code:
3072 1: def f(a):
3073 2: if a:
3074 3: print 1
3075 4: else:
3076 5: print 2
3078 which compiles to this:
3080 2 0 LOAD_FAST 0 (a)
3081 3 JUMP_IF_FALSE 9 (to 15)
3082 6 POP_TOP
3084 3 7 LOAD_CONST 1 (1)
3085 10 PRINT_ITEM
3086 11 PRINT_NEWLINE
3087 12 JUMP_FORWARD 6 (to 21)
3088 >> 15 POP_TOP
3090 5 16 LOAD_CONST 2 (2)
3091 19 PRINT_ITEM
3092 20 PRINT_NEWLINE
3093 >> 21 LOAD_CONST 0 (None)
3094 24 RETURN_VALUE
3096 If 'a' is false, execution will jump to instruction at offset
3097 15 and the co_lnotab will claim that execution has moved to
3098 line 3. This is at best misleading. In this case we could
3099 associate the POP_TOP with line 4, but that doesn't make
3100 sense in all cases (I think).
3102 What we do is only call the line trace function if the co_lnotab
3103 indicates we have jumped to the *start* of a line, i.e. if the
3104 current instruction offset matches the offset given for the
3105 start of a line by the co_lnotab.
3107 This also takes care of the situation where 'a' is true.
3108 Execution will jump from instruction offset 12 to offset 21.
3109 Then the co_lnotab would imply that execution has moved to line
3110 5, which is again misleading.
3112 Why do we set f_lineno when tracing? Well, consider the code
3113 above when 'a' is true. If stepping through this with 'n' in
3114 pdb, you would stop at line 1 with a "call" type event, then
3115 line events on lines 2 and 3, then a "return" type event -- but
3116 you would be shown line 5 during this event. This is a change
3117 from the behaviour in 2.2 and before, and I've found it
3118 confusing in practice. By setting and using f_lineno when
3119 tracing, one can report a line number different from that
3120 suggested by f_lasti on this one occasion where it's desirable.
3123 int result = 0;
3125 if ((frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub)) {
3126 PyCodeObject* co = frame->f_code;
3127 int size, addr, line;
3128 unsigned char* p;
3130 size = PyString_GET_SIZE(co->co_lnotab) / 2;
3131 p = (unsigned char*)PyString_AS_STRING(co->co_lnotab);
3133 addr = 0;
3134 line = co->co_firstlineno;
3136 /* possible optimization: if f->f_lasti == instr_ub
3137 (likely to be a common case) then we already know
3138 instr_lb -- if we stored the matching value of p
3139 somwhere we could skip the first while loop. */
3141 /* see comments in compile.c for the description of
3142 co_lnotab. A point to remember: increments to p
3143 should come in pairs -- although we don't care about
3144 the line increments here, treating them as byte
3145 increments gets confusing, to say the least. */
3147 while (size > 0) {
3148 if (addr + *p > frame->f_lasti)
3149 break;
3150 addr += *p++;
3151 if (*p) *instr_lb = addr;
3152 line += *p++;
3153 --size;
3156 if (addr == frame->f_lasti) {
3157 frame->f_lineno = line;
3158 result = call_trace(func, obj, frame,
3159 PyTrace_LINE, Py_None);
3162 if (size > 0) {
3163 while (--size >= 0) {
3164 addr += *p++;
3165 if (*p++)
3166 break;
3168 *instr_ub = addr;
3170 else {
3171 *instr_ub = INT_MAX;
3175 return result;
3178 void
3179 PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
3181 PyThreadState *tstate = PyThreadState_Get();
3182 PyObject *temp = tstate->c_profileobj;
3183 Py_XINCREF(arg);
3184 tstate->c_profilefunc = NULL;
3185 tstate->c_profileobj = NULL;
3186 tstate->use_tracing = tstate->c_tracefunc != NULL;
3187 Py_XDECREF(temp);
3188 tstate->c_profilefunc = func;
3189 tstate->c_profileobj = arg;
3190 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
3193 void
3194 PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
3196 PyThreadState *tstate = PyThreadState_Get();
3197 PyObject *temp = tstate->c_traceobj;
3198 Py_XINCREF(arg);
3199 tstate->c_tracefunc = NULL;
3200 tstate->c_traceobj = NULL;
3201 tstate->use_tracing = tstate->c_profilefunc != NULL;
3202 Py_XDECREF(temp);
3203 tstate->c_tracefunc = func;
3204 tstate->c_traceobj = arg;
3205 tstate->use_tracing = ((func != NULL)
3206 || (tstate->c_profilefunc != NULL));
3209 PyObject *
3210 PyEval_GetBuiltins(void)
3212 PyFrameObject *current_frame = PyEval_GetFrame();
3213 if (current_frame == NULL)
3214 return PyThreadState_Get()->interp->builtins;
3215 else
3216 return current_frame->f_builtins;
3219 PyObject *
3220 PyEval_GetLocals(void)
3222 PyFrameObject *current_frame = PyEval_GetFrame();
3223 if (current_frame == NULL)
3224 return NULL;
3225 PyFrame_FastToLocals(current_frame);
3226 return current_frame->f_locals;
3229 PyObject *
3230 PyEval_GetGlobals(void)
3232 PyFrameObject *current_frame = PyEval_GetFrame();
3233 if (current_frame == NULL)
3234 return NULL;
3235 else
3236 return current_frame->f_globals;
3239 PyFrameObject *
3240 PyEval_GetFrame(void)
3242 PyThreadState *tstate = PyThreadState_Get();
3243 return _PyThreadState_GetFrame(tstate);
3247 PyEval_GetRestricted(void)
3249 PyFrameObject *current_frame = PyEval_GetFrame();
3250 return current_frame == NULL ? 0 : current_frame->f_restricted;
3254 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
3256 PyFrameObject *current_frame = PyEval_GetFrame();
3257 int result = cf->cf_flags != 0;
3259 if (current_frame != NULL) {
3260 const int codeflags = current_frame->f_code->co_flags;
3261 const int compilerflags = codeflags & PyCF_MASK;
3262 if (compilerflags) {
3263 result = 1;
3264 cf->cf_flags |= compilerflags;
3266 #if 0 /* future keyword */
3267 if (codeflags & CO_GENERATOR_ALLOWED) {
3268 result = 1;
3269 cf->cf_flags |= CO_GENERATOR_ALLOWED;
3271 #endif
3273 return result;
3277 Py_FlushLine(void)
3279 PyObject *f = PySys_GetObject("stdout");
3280 if (f == NULL)
3281 return 0;
3282 if (!PyFile_SoftSpace(f, 0))
3283 return 0;
3284 return PyFile_WriteString("\n", f);
3288 /* External interface to call any callable object.
3289 The arg must be a tuple or NULL. */
3291 #undef PyEval_CallObject
3292 /* for backward compatibility: export this interface */
3294 PyObject *
3295 PyEval_CallObject(PyObject *func, PyObject *arg)
3297 return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL);
3299 #define PyEval_CallObject(func,arg) \
3300 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
3302 PyObject *
3303 PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
3305 PyObject *result;
3307 if (arg == NULL)
3308 arg = PyTuple_New(0);
3309 else if (!PyTuple_Check(arg)) {
3310 PyErr_SetString(PyExc_TypeError,
3311 "argument list must be a tuple");
3312 return NULL;
3314 else
3315 Py_INCREF(arg);
3317 if (kw != NULL && !PyDict_Check(kw)) {
3318 PyErr_SetString(PyExc_TypeError,
3319 "keyword list must be a dictionary");
3320 Py_DECREF(arg);
3321 return NULL;
3324 result = PyObject_Call(func, arg, kw);
3325 Py_DECREF(arg);
3326 return result;
3329 char *
3330 PyEval_GetFuncName(PyObject *func)
3332 if (PyMethod_Check(func))
3333 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3334 else if (PyFunction_Check(func))
3335 return PyString_AsString(((PyFunctionObject*)func)->func_name);
3336 else if (PyCFunction_Check(func))
3337 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3338 else if (PyClass_Check(func))
3339 return PyString_AsString(((PyClassObject*)func)->cl_name);
3340 else if (PyInstance_Check(func)) {
3341 return PyString_AsString(
3342 ((PyInstanceObject*)func)->in_class->cl_name);
3343 } else {
3344 return func->ob_type->tp_name;
3348 char *
3349 PyEval_GetFuncDesc(PyObject *func)
3351 if (PyMethod_Check(func))
3352 return "()";
3353 else if (PyFunction_Check(func))
3354 return "()";
3355 else if (PyCFunction_Check(func))
3356 return "()";
3357 else if (PyClass_Check(func))
3358 return " constructor";
3359 else if (PyInstance_Check(func)) {
3360 return " instance";
3361 } else {
3362 return " object";
3366 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
3368 static void
3369 err_args(PyObject *func, int flags, int nargs)
3371 if (flags & METH_NOARGS)
3372 PyErr_Format(PyExc_TypeError,
3373 "%.200s() takes no arguments (%d given)",
3374 ((PyCFunctionObject *)func)->m_ml->ml_name,
3375 nargs);
3376 else
3377 PyErr_Format(PyExc_TypeError,
3378 "%.200s() takes exactly one argument (%d given)",
3379 ((PyCFunctionObject *)func)->m_ml->ml_name,
3380 nargs);
3383 static PyObject *
3384 call_function(PyObject ***pp_stack, int oparg)
3386 int na = oparg & 0xff;
3387 int nk = (oparg>>8) & 0xff;
3388 int n = na + 2 * nk;
3389 PyObject **pfunc = (*pp_stack) - n - 1;
3390 PyObject *func = *pfunc;
3391 PyObject *x, *w;
3393 /* Always dispatch PyCFunction first, because these are
3394 presumed to be the most frequent callable object.
3396 if (PyCFunction_Check(func) && nk == 0) {
3397 int flags = PyCFunction_GET_FLAGS(func);
3398 PCALL(PCALL_CFUNCTION);
3399 if (flags & (METH_NOARGS | METH_O)) {
3400 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3401 PyObject *self = PyCFunction_GET_SELF(func);
3402 if (flags & METH_NOARGS && na == 0)
3403 x = (*meth)(self, NULL);
3404 else if (flags & METH_O && na == 1) {
3405 PyObject *arg = EXT_POP(*pp_stack);
3406 x = (*meth)(self, arg);
3407 Py_DECREF(arg);
3409 else {
3410 err_args(func, flags, na);
3411 x = NULL;
3414 else {
3415 PyObject *callargs;
3416 callargs = load_args(pp_stack, na);
3417 x = PyCFunction_Call(func, callargs, NULL);
3418 Py_XDECREF(callargs);
3420 } else {
3421 if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
3422 /* optimize access to bound methods */
3423 PyObject *self = PyMethod_GET_SELF(func);
3424 PCALL(PCALL_METHOD);
3425 PCALL(PCALL_BOUND_METHOD);
3426 Py_INCREF(self);
3427 func = PyMethod_GET_FUNCTION(func);
3428 Py_INCREF(func);
3429 Py_DECREF(*pfunc);
3430 *pfunc = self;
3431 na++;
3432 n++;
3433 } else
3434 Py_INCREF(func);
3435 if (PyFunction_Check(func))
3436 x = fast_function(func, pp_stack, n, na, nk);
3437 else
3438 x = do_call(func, pp_stack, na, nk);
3439 Py_DECREF(func);
3442 /* What does this do? */
3443 while ((*pp_stack) > pfunc) {
3444 w = EXT_POP(*pp_stack);
3445 Py_DECREF(w);
3446 PCALL(PCALL_POP);
3448 return x;
3451 /* The fast_function() function optimize calls for which no argument
3452 tuple is necessary; the objects are passed directly from the stack.
3453 For the simplest case -- a function that takes only positional
3454 arguments and is called with only positional arguments -- it
3455 inlines the most primitive frame setup code from
3456 PyEval_EvalCodeEx(), which vastly reduces the checks that must be
3457 done before evaluating the frame.
3460 static PyObject *
3461 fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
3463 PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
3464 PyObject *globals = PyFunction_GET_GLOBALS(func);
3465 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
3466 PyObject **d = NULL;
3467 int nd = 0;
3469 PCALL(PCALL_FUNCTION);
3470 PCALL(PCALL_FAST_FUNCTION);
3471 if (argdefs == NULL && co->co_argcount == n &&
3472 co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
3473 PyFrameObject *f;
3474 PyObject *retval = NULL;
3475 PyThreadState *tstate = PyThreadState_GET();
3476 PyObject **fastlocals, **stack;
3477 int i;
3479 PCALL(PCALL_FASTER_FUNCTION);
3480 assert(globals != NULL);
3481 /* XXX Perhaps we should create a specialized
3482 PyFrame_New() that doesn't take locals, but does
3483 take builtins without sanity checking them.
3485 f = PyFrame_New(tstate, co, globals, NULL);
3486 if (f == NULL)
3487 return NULL;
3489 fastlocals = f->f_localsplus;
3490 stack = (*pp_stack) - n;
3492 for (i = 0; i < n; i++) {
3493 Py_INCREF(*stack);
3494 fastlocals[i] = *stack++;
3496 retval = eval_frame(f);
3497 assert(tstate != NULL);
3498 ++tstate->recursion_depth;
3499 Py_DECREF(f);
3500 --tstate->recursion_depth;
3501 return retval;
3503 if (argdefs != NULL) {
3504 d = &PyTuple_GET_ITEM(argdefs, 0);
3505 nd = ((PyTupleObject *)argdefs)->ob_size;
3507 return PyEval_EvalCodeEx(co, globals,
3508 (PyObject *)NULL, (*pp_stack)-n, na,
3509 (*pp_stack)-2*nk, nk, d, nd,
3510 PyFunction_GET_CLOSURE(func));
3513 static PyObject *
3514 update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
3515 PyObject *func)
3517 PyObject *kwdict = NULL;
3518 if (orig_kwdict == NULL)
3519 kwdict = PyDict_New();
3520 else {
3521 kwdict = PyDict_Copy(orig_kwdict);
3522 Py_DECREF(orig_kwdict);
3524 if (kwdict == NULL)
3525 return NULL;
3526 while (--nk >= 0) {
3527 int err;
3528 PyObject *value = EXT_POP(*pp_stack);
3529 PyObject *key = EXT_POP(*pp_stack);
3530 if (PyDict_GetItem(kwdict, key) != NULL) {
3531 PyErr_Format(PyExc_TypeError,
3532 "%.200s%s got multiple values "
3533 "for keyword argument '%.200s'",
3534 PyEval_GetFuncName(func),
3535 PyEval_GetFuncDesc(func),
3536 PyString_AsString(key));
3537 Py_DECREF(key);
3538 Py_DECREF(value);
3539 Py_DECREF(kwdict);
3540 return NULL;
3542 err = PyDict_SetItem(kwdict, key, value);
3543 Py_DECREF(key);
3544 Py_DECREF(value);
3545 if (err) {
3546 Py_DECREF(kwdict);
3547 return NULL;
3550 return kwdict;
3553 static PyObject *
3554 update_star_args(int nstack, int nstar, PyObject *stararg,
3555 PyObject ***pp_stack)
3557 PyObject *callargs, *w;
3559 callargs = PyTuple_New(nstack + nstar);
3560 if (callargs == NULL) {
3561 return NULL;
3563 if (nstar) {
3564 int i;
3565 for (i = 0; i < nstar; i++) {
3566 PyObject *a = PyTuple_GET_ITEM(stararg, i);
3567 Py_INCREF(a);
3568 PyTuple_SET_ITEM(callargs, nstack + i, a);
3571 while (--nstack >= 0) {
3572 w = EXT_POP(*pp_stack);
3573 PyTuple_SET_ITEM(callargs, nstack, w);
3575 return callargs;
3578 static PyObject *
3579 load_args(PyObject ***pp_stack, int na)
3581 PyObject *args = PyTuple_New(na);
3582 PyObject *w;
3584 if (args == NULL)
3585 return NULL;
3586 while (--na >= 0) {
3587 w = EXT_POP(*pp_stack);
3588 PyTuple_SET_ITEM(args, na, w);
3590 return args;
3593 static PyObject *
3594 do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
3596 PyObject *callargs = NULL;
3597 PyObject *kwdict = NULL;
3598 PyObject *result = NULL;
3600 if (nk > 0) {
3601 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
3602 if (kwdict == NULL)
3603 goto call_fail;
3605 callargs = load_args(pp_stack, na);
3606 if (callargs == NULL)
3607 goto call_fail;
3608 #ifdef CALL_PROFILE
3609 /* At this point, we have to look at the type of func to
3610 update the call stats properly. Do it here so as to avoid
3611 exposing the call stats machinery outside ceval.c
3613 if (PyFunction_Check(func))
3614 PCALL(PCALL_FUNCTION);
3615 else if (PyMethod_Check(func))
3616 PCALL(PCALL_METHOD);
3617 else if (PyType_Check(func))
3618 PCALL(PCALL_TYPE);
3619 else
3620 PCALL(PCALL_OTHER);
3621 #endif
3622 result = PyObject_Call(func, callargs, kwdict);
3623 call_fail:
3624 Py_XDECREF(callargs);
3625 Py_XDECREF(kwdict);
3626 return result;
3629 static PyObject *
3630 ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
3632 int nstar = 0;
3633 PyObject *callargs = NULL;
3634 PyObject *stararg = NULL;
3635 PyObject *kwdict = NULL;
3636 PyObject *result = NULL;
3638 if (flags & CALL_FLAG_KW) {
3639 kwdict = EXT_POP(*pp_stack);
3640 if (!(kwdict && PyDict_Check(kwdict))) {
3641 PyErr_Format(PyExc_TypeError,
3642 "%s%s argument after ** "
3643 "must be a dictionary",
3644 PyEval_GetFuncName(func),
3645 PyEval_GetFuncDesc(func));
3646 goto ext_call_fail;
3649 if (flags & CALL_FLAG_VAR) {
3650 stararg = EXT_POP(*pp_stack);
3651 if (!PyTuple_Check(stararg)) {
3652 PyObject *t = NULL;
3653 t = PySequence_Tuple(stararg);
3654 if (t == NULL) {
3655 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3656 PyErr_Format(PyExc_TypeError,
3657 "%s%s argument after * "
3658 "must be a sequence",
3659 PyEval_GetFuncName(func),
3660 PyEval_GetFuncDesc(func));
3662 goto ext_call_fail;
3664 Py_DECREF(stararg);
3665 stararg = t;
3667 nstar = PyTuple_GET_SIZE(stararg);
3669 if (nk > 0) {
3670 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
3671 if (kwdict == NULL)
3672 goto ext_call_fail;
3674 callargs = update_star_args(na, nstar, stararg, pp_stack);
3675 if (callargs == NULL)
3676 goto ext_call_fail;
3677 #ifdef CALL_PROFILE
3678 /* At this point, we have to look at the type of func to
3679 update the call stats properly. Do it here so as to avoid
3680 exposing the call stats machinery outside ceval.c
3682 if (PyFunction_Check(func))
3683 PCALL(PCALL_FUNCTION);
3684 else if (PyMethod_Check(func))
3685 PCALL(PCALL_METHOD);
3686 else if (PyType_Check(func))
3687 PCALL(PCALL_TYPE);
3688 else
3689 PCALL(PCALL_OTHER);
3690 #endif
3691 result = PyObject_Call(func, callargs, kwdict);
3692 ext_call_fail:
3693 Py_XDECREF(callargs);
3694 Py_XDECREF(kwdict);
3695 Py_XDECREF(stararg);
3696 return result;
3699 #define SLICE_ERROR_MSG \
3700 "standard sequence type does not support step size other than one"
3702 /* Extract a slice index from a PyInt or PyLong, and store in *pi.
3703 Silently reduce values larger than INT_MAX to INT_MAX, and silently
3704 boost values less than -INT_MAX to 0. Return 0 on error, 1 on success.
3706 /* Note: If v is NULL, return success without storing into *pi. This
3707 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
3708 called by the SLICE opcode with v and/or w equal to NULL.
3711 _PyEval_SliceIndex(PyObject *v, int *pi)
3713 if (v != NULL) {
3714 long x;
3715 if (PyInt_Check(v)) {
3716 x = PyInt_AsLong(v);
3717 } else if (PyLong_Check(v)) {
3718 x = PyLong_AsLong(v);
3719 if (x==-1 && PyErr_Occurred()) {
3720 PyObject *long_zero;
3721 int cmp;
3723 if (!PyErr_ExceptionMatches(
3724 PyExc_OverflowError)) {
3725 /* It's not an overflow error, so just
3726 signal an error */
3727 return 0;
3730 /* Clear the OverflowError */
3731 PyErr_Clear();
3733 /* It's an overflow error, so we need to
3734 check the sign of the long integer,
3735 set the value to INT_MAX or -INT_MAX,
3736 and clear the error. */
3738 /* Create a long integer with a value of 0 */
3739 long_zero = PyLong_FromLong(0L);
3740 if (long_zero == NULL)
3741 return 0;
3743 /* Check sign */
3744 cmp = PyObject_RichCompareBool(v, long_zero,
3745 Py_GT);
3746 Py_DECREF(long_zero);
3747 if (cmp < 0)
3748 return 0;
3749 else if (cmp)
3750 x = INT_MAX;
3751 else
3752 x = -INT_MAX;
3754 } else {
3755 PyErr_SetString(PyExc_TypeError,
3756 "slice indices must be integers");
3757 return 0;
3759 /* Truncate -- very long indices are truncated anyway */
3760 if (x > INT_MAX)
3761 x = INT_MAX;
3762 else if (x < -INT_MAX)
3763 x = -INT_MAX;
3764 *pi = x;
3766 return 1;
3769 #undef ISINT
3770 #define ISINT(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x))
3772 static PyObject *
3773 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
3775 PyTypeObject *tp = u->ob_type;
3776 PySequenceMethods *sq = tp->tp_as_sequence;
3778 if (sq && sq->sq_slice && ISINT(v) && ISINT(w)) {
3779 int ilow = 0, ihigh = INT_MAX;
3780 if (!_PyEval_SliceIndex(v, &ilow))
3781 return NULL;
3782 if (!_PyEval_SliceIndex(w, &ihigh))
3783 return NULL;
3784 return PySequence_GetSlice(u, ilow, ihigh);
3786 else {
3787 PyObject *slice = PySlice_New(v, w, NULL);
3788 if (slice != NULL) {
3789 PyObject *res = PyObject_GetItem(u, slice);
3790 Py_DECREF(slice);
3791 return res;
3793 else
3794 return NULL;
3798 static int
3799 assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x)
3800 /* u[v:w] = x */
3802 PyTypeObject *tp = u->ob_type;
3803 PySequenceMethods *sq = tp->tp_as_sequence;
3805 if (sq && sq->sq_slice && ISINT(v) && ISINT(w)) {
3806 int ilow = 0, ihigh = INT_MAX;
3807 if (!_PyEval_SliceIndex(v, &ilow))
3808 return -1;
3809 if (!_PyEval_SliceIndex(w, &ihigh))
3810 return -1;
3811 if (x == NULL)
3812 return PySequence_DelSlice(u, ilow, ihigh);
3813 else
3814 return PySequence_SetSlice(u, ilow, ihigh, x);
3816 else {
3817 PyObject *slice = PySlice_New(v, w, NULL);
3818 if (slice != NULL) {
3819 int res;
3820 if (x != NULL)
3821 res = PyObject_SetItem(u, slice, x);
3822 else
3823 res = PyObject_DelItem(u, slice);
3824 Py_DECREF(slice);
3825 return res;
3827 else
3828 return -1;
3832 static PyObject *
3833 cmp_outcome(int op, register PyObject *v, register PyObject *w)
3835 int res = 0;
3836 switch (op) {
3837 case PyCmp_IS:
3838 res = (v == w);
3839 break;
3840 case PyCmp_IS_NOT:
3841 res = (v != w);
3842 break;
3843 case PyCmp_IN:
3844 res = PySequence_Contains(w, v);
3845 if (res < 0)
3846 return NULL;
3847 break;
3848 case PyCmp_NOT_IN:
3849 res = PySequence_Contains(w, v);
3850 if (res < 0)
3851 return NULL;
3852 res = !res;
3853 break;
3854 case PyCmp_EXC_MATCH:
3855 res = PyErr_GivenExceptionMatches(v, w);
3856 break;
3857 default:
3858 return PyObject_RichCompare(v, w, op);
3860 v = res ? Py_True : Py_False;
3861 Py_INCREF(v);
3862 return v;
3865 static PyObject *
3866 import_from(PyObject *v, PyObject *name)
3868 PyObject *x;
3870 x = PyObject_GetAttr(v, name);
3871 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3872 PyErr_Format(PyExc_ImportError,
3873 "cannot import name %.230s",
3874 PyString_AsString(name));
3876 return x;
3879 static int
3880 import_all_from(PyObject *locals, PyObject *v)
3882 PyObject *all = PyObject_GetAttrString(v, "__all__");
3883 PyObject *dict, *name, *value;
3884 int skip_leading_underscores = 0;
3885 int pos, err;
3887 if (all == NULL) {
3888 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
3889 return -1; /* Unexpected error */
3890 PyErr_Clear();
3891 dict = PyObject_GetAttrString(v, "__dict__");
3892 if (dict == NULL) {
3893 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
3894 return -1;
3895 PyErr_SetString(PyExc_ImportError,
3896 "from-import-* object has no __dict__ and no __all__");
3897 return -1;
3899 all = PyMapping_Keys(dict);
3900 Py_DECREF(dict);
3901 if (all == NULL)
3902 return -1;
3903 skip_leading_underscores = 1;
3906 for (pos = 0, err = 0; ; pos++) {
3907 name = PySequence_GetItem(all, pos);
3908 if (name == NULL) {
3909 if (!PyErr_ExceptionMatches(PyExc_IndexError))
3910 err = -1;
3911 else
3912 PyErr_Clear();
3913 break;
3915 if (skip_leading_underscores &&
3916 PyString_Check(name) &&
3917 PyString_AS_STRING(name)[0] == '_')
3919 Py_DECREF(name);
3920 continue;
3922 value = PyObject_GetAttr(v, name);
3923 if (value == NULL)
3924 err = -1;
3925 else
3926 err = PyDict_SetItem(locals, name, value);
3927 Py_DECREF(name);
3928 Py_XDECREF(value);
3929 if (err != 0)
3930 break;
3932 Py_DECREF(all);
3933 return err;
3936 static PyObject *
3937 build_class(PyObject *methods, PyObject *bases, PyObject *name)
3939 PyObject *metaclass = NULL, *result, *base;
3941 if (PyDict_Check(methods))
3942 metaclass = PyDict_GetItemString(methods, "__metaclass__");
3943 if (metaclass != NULL)
3944 Py_INCREF(metaclass);
3945 else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
3946 base = PyTuple_GET_ITEM(bases, 0);
3947 metaclass = PyObject_GetAttrString(base, "__class__");
3948 if (metaclass == NULL) {
3949 PyErr_Clear();
3950 metaclass = (PyObject *)base->ob_type;
3951 Py_INCREF(metaclass);
3954 else {
3955 PyObject *g = PyEval_GetGlobals();
3956 if (g != NULL && PyDict_Check(g))
3957 metaclass = PyDict_GetItemString(g, "__metaclass__");
3958 if (metaclass == NULL)
3959 metaclass = (PyObject *) &PyClass_Type;
3960 Py_INCREF(metaclass);
3962 result = PyObject_CallFunction(metaclass, "OOO", name, bases, methods);
3963 Py_DECREF(metaclass);
3964 return result;
3967 static int
3968 exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
3969 PyObject *locals)
3971 int n;
3972 PyObject *v;
3973 int plain = 0;
3975 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
3976 ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
3977 /* Backward compatibility hack */
3978 globals = PyTuple_GetItem(prog, 1);
3979 if (n == 3)
3980 locals = PyTuple_GetItem(prog, 2);
3981 prog = PyTuple_GetItem(prog, 0);
3983 if (globals == Py_None) {
3984 globals = PyEval_GetGlobals();
3985 if (locals == Py_None) {
3986 locals = PyEval_GetLocals();
3987 plain = 1;
3990 else if (locals == Py_None)
3991 locals = globals;
3992 if (!PyString_Check(prog) &&
3993 !PyUnicode_Check(prog) &&
3994 !PyCode_Check(prog) &&
3995 !PyFile_Check(prog)) {
3996 PyErr_SetString(PyExc_TypeError,
3997 "exec: arg 1 must be a string, file, or code object");
3998 return -1;
4000 if (!PyDict_Check(globals)) {
4001 PyErr_SetString(PyExc_TypeError,
4002 "exec: arg 2 must be a dictionary or None");
4003 return -1;
4005 if (!PyDict_Check(locals)) {
4006 PyErr_SetString(PyExc_TypeError,
4007 "exec: arg 3 must be a dictionary or None");
4008 return -1;
4010 if (PyDict_GetItemString(globals, "__builtins__") == NULL)
4011 PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
4012 if (PyCode_Check(prog)) {
4013 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
4014 PyErr_SetString(PyExc_TypeError,
4015 "code object passed to exec may not contain free variables");
4016 return -1;
4018 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
4020 else if (PyFile_Check(prog)) {
4021 FILE *fp = PyFile_AsFile(prog);
4022 char *name = PyString_AsString(PyFile_Name(prog));
4023 PyCompilerFlags cf;
4024 cf.cf_flags = 0;
4025 if (PyEval_MergeCompilerFlags(&cf))
4026 v = PyRun_FileFlags(fp, name, Py_file_input, globals,
4027 locals, &cf);
4028 else
4029 v = PyRun_File(fp, name, Py_file_input, globals,
4030 locals);
4032 else {
4033 PyObject *tmp = NULL;
4034 char *str;
4035 PyCompilerFlags cf;
4036 cf.cf_flags = 0;
4037 #ifdef Py_USING_UNICODE
4038 if (PyUnicode_Check(prog)) {
4039 tmp = PyUnicode_AsUTF8String(prog);
4040 if (tmp == NULL)
4041 return -1;
4042 prog = tmp;
4043 cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
4045 #endif
4046 if (PyString_AsStringAndSize(prog, &str, NULL))
4047 return -1;
4048 if (PyEval_MergeCompilerFlags(&cf))
4049 v = PyRun_StringFlags(str, Py_file_input, globals,
4050 locals, &cf);
4051 else
4052 v = PyRun_String(str, Py_file_input, globals, locals);
4053 Py_XDECREF(tmp);
4055 if (plain)
4056 PyFrame_LocalsToFast(f, 0);
4057 if (v == NULL)
4058 return -1;
4059 Py_DECREF(v);
4060 return 0;
4063 static void
4064 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
4066 char *obj_str;
4068 if (!obj)
4069 return;
4071 obj_str = PyString_AsString(obj);
4072 if (!obj_str)
4073 return;
4075 PyErr_Format(exc, format_str, obj_str);
4078 #ifdef DYNAMIC_EXECUTION_PROFILE
4080 static PyObject *
4081 getarray(long a[256])
4083 int i;
4084 PyObject *l = PyList_New(256);
4085 if (l == NULL) return NULL;
4086 for (i = 0; i < 256; i++) {
4087 PyObject *x = PyInt_FromLong(a[i]);
4088 if (x == NULL) {
4089 Py_DECREF(l);
4090 return NULL;
4092 PyList_SetItem(l, i, x);
4094 for (i = 0; i < 256; i++)
4095 a[i] = 0;
4096 return l;
4099 PyObject *
4100 _Py_GetDXProfile(PyObject *self, PyObject *args)
4102 #ifndef DXPAIRS
4103 return getarray(dxp);
4104 #else
4105 int i;
4106 PyObject *l = PyList_New(257);
4107 if (l == NULL) return NULL;
4108 for (i = 0; i < 257; i++) {
4109 PyObject *x = getarray(dxpairs[i]);
4110 if (x == NULL) {
4111 Py_DECREF(l);
4112 return NULL;
4114 PyList_SetItem(l, i, x);
4116 return l;
4117 #endif
4120 #endif