This commit was manufactured by cvs2svn to create tag 'r221'.
[python/dscho.git] / Python / ceval.c
blob0fa58877819122a5a77399a9b797f18186e1ce20
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 *fast_function(PyObject *, PyObject ***, int, int, int);
37 static PyObject *fast_cfunction(PyObject *, PyObject ***, 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 PyObject *loop_subscript(PyObject *, PyObject *);
55 static PyObject *apply_slice(PyObject *, PyObject *, PyObject *);
56 static int assign_slice(PyObject *, PyObject *,
57 PyObject *, PyObject *);
58 static PyObject *cmp_outcome(int, PyObject *, PyObject *);
59 static PyObject *import_from(PyObject *, PyObject *);
60 static int import_all_from(PyObject *, PyObject *);
61 static PyObject *build_class(PyObject *, PyObject *, PyObject *);
62 static int exec_statement(PyFrameObject *,
63 PyObject *, PyObject *, PyObject *);
64 static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
65 static void reset_exc_info(PyThreadState *);
66 static void format_exc_check_arg(PyObject *, char *, PyObject *);
68 #define NAME_ERROR_MSG \
69 "name '%.200s' is not defined"
70 #define GLOBAL_NAME_ERROR_MSG \
71 "global name '%.200s' is not defined"
72 #define UNBOUNDLOCAL_ERROR_MSG \
73 "local variable '%.200s' referenced before assignment"
74 #define UNBOUNDFREE_ERROR_MSG \
75 "free variable '%.200s' referenced before assignment" \
76 " in enclosing scope"
78 /* Dynamic execution profile */
79 #ifdef DYNAMIC_EXECUTION_PROFILE
80 #ifdef DXPAIRS
81 static long dxpairs[257][256];
82 #define dxp dxpairs[256]
83 #else
84 static long dxp[256];
85 #endif
86 #endif
88 staticforward PyTypeObject gentype;
90 typedef struct {
91 PyObject_HEAD
92 /* The gi_ prefix is intended to remind of generator-iterator. */
94 PyFrameObject *gi_frame;
96 /* True if generator is being executed. */
97 int gi_running;
98 } genobject;
100 static PyObject *
101 gen_new(PyFrameObject *f)
103 genobject *gen = PyObject_New(genobject, &gentype);
104 if (gen == NULL) {
105 Py_DECREF(f);
106 return NULL;
108 gen->gi_frame = f;
109 gen->gi_running = 0;
110 PyObject_GC_Init(gen);
111 return (PyObject *)gen;
114 static int
115 gen_traverse(genobject *gen, visitproc visit, void *arg)
117 return visit((PyObject *)gen->gi_frame, arg);
120 static void
121 gen_dealloc(genobject *gen)
123 PyObject_GC_Fini(gen);
124 Py_DECREF(gen->gi_frame);
125 PyObject_Del(gen);
128 static PyObject *
129 gen_iternext(genobject *gen)
131 PyThreadState *tstate = PyThreadState_GET();
132 PyFrameObject *f = gen->gi_frame;
133 PyObject *result;
135 if (gen->gi_running) {
136 PyErr_SetString(PyExc_ValueError,
137 "generator already executing");
138 return NULL;
140 if (f->f_stacktop == NULL)
141 return NULL;
143 /* Generators always return to their most recent caller, not
144 * necessarily their creator. */
145 Py_XINCREF(tstate->frame);
146 assert(f->f_back == NULL);
147 f->f_back = tstate->frame;
149 gen->gi_running = 1;
150 result = eval_frame(f);
151 gen->gi_running = 0;
153 /* Don't keep the reference to f_back any longer than necessary. It
154 * may keep a chain of frames alive or it could create a reference
155 * cycle. */
156 Py_XDECREF(f->f_back);
157 f->f_back = NULL;
159 /* If the generator just returned (as opposed to yielding), signal
160 * that the generator is exhausted. */
161 if (result == Py_None && f->f_stacktop == NULL) {
162 Py_DECREF(result);
163 result = NULL;
166 return result;
169 static PyObject *
170 gen_next(genobject *gen)
172 PyObject *result;
174 result = gen_iternext(gen);
176 if (result == NULL && !PyErr_Occurred()) {
177 PyErr_SetObject(PyExc_StopIteration, Py_None);
178 return NULL;
181 return result;
184 static PyObject *
185 gen_getiter(PyObject *gen)
187 Py_INCREF(gen);
188 return gen;
191 static struct PyMethodDef gen_methods[] = {
192 {"next", (PyCFunction)gen_next, METH_NOARGS,
193 "next() -- get the next value, or raise StopIteration"},
194 {NULL, NULL} /* Sentinel */
197 static PyMemberDef gen_memberlist[] = {
198 {"gi_frame", T_OBJECT, offsetof(genobject, gi_frame), RO},
199 {"gi_running", T_INT, offsetof(genobject, gi_running), RO},
200 {NULL} /* Sentinel */
203 statichere PyTypeObject gentype = {
204 PyObject_HEAD_INIT(&PyType_Type)
205 0, /* ob_size */
206 "generator", /* tp_name */
207 sizeof(genobject) + PyGC_HEAD_SIZE, /* tp_basicsize */
208 0, /* tp_itemsize */
209 /* methods */
210 (destructor)gen_dealloc, /* tp_dealloc */
211 0, /* tp_print */
212 0, /* tp_getattr */
213 0, /* tp_setattr */
214 0, /* tp_compare */
215 0, /* tp_repr */
216 0, /* tp_as_number */
217 0, /* tp_as_sequence */
218 0, /* tp_as_mapping */
219 0, /* tp_hash */
220 0, /* tp_call */
221 0, /* tp_str */
222 PyObject_GenericGetAttr, /* tp_getattro */
223 0, /* tp_setattro */
224 0, /* tp_as_buffer */
225 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /* tp_flags */
226 0, /* tp_doc */
227 (traverseproc)gen_traverse, /* tp_traverse */
228 0, /* tp_clear */
229 0, /* tp_richcompare */
230 0, /* tp_weaklistoffset */
231 (getiterfunc)gen_getiter, /* tp_iter */
232 (iternextfunc)gen_iternext, /* tp_iternext */
233 gen_methods, /* tp_methods */
234 gen_memberlist, /* tp_members */
235 0, /* tp_getset */
236 0, /* tp_base */
237 0, /* tp_dict */
241 #ifdef WITH_THREAD
243 #ifndef DONT_HAVE_ERRNO_H
244 #include <errno.h>
245 #endif
246 #include "pythread.h"
248 extern int _PyThread_Started; /* Flag for Py_Exit */
250 static PyThread_type_lock interpreter_lock = 0;
251 static long main_thread = 0;
253 void
254 PyEval_InitThreads(void)
256 if (interpreter_lock)
257 return;
258 _PyThread_Started = 1;
259 interpreter_lock = PyThread_allocate_lock();
260 PyThread_acquire_lock(interpreter_lock, 1);
261 main_thread = PyThread_get_thread_ident();
264 void
265 PyEval_AcquireLock(void)
267 PyThread_acquire_lock(interpreter_lock, 1);
270 void
271 PyEval_ReleaseLock(void)
273 PyThread_release_lock(interpreter_lock);
276 void
277 PyEval_AcquireThread(PyThreadState *tstate)
279 if (tstate == NULL)
280 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
281 PyThread_acquire_lock(interpreter_lock, 1);
282 if (PyThreadState_Swap(tstate) != NULL)
283 Py_FatalError(
284 "PyEval_AcquireThread: non-NULL old thread state");
287 void
288 PyEval_ReleaseThread(PyThreadState *tstate)
290 if (tstate == NULL)
291 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
292 if (PyThreadState_Swap(NULL) != tstate)
293 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
294 PyThread_release_lock(interpreter_lock);
297 /* This function is called from PyOS_AfterFork to ensure that newly
298 created child processes don't hold locks referring to threads which
299 are not running in the child process. (This could also be done using
300 pthread_atfork mechanism, at least for the pthreads implementation.) */
302 void
303 PyEval_ReInitThreads(void)
305 if (!interpreter_lock)
306 return;
307 /*XXX Can't use PyThread_free_lock here because it does too
308 much error-checking. Doing this cleanly would require
309 adding a new function to each thread_*.h. Instead, just
310 create a new lock and waste a little bit of memory */
311 interpreter_lock = PyThread_allocate_lock();
312 PyThread_acquire_lock(interpreter_lock, 1);
313 main_thread = PyThread_get_thread_ident();
315 #endif
317 /* Functions save_thread and restore_thread are always defined so
318 dynamically loaded modules needn't be compiled separately for use
319 with and without threads: */
321 PyThreadState *
322 PyEval_SaveThread(void)
324 PyThreadState *tstate = PyThreadState_Swap(NULL);
325 if (tstate == NULL)
326 Py_FatalError("PyEval_SaveThread: NULL tstate");
327 #ifdef WITH_THREAD
328 if (interpreter_lock)
329 PyThread_release_lock(interpreter_lock);
330 #endif
331 return tstate;
334 void
335 PyEval_RestoreThread(PyThreadState *tstate)
337 if (tstate == NULL)
338 Py_FatalError("PyEval_RestoreThread: NULL tstate");
339 #ifdef WITH_THREAD
340 if (interpreter_lock) {
341 int err = errno;
342 PyThread_acquire_lock(interpreter_lock, 1);
343 errno = err;
345 #endif
346 PyThreadState_Swap(tstate);
350 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
351 signal handlers or Mac I/O completion routines) can schedule calls
352 to a function to be called synchronously.
353 The synchronous function is called with one void* argument.
354 It should return 0 for success or -1 for failure -- failure should
355 be accompanied by an exception.
357 If registry succeeds, the registry function returns 0; if it fails
358 (e.g. due to too many pending calls) it returns -1 (without setting
359 an exception condition).
361 Note that because registry may occur from within signal handlers,
362 or other asynchronous events, calling malloc() is unsafe!
364 #ifdef WITH_THREAD
365 Any thread can schedule pending calls, but only the main thread
366 will execute them.
367 #endif
369 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
370 There are two possible race conditions:
371 (1) nested asynchronous registry calls;
372 (2) registry calls made while pending calls are being processed.
373 While (1) is very unlikely, (2) is a real possibility.
374 The current code is safe against (2), but not against (1).
375 The safety against (2) is derived from the fact that only one
376 thread (the main thread) ever takes things out of the queue.
378 XXX Darn! With the advent of thread state, we should have an array
379 of pending calls per thread in the thread state! Later...
382 #define NPENDINGCALLS 32
383 static struct {
384 int (*func)(void *);
385 void *arg;
386 } pendingcalls[NPENDINGCALLS];
387 static volatile int pendingfirst = 0;
388 static volatile int pendinglast = 0;
389 static volatile int things_to_do = 0;
392 Py_AddPendingCall(int (*func)(void *), void *arg)
394 static int busy = 0;
395 int i, j;
396 /* XXX Begin critical section */
397 /* XXX If you want this to be safe against nested
398 XXX asynchronous calls, you'll have to work harder! */
399 if (busy)
400 return -1;
401 busy = 1;
402 i = pendinglast;
403 j = (i + 1) % NPENDINGCALLS;
404 if (j == pendingfirst)
405 return -1; /* Queue full */
406 pendingcalls[i].func = func;
407 pendingcalls[i].arg = arg;
408 pendinglast = j;
409 things_to_do = 1; /* Signal main loop */
410 busy = 0;
411 /* XXX End critical section */
412 return 0;
416 Py_MakePendingCalls(void)
418 static int busy = 0;
419 #ifdef WITH_THREAD
420 if (main_thread && PyThread_get_thread_ident() != main_thread)
421 return 0;
422 #endif
423 if (busy)
424 return 0;
425 busy = 1;
426 things_to_do = 0;
427 for (;;) {
428 int i;
429 int (*func)(void *);
430 void *arg;
431 i = pendingfirst;
432 if (i == pendinglast)
433 break; /* Queue empty */
434 func = pendingcalls[i].func;
435 arg = pendingcalls[i].arg;
436 pendingfirst = (i + 1) % NPENDINGCALLS;
437 if (func(arg) < 0) {
438 busy = 0;
439 things_to_do = 1; /* We're not done yet */
440 return -1;
443 busy = 0;
444 return 0;
448 /* The interpreter's recursion limit */
450 static int recursion_limit = 1000;
453 Py_GetRecursionLimit(void)
455 return recursion_limit;
458 void
459 Py_SetRecursionLimit(int new_limit)
461 recursion_limit = new_limit;
464 /* Status code for main loop (reason for stack unwind) */
466 enum why_code {
467 WHY_NOT, /* No error */
468 WHY_EXCEPTION, /* Exception occurred */
469 WHY_RERAISE, /* Exception re-raised by 'finally' */
470 WHY_RETURN, /* 'return' statement */
471 WHY_BREAK, /* 'break' statement */
472 WHY_CONTINUE, /* 'continue' statement */
473 WHY_YIELD /* 'yield' operator */
476 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
477 static int unpack_iterable(PyObject *, int, PyObject **);
480 PyObject *
481 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
483 return PyEval_EvalCodeEx(co,
484 globals, locals,
485 (PyObject **)NULL, 0,
486 (PyObject **)NULL, 0,
487 (PyObject **)NULL, 0,
488 NULL);
492 /* Interpreter main loop */
494 static PyObject *
495 eval_frame(PyFrameObject *f)
497 #ifdef DXPAIRS
498 int lastopcode = 0;
499 #endif
500 PyObject **stack_pointer; /* Next free slot in value stack */
501 register unsigned char *next_instr;
502 register int opcode=0; /* Current opcode */
503 register int oparg=0; /* Current opcode argument, if any */
504 register enum why_code why; /* Reason for block stack unwind */
505 register int err; /* Error status -- nonzero if error */
506 register PyObject *x; /* Result object -- NULL if error */
507 register PyObject *v; /* Temporary objects popped off stack */
508 register PyObject *w;
509 register PyObject *u;
510 register PyObject *t;
511 register PyObject *stream = NULL; /* for PRINT opcodes */
512 register PyObject **fastlocals, **freevars;
513 PyObject *retval = NULL; /* Return value */
514 PyThreadState *tstate = PyThreadState_GET();
515 PyCodeObject *co;
516 unsigned char *first_instr;
517 #ifdef LLTRACE
518 int lltrace;
519 #endif
520 #if defined(Py_DEBUG) || defined(LLTRACE)
521 /* Make it easier to find out where we are with a debugger */
522 char *filename;
523 #endif
525 /* Code access macros */
527 #define GETCONST(i) Getconst(f, i)
528 #define GETNAME(i) Getname(f, i)
529 #define GETNAMEV(i) Getnamev(f, i)
530 #define INSTR_OFFSET() (next_instr - first_instr)
531 #define NEXTOP() (*next_instr++)
532 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
533 #define JUMPTO(x) (next_instr = first_instr + (x))
534 #define JUMPBY(x) (next_instr += (x))
536 /* Stack manipulation macros */
538 #define STACK_LEVEL() (stack_pointer - f->f_valuestack)
539 #define EMPTY() (STACK_LEVEL() == 0)
540 #define TOP() (stack_pointer[-1])
541 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
542 #define BASIC_POP() (*--stack_pointer)
544 #ifdef LLTRACE
545 #define PUSH(v) { (void)(BASIC_PUSH(v), \
546 lltrace && prtrace(TOP(), "push")); \
547 assert(STACK_LEVEL() <= f->f_stacksize); }
548 #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP())
549 #else
550 #define PUSH(v) BASIC_PUSH(v)
551 #define POP() BASIC_POP()
552 #endif
554 /* Local variable macros */
556 #define GETLOCAL(i) (fastlocals[i])
558 /* The SETLOCAL() macro must not DECREF the local variable in-place and
559 then store the new value; it must copy the old value to a temporary
560 value, then store the new value, and then DECREF the temporary value.
561 This is because it is possible that during the DECREF the frame is
562 accessed by other code (e.g. a __del__ method or gc.collect()) and the
563 variable would be pointing to already-freed memory. */
564 #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
565 GETLOCAL(i) = value; \
566 Py_XDECREF(tmp); } while (0)
568 /* Start of code */
570 if (f == NULL)
571 return NULL;
573 #ifdef USE_STACKCHECK
574 if (tstate->recursion_depth%10 == 0 && PyOS_CheckStack()) {
575 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
576 return NULL;
578 #endif
580 /* push frame */
581 if (++tstate->recursion_depth > recursion_limit) {
582 --tstate->recursion_depth;
583 PyErr_SetString(PyExc_RuntimeError,
584 "maximum recursion depth exceeded");
585 tstate->frame = f->f_back;
586 return NULL;
589 tstate->frame = f;
590 co = f->f_code;
591 fastlocals = f->f_localsplus;
592 freevars = f->f_localsplus + f->f_nlocals;
593 _PyCode_GETCODEPTR(co, &first_instr);
594 next_instr = first_instr + f->f_lasti;
595 stack_pointer = f->f_stacktop;
596 assert(stack_pointer != NULL);
597 f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
599 if (tstate->use_tracing) {
600 if (tstate->c_tracefunc != NULL) {
601 /* tstate->c_tracefunc, if defined, is a
602 function that will be called on *every* entry
603 to a code block. Its return value, if not
604 None, is a function that will be called at
605 the start of each executed line of code.
606 (Actually, the function must return itself
607 in order to continue tracing.) The trace
608 functions are called with three arguments:
609 a pointer to the current frame, a string
610 indicating why the function is called, and
611 an argument which depends on the situation.
612 The global trace function is also called
613 whenever an exception is detected. */
614 if (call_trace(tstate->c_tracefunc, tstate->c_traceobj,
615 f, PyTrace_CALL, Py_None)) {
616 /* Trace function raised an error */
617 return NULL;
620 if (tstate->c_profilefunc != NULL) {
621 /* Similar for c_profilefunc, except it needn't
622 return itself and isn't called for "line" events */
623 if (call_trace(tstate->c_profilefunc,
624 tstate->c_profileobj,
625 f, PyTrace_CALL, Py_None)) {
626 /* Profile function raised an error */
627 return NULL;
632 #ifdef LLTRACE
633 lltrace = PyDict_GetItemString(f->f_globals,"__lltrace__") != NULL;
634 #endif
635 #if defined(Py_DEBUG) || defined(LLTRACE)
636 filename = PyString_AsString(co->co_filename);
637 #endif
639 why = WHY_NOT;
640 err = 0;
641 x = Py_None; /* Not a reference, just anything non-NULL */
642 w = NULL;
644 for (;;) {
645 assert(stack_pointer >= f->f_valuestack); /* else underflow */
646 assert(STACK_LEVEL() <= f->f_stacksize); /* else overflow */
647 /* Do periodic things. Doing this every time through
648 the loop would add too much overhead, so we do it
649 only every Nth instruction. We also do it if
650 ``things_to_do'' is set, i.e. when an asynchronous
651 event needs attention (e.g. a signal handler or
652 async I/O handler); see Py_AddPendingCall() and
653 Py_MakePendingCalls() above. */
655 if (things_to_do || --tstate->ticker < 0) {
656 tstate->ticker = tstate->interp->checkinterval;
657 if (things_to_do) {
658 if (Py_MakePendingCalls() < 0) {
659 why = WHY_EXCEPTION;
660 goto on_error;
663 #if !defined(HAVE_SIGNAL_H) || defined(macintosh)
664 /* If we have true signals, the signal handler
665 will call Py_AddPendingCall() so we don't
666 have to call sigcheck(). On the Mac and
667 DOS, alas, we have to call it. */
668 if (PyErr_CheckSignals()) {
669 why = WHY_EXCEPTION;
670 goto on_error;
672 #endif
674 #ifdef WITH_THREAD
675 if (interpreter_lock) {
676 /* Give another thread a chance */
678 if (PyThreadState_Swap(NULL) != tstate)
679 Py_FatalError("ceval: tstate mix-up");
680 PyThread_release_lock(interpreter_lock);
682 /* Other threads may run now */
684 PyThread_acquire_lock(interpreter_lock, 1);
685 if (PyThreadState_Swap(tstate) != NULL)
686 Py_FatalError("ceval: orphan tstate");
688 #endif
691 /* Extract opcode and argument */
693 #if defined(Py_DEBUG) || defined(LLTRACE)
694 f->f_lasti = INSTR_OFFSET();
695 #endif
697 opcode = NEXTOP();
698 if (HAS_ARG(opcode))
699 oparg = NEXTARG();
700 dispatch_opcode:
701 #ifdef DYNAMIC_EXECUTION_PROFILE
702 #ifdef DXPAIRS
703 dxpairs[lastopcode][opcode]++;
704 lastopcode = opcode;
705 #endif
706 dxp[opcode]++;
707 #endif
709 #ifdef LLTRACE
710 /* Instruction tracing */
712 if (lltrace) {
713 if (HAS_ARG(opcode)) {
714 printf("%d: %d, %d\n",
715 (int) (INSTR_OFFSET() - 3),
716 opcode, oparg);
718 else {
719 printf("%d: %d\n",
720 (int) (INSTR_OFFSET() - 1), opcode);
723 #endif
724 /* Main switch on opcode */
726 switch (opcode) {
728 /* BEWARE!
729 It is essential that any operation that fails sets either
730 x to NULL, err to nonzero, or why to anything but WHY_NOT,
731 and that no operation that succeeds does this! */
733 /* case STOP_CODE: this is an error! */
735 case POP_TOP:
736 v = POP();
737 Py_DECREF(v);
738 continue;
740 case ROT_TWO:
741 v = POP();
742 w = POP();
743 PUSH(v);
744 PUSH(w);
745 continue;
747 case ROT_THREE:
748 v = POP();
749 w = POP();
750 x = POP();
751 PUSH(v);
752 PUSH(x);
753 PUSH(w);
754 continue;
756 case ROT_FOUR:
757 u = POP();
758 v = POP();
759 w = POP();
760 x = POP();
761 PUSH(u);
762 PUSH(x);
763 PUSH(w);
764 PUSH(v);
765 continue;
767 case DUP_TOP:
768 v = TOP();
769 Py_INCREF(v);
770 PUSH(v);
771 continue;
773 case DUP_TOPX:
774 switch (oparg) {
775 case 1:
776 x = TOP();
777 Py_INCREF(x);
778 PUSH(x);
779 continue;
780 case 2:
781 x = POP();
782 Py_INCREF(x);
783 w = TOP();
784 Py_INCREF(w);
785 PUSH(x);
786 PUSH(w);
787 PUSH(x);
788 continue;
789 case 3:
790 x = POP();
791 Py_INCREF(x);
792 w = POP();
793 Py_INCREF(w);
794 v = TOP();
795 Py_INCREF(v);
796 PUSH(w);
797 PUSH(x);
798 PUSH(v);
799 PUSH(w);
800 PUSH(x);
801 continue;
802 case 4:
803 x = POP();
804 Py_INCREF(x);
805 w = POP();
806 Py_INCREF(w);
807 v = POP();
808 Py_INCREF(v);
809 u = TOP();
810 Py_INCREF(u);
811 PUSH(v);
812 PUSH(w);
813 PUSH(x);
814 PUSH(u);
815 PUSH(v);
816 PUSH(w);
817 PUSH(x);
818 continue;
819 case 5:
820 x = POP();
821 Py_INCREF(x);
822 w = POP();
823 Py_INCREF(w);
824 v = POP();
825 Py_INCREF(v);
826 u = POP();
827 Py_INCREF(u);
828 t = TOP();
829 Py_INCREF(t);
830 PUSH(u);
831 PUSH(v);
832 PUSH(w);
833 PUSH(x);
834 PUSH(t);
835 PUSH(u);
836 PUSH(v);
837 PUSH(w);
838 PUSH(x);
839 continue;
840 default:
841 Py_FatalError("invalid argument to DUP_TOPX"
842 " (bytecode corruption?)");
844 break;
846 case UNARY_POSITIVE:
847 v = POP();
848 x = PyNumber_Positive(v);
849 Py_DECREF(v);
850 PUSH(x);
851 if (x != NULL) continue;
852 break;
854 case UNARY_NEGATIVE:
855 v = POP();
856 x = PyNumber_Negative(v);
857 Py_DECREF(v);
858 PUSH(x);
859 if (x != NULL) continue;
860 break;
862 case UNARY_NOT:
863 v = POP();
864 err = PyObject_IsTrue(v);
865 Py_DECREF(v);
866 if (err == 0) {
867 Py_INCREF(Py_True);
868 PUSH(Py_True);
869 continue;
871 else if (err > 0) {
872 Py_INCREF(Py_False);
873 PUSH(Py_False);
874 err = 0;
875 continue;
877 break;
879 case UNARY_CONVERT:
880 v = POP();
881 x = PyObject_Repr(v);
882 Py_DECREF(v);
883 PUSH(x);
884 if (x != NULL) continue;
885 break;
887 case UNARY_INVERT:
888 v = POP();
889 x = PyNumber_Invert(v);
890 Py_DECREF(v);
891 PUSH(x);
892 if (x != NULL) continue;
893 break;
895 case BINARY_POWER:
896 w = POP();
897 v = POP();
898 x = PyNumber_Power(v, w, Py_None);
899 Py_DECREF(v);
900 Py_DECREF(w);
901 PUSH(x);
902 if (x != NULL) continue;
903 break;
905 case BINARY_MULTIPLY:
906 w = POP();
907 v = POP();
908 x = PyNumber_Multiply(v, w);
909 Py_DECREF(v);
910 Py_DECREF(w);
911 PUSH(x);
912 if (x != NULL) continue;
913 break;
915 case BINARY_DIVIDE:
916 if (!_Py_QnewFlag) {
917 w = POP();
918 v = POP();
919 x = PyNumber_Divide(v, w);
920 Py_DECREF(v);
921 Py_DECREF(w);
922 PUSH(x);
923 if (x != NULL) continue;
924 break;
926 /* -Qnew is in effect: fall through to
927 BINARY_TRUE_DIVIDE */
928 case BINARY_TRUE_DIVIDE:
929 w = POP();
930 v = POP();
931 x = PyNumber_TrueDivide(v, w);
932 Py_DECREF(v);
933 Py_DECREF(w);
934 PUSH(x);
935 if (x != NULL) continue;
936 break;
938 case BINARY_FLOOR_DIVIDE:
939 w = POP();
940 v = POP();
941 x = PyNumber_FloorDivide(v, w);
942 Py_DECREF(v);
943 Py_DECREF(w);
944 PUSH(x);
945 if (x != NULL) continue;
946 break;
948 case BINARY_MODULO:
949 w = POP();
950 v = POP();
951 x = PyNumber_Remainder(v, w);
952 Py_DECREF(v);
953 Py_DECREF(w);
954 PUSH(x);
955 if (x != NULL) continue;
956 break;
958 case BINARY_ADD:
959 w = POP();
960 v = POP();
961 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
962 /* INLINE: int + int */
963 register long a, b, i;
964 a = PyInt_AS_LONG(v);
965 b = PyInt_AS_LONG(w);
966 i = a + b;
967 if ((i^a) < 0 && (i^b) < 0)
968 goto slow_add;
969 x = PyInt_FromLong(i);
971 else {
972 slow_add:
973 x = PyNumber_Add(v, w);
975 Py_DECREF(v);
976 Py_DECREF(w);
977 PUSH(x);
978 if (x != NULL) continue;
979 break;
981 case BINARY_SUBTRACT:
982 w = POP();
983 v = POP();
984 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
985 /* INLINE: int - int */
986 register long a, b, i;
987 a = PyInt_AS_LONG(v);
988 b = PyInt_AS_LONG(w);
989 i = a - b;
990 if ((i^a) < 0 && (i^~b) < 0)
991 goto slow_sub;
992 x = PyInt_FromLong(i);
994 else {
995 slow_sub:
996 x = PyNumber_Subtract(v, w);
998 Py_DECREF(v);
999 Py_DECREF(w);
1000 PUSH(x);
1001 if (x != NULL) continue;
1002 break;
1004 case BINARY_SUBSCR:
1005 w = POP();
1006 v = POP();
1007 if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
1008 /* INLINE: list[int] */
1009 long i = PyInt_AsLong(w);
1010 if (i < 0)
1011 i += PyList_GET_SIZE(v);
1012 if (i < 0 ||
1013 i >= PyList_GET_SIZE(v)) {
1014 PyErr_SetString(PyExc_IndexError,
1015 "list index out of range");
1016 x = NULL;
1018 else {
1019 x = PyList_GET_ITEM(v, i);
1020 Py_INCREF(x);
1023 else
1024 x = PyObject_GetItem(v, w);
1025 Py_DECREF(v);
1026 Py_DECREF(w);
1027 PUSH(x);
1028 if (x != NULL) continue;
1029 break;
1031 case BINARY_LSHIFT:
1032 w = POP();
1033 v = POP();
1034 x = PyNumber_Lshift(v, w);
1035 Py_DECREF(v);
1036 Py_DECREF(w);
1037 PUSH(x);
1038 if (x != NULL) continue;
1039 break;
1041 case BINARY_RSHIFT:
1042 w = POP();
1043 v = POP();
1044 x = PyNumber_Rshift(v, w);
1045 Py_DECREF(v);
1046 Py_DECREF(w);
1047 PUSH(x);
1048 if (x != NULL) continue;
1049 break;
1051 case BINARY_AND:
1052 w = POP();
1053 v = POP();
1054 x = PyNumber_And(v, w);
1055 Py_DECREF(v);
1056 Py_DECREF(w);
1057 PUSH(x);
1058 if (x != NULL) continue;
1059 break;
1061 case BINARY_XOR:
1062 w = POP();
1063 v = POP();
1064 x = PyNumber_Xor(v, w);
1065 Py_DECREF(v);
1066 Py_DECREF(w);
1067 PUSH(x);
1068 if (x != NULL) continue;
1069 break;
1071 case BINARY_OR:
1072 w = POP();
1073 v = POP();
1074 x = PyNumber_Or(v, w);
1075 Py_DECREF(v);
1076 Py_DECREF(w);
1077 PUSH(x);
1078 if (x != NULL) continue;
1079 break;
1081 case INPLACE_POWER:
1082 w = POP();
1083 v = POP();
1084 x = PyNumber_InPlacePower(v, w, Py_None);
1085 Py_DECREF(v);
1086 Py_DECREF(w);
1087 PUSH(x);
1088 if (x != NULL) continue;
1089 break;
1091 case INPLACE_MULTIPLY:
1092 w = POP();
1093 v = POP();
1094 x = PyNumber_InPlaceMultiply(v, w);
1095 Py_DECREF(v);
1096 Py_DECREF(w);
1097 PUSH(x);
1098 if (x != NULL) continue;
1099 break;
1101 case INPLACE_DIVIDE:
1102 if (!_Py_QnewFlag) {
1103 w = POP();
1104 v = POP();
1105 x = PyNumber_InPlaceDivide(v, w);
1106 Py_DECREF(v);
1107 Py_DECREF(w);
1108 PUSH(x);
1109 if (x != NULL) continue;
1110 break;
1112 /* -Qnew is in effect: fall through to
1113 INPLACE_TRUE_DIVIDE */
1114 case INPLACE_TRUE_DIVIDE:
1115 w = POP();
1116 v = POP();
1117 x = PyNumber_InPlaceTrueDivide(v, w);
1118 Py_DECREF(v);
1119 Py_DECREF(w);
1120 PUSH(x);
1121 if (x != NULL) continue;
1122 break;
1124 case INPLACE_FLOOR_DIVIDE:
1125 w = POP();
1126 v = POP();
1127 x = PyNumber_InPlaceFloorDivide(v, w);
1128 Py_DECREF(v);
1129 Py_DECREF(w);
1130 PUSH(x);
1131 if (x != NULL) continue;
1132 break;
1134 case INPLACE_MODULO:
1135 w = POP();
1136 v = POP();
1137 x = PyNumber_InPlaceRemainder(v, w);
1138 Py_DECREF(v);
1139 Py_DECREF(w);
1140 PUSH(x);
1141 if (x != NULL) continue;
1142 break;
1144 case INPLACE_ADD:
1145 w = POP();
1146 v = POP();
1147 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1148 /* INLINE: int + int */
1149 register long a, b, i;
1150 a = PyInt_AS_LONG(v);
1151 b = PyInt_AS_LONG(w);
1152 i = a + b;
1153 if ((i^a) < 0 && (i^b) < 0)
1154 goto slow_iadd;
1155 x = PyInt_FromLong(i);
1157 else {
1158 slow_iadd:
1159 x = PyNumber_InPlaceAdd(v, w);
1161 Py_DECREF(v);
1162 Py_DECREF(w);
1163 PUSH(x);
1164 if (x != NULL) continue;
1165 break;
1167 case INPLACE_SUBTRACT:
1168 w = POP();
1169 v = POP();
1170 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1171 /* INLINE: int - int */
1172 register long a, b, i;
1173 a = PyInt_AS_LONG(v);
1174 b = PyInt_AS_LONG(w);
1175 i = a - b;
1176 if ((i^a) < 0 && (i^~b) < 0)
1177 goto slow_isub;
1178 x = PyInt_FromLong(i);
1180 else {
1181 slow_isub:
1182 x = PyNumber_InPlaceSubtract(v, w);
1184 Py_DECREF(v);
1185 Py_DECREF(w);
1186 PUSH(x);
1187 if (x != NULL) continue;
1188 break;
1190 case INPLACE_LSHIFT:
1191 w = POP();
1192 v = POP();
1193 x = PyNumber_InPlaceLshift(v, w);
1194 Py_DECREF(v);
1195 Py_DECREF(w);
1196 PUSH(x);
1197 if (x != NULL) continue;
1198 break;
1200 case INPLACE_RSHIFT:
1201 w = POP();
1202 v = POP();
1203 x = PyNumber_InPlaceRshift(v, w);
1204 Py_DECREF(v);
1205 Py_DECREF(w);
1206 PUSH(x);
1207 if (x != NULL) continue;
1208 break;
1210 case INPLACE_AND:
1211 w = POP();
1212 v = POP();
1213 x = PyNumber_InPlaceAnd(v, w);
1214 Py_DECREF(v);
1215 Py_DECREF(w);
1216 PUSH(x);
1217 if (x != NULL) continue;
1218 break;
1220 case INPLACE_XOR:
1221 w = POP();
1222 v = POP();
1223 x = PyNumber_InPlaceXor(v, w);
1224 Py_DECREF(v);
1225 Py_DECREF(w);
1226 PUSH(x);
1227 if (x != NULL) continue;
1228 break;
1230 case INPLACE_OR:
1231 w = POP();
1232 v = POP();
1233 x = PyNumber_InPlaceOr(v, w);
1234 Py_DECREF(v);
1235 Py_DECREF(w);
1236 PUSH(x);
1237 if (x != NULL) continue;
1238 break;
1240 case SLICE+0:
1241 case SLICE+1:
1242 case SLICE+2:
1243 case SLICE+3:
1244 if ((opcode-SLICE) & 2)
1245 w = POP();
1246 else
1247 w = NULL;
1248 if ((opcode-SLICE) & 1)
1249 v = POP();
1250 else
1251 v = NULL;
1252 u = POP();
1253 x = apply_slice(u, v, w);
1254 Py_DECREF(u);
1255 Py_XDECREF(v);
1256 Py_XDECREF(w);
1257 PUSH(x);
1258 if (x != NULL) continue;
1259 break;
1261 case STORE_SLICE+0:
1262 case STORE_SLICE+1:
1263 case STORE_SLICE+2:
1264 case STORE_SLICE+3:
1265 if ((opcode-STORE_SLICE) & 2)
1266 w = POP();
1267 else
1268 w = NULL;
1269 if ((opcode-STORE_SLICE) & 1)
1270 v = POP();
1271 else
1272 v = NULL;
1273 u = POP();
1274 t = POP();
1275 err = assign_slice(u, v, w, t); /* u[v:w] = t */
1276 Py_DECREF(t);
1277 Py_DECREF(u);
1278 Py_XDECREF(v);
1279 Py_XDECREF(w);
1280 if (err == 0) continue;
1281 break;
1283 case DELETE_SLICE+0:
1284 case DELETE_SLICE+1:
1285 case DELETE_SLICE+2:
1286 case DELETE_SLICE+3:
1287 if ((opcode-DELETE_SLICE) & 2)
1288 w = POP();
1289 else
1290 w = NULL;
1291 if ((opcode-DELETE_SLICE) & 1)
1292 v = POP();
1293 else
1294 v = NULL;
1295 u = POP();
1296 err = assign_slice(u, v, w, (PyObject *)NULL);
1297 /* del u[v:w] */
1298 Py_DECREF(u);
1299 Py_XDECREF(v);
1300 Py_XDECREF(w);
1301 if (err == 0) continue;
1302 break;
1304 case STORE_SUBSCR:
1305 w = POP();
1306 v = POP();
1307 u = POP();
1308 /* v[w] = u */
1309 err = PyObject_SetItem(v, w, u);
1310 Py_DECREF(u);
1311 Py_DECREF(v);
1312 Py_DECREF(w);
1313 if (err == 0) continue;
1314 break;
1316 case DELETE_SUBSCR:
1317 w = POP();
1318 v = POP();
1319 /* del v[w] */
1320 err = PyObject_DelItem(v, w);
1321 Py_DECREF(v);
1322 Py_DECREF(w);
1323 if (err == 0) continue;
1324 break;
1326 case PRINT_EXPR:
1327 v = POP();
1328 w = PySys_GetObject("displayhook");
1329 if (w == NULL) {
1330 PyErr_SetString(PyExc_RuntimeError,
1331 "lost sys.displayhook");
1332 err = -1;
1333 x = NULL;
1335 if (err == 0) {
1336 x = Py_BuildValue("(O)", v);
1337 if (x == NULL)
1338 err = -1;
1340 if (err == 0) {
1341 w = PyEval_CallObject(w, x);
1342 Py_XDECREF(w);
1343 if (w == NULL)
1344 err = -1;
1346 Py_DECREF(v);
1347 Py_XDECREF(x);
1348 break;
1350 case PRINT_ITEM_TO:
1351 w = stream = POP();
1352 /* fall through to PRINT_ITEM */
1354 case PRINT_ITEM:
1355 v = POP();
1356 if (stream == NULL || stream == Py_None) {
1357 w = PySys_GetObject("stdout");
1358 if (w == NULL) {
1359 PyErr_SetString(PyExc_RuntimeError,
1360 "lost sys.stdout");
1361 err = -1;
1364 if (w != NULL && PyFile_SoftSpace(w, 1))
1365 err = PyFile_WriteString(" ", w);
1366 if (err == 0)
1367 err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
1368 if (err == 0) {
1369 /* XXX move into writeobject() ? */
1370 if (PyString_Check(v)) {
1371 char *s = PyString_AS_STRING(v);
1372 int len = PyString_GET_SIZE(v);
1373 if (len > 0 &&
1374 isspace(Py_CHARMASK(s[len-1])) &&
1375 s[len-1] != ' ')
1376 PyFile_SoftSpace(w, 0);
1378 #ifdef Py_USING_UNICODE
1379 else if (PyUnicode_Check(v)) {
1380 Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
1381 int len = PyUnicode_GET_SIZE(v);
1382 if (len > 0 &&
1383 Py_UNICODE_ISSPACE(s[len-1]) &&
1384 s[len-1] != ' ')
1385 PyFile_SoftSpace(w, 0);
1387 #endif
1389 Py_DECREF(v);
1390 Py_XDECREF(stream);
1391 stream = NULL;
1392 if (err == 0)
1393 continue;
1394 break;
1396 case PRINT_NEWLINE_TO:
1397 w = stream = POP();
1398 /* fall through to PRINT_NEWLINE */
1400 case PRINT_NEWLINE:
1401 if (stream == NULL || stream == Py_None) {
1402 w = PySys_GetObject("stdout");
1403 if (w == NULL)
1404 PyErr_SetString(PyExc_RuntimeError,
1405 "lost sys.stdout");
1407 if (w != NULL) {
1408 err = PyFile_WriteString("\n", w);
1409 if (err == 0)
1410 PyFile_SoftSpace(w, 0);
1412 Py_XDECREF(stream);
1413 stream = NULL;
1414 break;
1417 #ifdef CASE_TOO_BIG
1418 default: switch (opcode) {
1419 #endif
1420 case BREAK_LOOP:
1421 why = WHY_BREAK;
1422 break;
1424 case CONTINUE_LOOP:
1425 retval = PyInt_FromLong(oparg);
1426 why = WHY_CONTINUE;
1427 break;
1429 case RAISE_VARARGS:
1430 u = v = w = NULL;
1431 switch (oparg) {
1432 case 3:
1433 u = POP(); /* traceback */
1434 /* Fallthrough */
1435 case 2:
1436 v = POP(); /* value */
1437 /* Fallthrough */
1438 case 1:
1439 w = POP(); /* exc */
1440 case 0: /* Fallthrough */
1441 why = do_raise(w, v, u);
1442 break;
1443 default:
1444 PyErr_SetString(PyExc_SystemError,
1445 "bad RAISE_VARARGS oparg");
1446 why = WHY_EXCEPTION;
1447 break;
1449 break;
1451 case LOAD_LOCALS:
1452 if ((x = f->f_locals) == NULL) {
1453 PyErr_SetString(PyExc_SystemError,
1454 "no locals");
1455 break;
1457 Py_INCREF(x);
1458 PUSH(x);
1459 break;
1461 case RETURN_VALUE:
1462 retval = POP();
1463 why = WHY_RETURN;
1464 break;
1466 case YIELD_VALUE:
1467 retval = POP();
1468 f->f_stacktop = stack_pointer;
1469 f->f_lasti = INSTR_OFFSET();
1470 why = WHY_YIELD;
1471 break;
1474 case EXEC_STMT:
1475 w = POP();
1476 v = POP();
1477 u = POP();
1478 err = exec_statement(f, u, v, w);
1479 Py_DECREF(u);
1480 Py_DECREF(v);
1481 Py_DECREF(w);
1482 break;
1484 case POP_BLOCK:
1486 PyTryBlock *b = PyFrame_BlockPop(f);
1487 while (STACK_LEVEL() > b->b_level) {
1488 v = POP();
1489 Py_DECREF(v);
1492 break;
1494 case END_FINALLY:
1495 v = POP();
1496 if (PyInt_Check(v)) {
1497 why = (enum why_code) PyInt_AsLong(v);
1498 if (why == WHY_RETURN ||
1499 why == WHY_YIELD ||
1500 why == CONTINUE_LOOP)
1501 retval = POP();
1503 else if (PyString_Check(v) || PyClass_Check(v)) {
1504 w = POP();
1505 u = POP();
1506 PyErr_Restore(v, w, u);
1507 why = WHY_RERAISE;
1508 break;
1510 else if (v != Py_None) {
1511 PyErr_SetString(PyExc_SystemError,
1512 "'finally' pops bad exception");
1513 why = WHY_EXCEPTION;
1515 Py_DECREF(v);
1516 break;
1518 case BUILD_CLASS:
1519 u = POP();
1520 v = POP();
1521 w = POP();
1522 x = build_class(u, v, w);
1523 PUSH(x);
1524 Py_DECREF(u);
1525 Py_DECREF(v);
1526 Py_DECREF(w);
1527 break;
1529 case STORE_NAME:
1530 w = GETNAMEV(oparg);
1531 v = POP();
1532 if ((x = f->f_locals) == NULL) {
1533 PyErr_Format(PyExc_SystemError,
1534 "no locals found when storing %s",
1535 PyObject_REPR(w));
1536 break;
1538 err = PyDict_SetItem(x, w, v);
1539 Py_DECREF(v);
1540 break;
1542 case DELETE_NAME:
1543 w = GETNAMEV(oparg);
1544 if ((x = f->f_locals) == NULL) {
1545 PyErr_Format(PyExc_SystemError,
1546 "no locals when deleting %s",
1547 PyObject_REPR(w));
1548 break;
1550 if ((err = PyDict_DelItem(x, w)) != 0)
1551 format_exc_check_arg(PyExc_NameError,
1552 NAME_ERROR_MSG ,w);
1553 break;
1555 case UNPACK_SEQUENCE:
1556 v = POP();
1557 if (PyTuple_Check(v)) {
1558 if (PyTuple_Size(v) != oparg) {
1559 PyErr_SetString(PyExc_ValueError,
1560 "unpack tuple of wrong size");
1561 why = WHY_EXCEPTION;
1563 else {
1564 for (; --oparg >= 0; ) {
1565 w = PyTuple_GET_ITEM(v, oparg);
1566 Py_INCREF(w);
1567 PUSH(w);
1571 else if (PyList_Check(v)) {
1572 if (PyList_Size(v) != oparg) {
1573 PyErr_SetString(PyExc_ValueError,
1574 "unpack list of wrong size");
1575 why = WHY_EXCEPTION;
1577 else {
1578 for (; --oparg >= 0; ) {
1579 w = PyList_GET_ITEM(v, oparg);
1580 Py_INCREF(w);
1581 PUSH(w);
1585 else if (unpack_iterable(v, oparg,
1586 stack_pointer + oparg))
1587 stack_pointer += oparg;
1588 else {
1589 if (PyErr_ExceptionMatches(PyExc_TypeError))
1590 PyErr_SetString(PyExc_TypeError,
1591 "unpack non-sequence");
1592 why = WHY_EXCEPTION;
1594 Py_DECREF(v);
1595 break;
1597 case STORE_ATTR:
1598 w = GETNAMEV(oparg);
1599 v = POP();
1600 u = POP();
1601 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1602 Py_DECREF(v);
1603 Py_DECREF(u);
1604 break;
1606 case DELETE_ATTR:
1607 w = GETNAMEV(oparg);
1608 v = POP();
1609 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
1610 /* del v.w */
1611 Py_DECREF(v);
1612 break;
1614 case STORE_GLOBAL:
1615 w = GETNAMEV(oparg);
1616 v = POP();
1617 err = PyDict_SetItem(f->f_globals, w, v);
1618 Py_DECREF(v);
1619 break;
1621 case DELETE_GLOBAL:
1622 w = GETNAMEV(oparg);
1623 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
1624 format_exc_check_arg(
1625 PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
1626 break;
1628 case LOAD_CONST:
1629 x = GETCONST(oparg);
1630 Py_INCREF(x);
1631 PUSH(x);
1632 break;
1634 case LOAD_NAME:
1635 w = GETNAMEV(oparg);
1636 if ((x = f->f_locals) == NULL) {
1637 PyErr_Format(PyExc_SystemError,
1638 "no locals when loading %s",
1639 PyObject_REPR(w));
1640 break;
1642 x = PyDict_GetItem(x, w);
1643 if (x == NULL) {
1644 x = PyDict_GetItem(f->f_globals, w);
1645 if (x == NULL) {
1646 x = PyDict_GetItem(f->f_builtins, w);
1647 if (x == NULL) {
1648 format_exc_check_arg(
1649 PyExc_NameError,
1650 NAME_ERROR_MSG ,w);
1651 break;
1655 Py_INCREF(x);
1656 PUSH(x);
1657 break;
1659 case LOAD_GLOBAL:
1660 w = GETNAMEV(oparg);
1661 x = PyDict_GetItem(f->f_globals, w);
1662 if (x == NULL) {
1663 x = PyDict_GetItem(f->f_builtins, w);
1664 if (x == NULL) {
1665 format_exc_check_arg(
1666 PyExc_NameError,
1667 GLOBAL_NAME_ERROR_MSG ,w);
1668 break;
1671 Py_INCREF(x);
1672 PUSH(x);
1673 break;
1675 case LOAD_FAST:
1676 x = GETLOCAL(oparg);
1677 if (x == NULL) {
1678 format_exc_check_arg(
1679 PyExc_UnboundLocalError,
1680 UNBOUNDLOCAL_ERROR_MSG,
1681 PyTuple_GetItem(co->co_varnames, oparg)
1683 break;
1685 Py_INCREF(x);
1686 PUSH(x);
1687 if (x != NULL) continue;
1688 break;
1690 case STORE_FAST:
1691 v = POP();
1692 SETLOCAL(oparg, v);
1693 continue;
1695 case DELETE_FAST:
1696 x = GETLOCAL(oparg);
1697 if (x == NULL) {
1698 format_exc_check_arg(
1699 PyExc_UnboundLocalError,
1700 UNBOUNDLOCAL_ERROR_MSG,
1701 PyTuple_GetItem(co->co_varnames, oparg)
1703 break;
1705 SETLOCAL(oparg, NULL);
1706 continue;
1708 case LOAD_CLOSURE:
1709 x = freevars[oparg];
1710 Py_INCREF(x);
1711 PUSH(x);
1712 break;
1714 case LOAD_DEREF:
1715 x = freevars[oparg];
1716 w = PyCell_Get(x);
1717 if (w == NULL) {
1718 if (oparg < f->f_ncells) {
1719 v = PyTuple_GetItem(co->co_cellvars,
1720 oparg);
1721 format_exc_check_arg(
1722 PyExc_UnboundLocalError,
1723 UNBOUNDLOCAL_ERROR_MSG,
1725 } else {
1726 v = PyTuple_GetItem(
1727 co->co_freevars,
1728 oparg - f->f_ncells);
1729 format_exc_check_arg(
1730 PyExc_NameError,
1731 UNBOUNDFREE_ERROR_MSG,
1734 err = -1;
1735 break;
1737 PUSH(w);
1738 break;
1740 case STORE_DEREF:
1741 w = POP();
1742 x = freevars[oparg];
1743 PyCell_Set(x, w);
1744 Py_DECREF(w);
1745 continue;
1747 case BUILD_TUPLE:
1748 x = PyTuple_New(oparg);
1749 if (x != NULL) {
1750 for (; --oparg >= 0;) {
1751 w = POP();
1752 PyTuple_SET_ITEM(x, oparg, w);
1754 PUSH(x);
1755 continue;
1757 break;
1759 case BUILD_LIST:
1760 x = PyList_New(oparg);
1761 if (x != NULL) {
1762 for (; --oparg >= 0;) {
1763 w = POP();
1764 PyList_SET_ITEM(x, oparg, w);
1766 PUSH(x);
1767 continue;
1769 break;
1771 case BUILD_MAP:
1772 x = PyDict_New();
1773 PUSH(x);
1774 if (x != NULL) continue;
1775 break;
1777 case LOAD_ATTR:
1778 w = GETNAMEV(oparg);
1779 v = POP();
1780 x = PyObject_GetAttr(v, w);
1781 Py_DECREF(v);
1782 PUSH(x);
1783 if (x != NULL) continue;
1784 break;
1786 case COMPARE_OP:
1787 w = POP();
1788 v = POP();
1789 if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
1790 /* INLINE: cmp(int, int) */
1791 register long a, b;
1792 register int res;
1793 a = PyInt_AS_LONG(v);
1794 b = PyInt_AS_LONG(w);
1795 switch (oparg) {
1796 case LT: res = a < b; break;
1797 case LE: res = a <= b; break;
1798 case EQ: res = a == b; break;
1799 case NE: res = a != b; break;
1800 case GT: res = a > b; break;
1801 case GE: res = a >= b; break;
1802 case IS: res = v == w; break;
1803 case IS_NOT: res = v != w; break;
1804 default: goto slow_compare;
1806 x = res ? Py_True : Py_False;
1807 Py_INCREF(x);
1809 else {
1810 slow_compare:
1811 x = cmp_outcome(oparg, v, w);
1813 Py_DECREF(v);
1814 Py_DECREF(w);
1815 PUSH(x);
1816 if (x != NULL) continue;
1817 break;
1819 case IMPORT_NAME:
1820 w = GETNAMEV(oparg);
1821 x = PyDict_GetItemString(f->f_builtins, "__import__");
1822 if (x == NULL) {
1823 PyErr_SetString(PyExc_ImportError,
1824 "__import__ not found");
1825 break;
1827 u = POP();
1828 w = Py_BuildValue("(OOOO)",
1830 f->f_globals,
1831 f->f_locals == NULL ?
1832 Py_None : f->f_locals,
1834 Py_DECREF(u);
1835 if (w == NULL) {
1836 x = NULL;
1837 break;
1839 x = PyEval_CallObject(x, w);
1840 Py_DECREF(w);
1841 PUSH(x);
1842 if (x != NULL) continue;
1843 break;
1845 case IMPORT_STAR:
1846 v = POP();
1847 PyFrame_FastToLocals(f);
1848 if ((x = f->f_locals) == NULL) {
1849 PyErr_SetString(PyExc_SystemError,
1850 "no locals found during 'import *'");
1851 break;
1853 err = import_all_from(x, v);
1854 PyFrame_LocalsToFast(f, 0);
1855 Py_DECREF(v);
1856 if (err == 0) continue;
1857 break;
1859 case IMPORT_FROM:
1860 w = GETNAMEV(oparg);
1861 v = TOP();
1862 x = import_from(v, w);
1863 PUSH(x);
1864 if (x != NULL) continue;
1865 break;
1867 case JUMP_FORWARD:
1868 JUMPBY(oparg);
1869 continue;
1871 case JUMP_IF_FALSE:
1872 err = PyObject_IsTrue(TOP());
1873 if (err > 0)
1874 err = 0;
1875 else if (err == 0)
1876 JUMPBY(oparg);
1877 else
1878 break;
1879 continue;
1881 case JUMP_IF_TRUE:
1882 err = PyObject_IsTrue(TOP());
1883 if (err > 0) {
1884 err = 0;
1885 JUMPBY(oparg);
1887 else if (err == 0)
1889 else
1890 break;
1891 continue;
1893 case JUMP_ABSOLUTE:
1894 JUMPTO(oparg);
1895 continue;
1897 case GET_ITER:
1898 /* before: [obj]; after [getiter(obj)] */
1899 v = POP();
1900 x = PyObject_GetIter(v);
1901 Py_DECREF(v);
1902 if (x != NULL) {
1903 PUSH(x);
1904 continue;
1906 break;
1908 case FOR_ITER:
1909 /* before: [iter]; after: [iter, iter()] *or* [] */
1910 v = TOP();
1911 x = PyIter_Next(v);
1912 if (x != NULL) {
1913 PUSH(x);
1914 continue;
1916 if (!PyErr_Occurred()) {
1917 /* iterator ended normally */
1918 x = v = POP();
1919 Py_DECREF(v);
1920 JUMPBY(oparg);
1921 continue;
1923 break;
1925 case FOR_LOOP:
1926 /* for v in s: ...
1927 On entry: stack contains s, i.
1928 On exit: stack contains s, i+1, s[i];
1929 but if loop exhausted:
1930 s, i are popped, and we jump */
1931 w = POP(); /* Loop index */
1932 v = POP(); /* Sequence object */
1933 u = loop_subscript(v, w);
1934 if (u != NULL) {
1935 PUSH(v);
1936 x = PyInt_FromLong(PyInt_AsLong(w)+1);
1937 PUSH(x);
1938 Py_DECREF(w);
1939 PUSH(u);
1940 if (x != NULL) continue;
1942 else {
1943 Py_DECREF(v);
1944 Py_DECREF(w);
1945 /* A NULL can mean "s exhausted"
1946 but also an error: */
1947 if (PyErr_Occurred())
1948 why = WHY_EXCEPTION;
1949 else {
1950 JUMPBY(oparg);
1951 continue;
1954 break;
1956 case SETUP_LOOP:
1957 case SETUP_EXCEPT:
1958 case SETUP_FINALLY:
1959 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
1960 STACK_LEVEL());
1961 continue;
1963 case SET_LINENO:
1964 #ifdef LLTRACE
1965 if (lltrace)
1966 printf("--- %s:%d \n", filename, oparg);
1967 #endif
1968 f->f_lineno = oparg;
1969 if (tstate->c_tracefunc == NULL || tstate->tracing)
1970 continue;
1971 /* Trace each line of code reached */
1972 f->f_lasti = INSTR_OFFSET();
1973 /* Inline call_trace() for performance: */
1974 tstate->tracing++;
1975 tstate->use_tracing = 0;
1976 err = (tstate->c_tracefunc)(tstate->c_traceobj, f,
1977 PyTrace_LINE, Py_None);
1978 tstate->use_tracing = (tstate->c_tracefunc
1979 || tstate->c_profilefunc);
1980 tstate->tracing--;
1981 break;
1983 case CALL_FUNCTION:
1985 int na = oparg & 0xff;
1986 int nk = (oparg>>8) & 0xff;
1987 int n = na + 2 * nk;
1988 PyObject **pfunc = stack_pointer - n - 1;
1989 PyObject *func = *pfunc;
1990 f->f_lasti = INSTR_OFFSET() - 3; /* For tracing */
1992 /* Always dispatch PyCFunction first, because
1993 these are presumed to be the most frequent
1994 callable object.
1996 if (PyCFunction_Check(func)) {
1997 int flags = PyCFunction_GET_FLAGS(func);
1998 if (nk != 0 || (flags & METH_KEYWORDS))
1999 x = do_call(func, &stack_pointer,
2000 na, nk);
2001 else if (flags == METH_VARARGS) {
2002 PyObject *callargs;
2003 callargs = load_args(&stack_pointer, na);
2004 x = PyCFunction_Call(func, callargs, NULL);
2005 Py_XDECREF(callargs);
2006 } else
2007 x = fast_cfunction(func,
2008 &stack_pointer, na);
2009 } else {
2010 if (PyMethod_Check(func)
2011 && PyMethod_GET_SELF(func) != NULL) {
2012 /* optimize access to bound methods */
2013 PyObject *self = PyMethod_GET_SELF(func);
2014 Py_INCREF(self);
2015 func = PyMethod_GET_FUNCTION(func);
2016 Py_INCREF(func);
2017 Py_DECREF(*pfunc);
2018 *pfunc = self;
2019 na++;
2020 n++;
2021 } else
2022 Py_INCREF(func);
2023 if (PyFunction_Check(func)) {
2024 x = fast_function(func, &stack_pointer,
2025 n, na, nk);
2026 } else {
2027 x = do_call(func, &stack_pointer,
2028 na, nk);
2030 Py_DECREF(func);
2033 while (stack_pointer > pfunc) {
2034 w = POP();
2035 Py_DECREF(w);
2037 PUSH(x);
2038 if (x != NULL)
2039 continue;
2040 break;
2043 case CALL_FUNCTION_VAR:
2044 case CALL_FUNCTION_KW:
2045 case CALL_FUNCTION_VAR_KW:
2047 int na = oparg & 0xff;
2048 int nk = (oparg>>8) & 0xff;
2049 int flags = (opcode - CALL_FUNCTION) & 3;
2050 int n = na + 2 * nk;
2051 PyObject **pfunc, *func;
2052 if (flags & CALL_FLAG_VAR)
2053 n++;
2054 if (flags & CALL_FLAG_KW)
2055 n++;
2056 pfunc = stack_pointer - n - 1;
2057 func = *pfunc;
2058 f->f_lasti = INSTR_OFFSET() - 3; /* For tracing */
2060 if (PyMethod_Check(func)
2061 && PyMethod_GET_SELF(func) != NULL) {
2062 PyObject *self = PyMethod_GET_SELF(func);
2063 Py_INCREF(self);
2064 func = PyMethod_GET_FUNCTION(func);
2065 Py_INCREF(func);
2066 Py_DECREF(*pfunc);
2067 *pfunc = self;
2068 na++;
2069 n++;
2070 } else
2071 Py_INCREF(func);
2072 x = ext_do_call(func, &stack_pointer, flags, na, nk);
2073 Py_DECREF(func);
2075 while (stack_pointer > pfunc) {
2076 w = POP();
2077 Py_DECREF(w);
2079 PUSH(x);
2080 if (x != NULL)
2081 continue;
2082 break;
2085 case MAKE_FUNCTION:
2086 v = POP(); /* code object */
2087 x = PyFunction_New(v, f->f_globals);
2088 Py_DECREF(v);
2089 /* XXX Maybe this should be a separate opcode? */
2090 if (x != NULL && oparg > 0) {
2091 v = PyTuple_New(oparg);
2092 if (v == NULL) {
2093 Py_DECREF(x);
2094 x = NULL;
2095 break;
2097 while (--oparg >= 0) {
2098 w = POP();
2099 PyTuple_SET_ITEM(v, oparg, w);
2101 err = PyFunction_SetDefaults(x, v);
2102 Py_DECREF(v);
2104 PUSH(x);
2105 break;
2107 case MAKE_CLOSURE:
2109 int nfree;
2110 v = POP(); /* code object */
2111 x = PyFunction_New(v, f->f_globals);
2112 nfree = PyCode_GetNumFree((PyCodeObject *)v);
2113 Py_DECREF(v);
2114 /* XXX Maybe this should be a separate opcode? */
2115 if (x != NULL && nfree > 0) {
2116 v = PyTuple_New(nfree);
2117 if (v == NULL) {
2118 Py_DECREF(x);
2119 x = NULL;
2120 break;
2122 while (--nfree >= 0) {
2123 w = POP();
2124 PyTuple_SET_ITEM(v, nfree, w);
2126 err = PyFunction_SetClosure(x, v);
2127 Py_DECREF(v);
2129 if (x != NULL && oparg > 0) {
2130 v = PyTuple_New(oparg);
2131 if (v == NULL) {
2132 Py_DECREF(x);
2133 x = NULL;
2134 break;
2136 while (--oparg >= 0) {
2137 w = POP();
2138 PyTuple_SET_ITEM(v, oparg, w);
2140 err = PyFunction_SetDefaults(x, v);
2141 Py_DECREF(v);
2143 PUSH(x);
2144 break;
2147 case BUILD_SLICE:
2148 if (oparg == 3)
2149 w = POP();
2150 else
2151 w = NULL;
2152 v = POP();
2153 u = POP();
2154 x = PySlice_New(u, v, w);
2155 Py_DECREF(u);
2156 Py_DECREF(v);
2157 Py_XDECREF(w);
2158 PUSH(x);
2159 if (x != NULL) continue;
2160 break;
2162 case EXTENDED_ARG:
2163 opcode = NEXTOP();
2164 oparg = oparg<<16 | NEXTARG();
2165 goto dispatch_opcode;
2167 default:
2168 fprintf(stderr,
2169 "XXX lineno: %d, opcode: %d\n",
2170 f->f_lineno, opcode);
2171 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2172 why = WHY_EXCEPTION;
2173 break;
2175 #ifdef CASE_TOO_BIG
2177 #endif
2179 } /* switch */
2181 on_error:
2183 /* Quickly continue if no error occurred */
2185 if (why == WHY_NOT) {
2186 if (err == 0 && x != NULL) {
2187 #ifdef CHECKEXC
2188 /* This check is expensive! */
2189 if (PyErr_Occurred())
2190 fprintf(stderr,
2191 "XXX undetected error\n");
2192 else
2193 #endif
2194 continue; /* Normal, fast path */
2196 why = WHY_EXCEPTION;
2197 x = Py_None;
2198 err = 0;
2201 /* Double-check exception status */
2203 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2204 if (!PyErr_Occurred()) {
2205 PyErr_SetString(PyExc_SystemError,
2206 "error return without exception set");
2207 why = WHY_EXCEPTION;
2210 #ifdef CHECKEXC
2211 else {
2212 /* This check is expensive! */
2213 if (PyErr_Occurred()) {
2214 fprintf(stderr,
2215 "XXX undetected error (why=%d)\n",
2216 why);
2217 why = WHY_EXCEPTION;
2220 #endif
2222 /* Log traceback info if this is a real exception */
2224 if (why == WHY_EXCEPTION) {
2225 f->f_lasti = INSTR_OFFSET() - 1;
2226 if (HAS_ARG(opcode))
2227 f->f_lasti -= 2;
2228 PyTraceBack_Here(f);
2230 if (tstate->c_tracefunc != NULL)
2231 call_exc_trace(tstate->c_tracefunc,
2232 tstate->c_traceobj, f);
2235 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2237 if (why == WHY_RERAISE)
2238 why = WHY_EXCEPTION;
2240 /* Unwind stacks if a (pseudo) exception occurred */
2242 while (why != WHY_NOT && why != WHY_YIELD && f->f_iblock > 0) {
2243 PyTryBlock *b = PyFrame_BlockPop(f);
2245 if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
2246 /* For a continue inside a try block,
2247 don't pop the block for the loop. */
2248 PyFrame_BlockSetup(f, b->b_type, b->b_handler,
2249 b->b_level);
2250 why = WHY_NOT;
2251 JUMPTO(PyInt_AS_LONG(retval));
2252 Py_DECREF(retval);
2253 break;
2256 while (STACK_LEVEL() > b->b_level) {
2257 v = POP();
2258 Py_XDECREF(v);
2260 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2261 why = WHY_NOT;
2262 JUMPTO(b->b_handler);
2263 break;
2265 if (b->b_type == SETUP_FINALLY ||
2266 (b->b_type == SETUP_EXCEPT &&
2267 why == WHY_EXCEPTION)) {
2268 if (why == WHY_EXCEPTION) {
2269 PyObject *exc, *val, *tb;
2270 PyErr_Fetch(&exc, &val, &tb);
2271 if (val == NULL) {
2272 val = Py_None;
2273 Py_INCREF(val);
2275 /* Make the raw exception data
2276 available to the handler,
2277 so a program can emulate the
2278 Python main loop. Don't do
2279 this for 'finally'. */
2280 if (b->b_type == SETUP_EXCEPT) {
2281 PyErr_NormalizeException(
2282 &exc, &val, &tb);
2283 set_exc_info(tstate,
2284 exc, val, tb);
2286 if (tb == NULL) {
2287 Py_INCREF(Py_None);
2288 PUSH(Py_None);
2289 } else
2290 PUSH(tb);
2291 PUSH(val);
2292 PUSH(exc);
2294 else {
2295 if (why == WHY_RETURN ||
2296 why == CONTINUE_LOOP)
2297 PUSH(retval);
2298 v = PyInt_FromLong((long)why);
2299 PUSH(v);
2301 why = WHY_NOT;
2302 JUMPTO(b->b_handler);
2303 break;
2305 } /* unwind stack */
2307 /* End the loop if we still have an error (or return) */
2309 if (why != WHY_NOT)
2310 break;
2312 } /* main loop */
2314 if (why != WHY_YIELD) {
2315 /* Pop remaining stack entries -- but when yielding */
2316 while (!EMPTY()) {
2317 v = POP();
2318 Py_XDECREF(v);
2322 if (why != WHY_RETURN && why != WHY_YIELD)
2323 retval = NULL;
2325 if (tstate->use_tracing) {
2326 if (tstate->c_tracefunc
2327 && (why == WHY_RETURN || why == WHY_YIELD)) {
2328 if (call_trace(tstate->c_tracefunc,
2329 tstate->c_traceobj, f,
2330 PyTrace_RETURN, retval)) {
2331 Py_XDECREF(retval);
2332 retval = NULL;
2333 why = WHY_EXCEPTION;
2336 if (tstate->c_profilefunc) {
2337 if (why == WHY_EXCEPTION)
2338 call_trace_protected(tstate->c_profilefunc,
2339 tstate->c_profileobj, f,
2340 PyTrace_RETURN);
2341 else if (call_trace(tstate->c_profilefunc,
2342 tstate->c_profileobj, f,
2343 PyTrace_RETURN, retval)) {
2344 Py_XDECREF(retval);
2345 retval = NULL;
2346 why = WHY_EXCEPTION;
2351 reset_exc_info(tstate);
2353 /* pop frame */
2354 --tstate->recursion_depth;
2355 tstate->frame = f->f_back;
2357 return retval;
2360 PyObject *
2361 PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals,
2362 PyObject **args, int argcount, PyObject **kws, int kwcount,
2363 PyObject **defs, int defcount, PyObject *closure)
2365 register PyFrameObject *f;
2366 register PyObject *retval = NULL;
2367 register PyObject **fastlocals, **freevars;
2368 PyThreadState *tstate = PyThreadState_GET();
2369 PyObject *x, *u;
2371 if (globals == NULL) {
2372 PyErr_SetString(PyExc_SystemError,
2373 "PyEval_EvalCodeEx: NULL globals");
2374 return NULL;
2377 f = PyFrame_New(tstate, /*back*/
2378 co, /*code*/
2379 globals, locals);
2380 if (f == NULL)
2381 return NULL;
2383 fastlocals = f->f_localsplus;
2384 freevars = f->f_localsplus + f->f_nlocals;
2386 if (co->co_argcount > 0 ||
2387 co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
2388 int i;
2389 int n = argcount;
2390 PyObject *kwdict = NULL;
2391 if (co->co_flags & CO_VARKEYWORDS) {
2392 kwdict = PyDict_New();
2393 if (kwdict == NULL)
2394 goto fail;
2395 i = co->co_argcount;
2396 if (co->co_flags & CO_VARARGS)
2397 i++;
2398 SETLOCAL(i, kwdict);
2400 if (argcount > co->co_argcount) {
2401 if (!(co->co_flags & CO_VARARGS)) {
2402 PyErr_Format(PyExc_TypeError,
2403 "%.200s() takes %s %d "
2404 "%sargument%s (%d given)",
2405 PyString_AsString(co->co_name),
2406 defcount ? "at most" : "exactly",
2407 co->co_argcount,
2408 kwcount ? "non-keyword " : "",
2409 co->co_argcount == 1 ? "" : "s",
2410 argcount);
2411 goto fail;
2413 n = co->co_argcount;
2415 for (i = 0; i < n; i++) {
2416 x = args[i];
2417 Py_INCREF(x);
2418 SETLOCAL(i, x);
2420 if (co->co_flags & CO_VARARGS) {
2421 u = PyTuple_New(argcount - n);
2422 if (u == NULL)
2423 goto fail;
2424 SETLOCAL(co->co_argcount, u);
2425 for (i = n; i < argcount; i++) {
2426 x = args[i];
2427 Py_INCREF(x);
2428 PyTuple_SET_ITEM(u, i-n, x);
2431 for (i = 0; i < kwcount; i++) {
2432 PyObject *keyword = kws[2*i];
2433 PyObject *value = kws[2*i + 1];
2434 int j;
2435 if (keyword == NULL || !PyString_Check(keyword)) {
2436 PyErr_Format(PyExc_TypeError,
2437 "%.200s() keywords must be strings",
2438 PyString_AsString(co->co_name));
2439 goto fail;
2441 /* XXX slow -- speed up using dictionary? */
2442 for (j = 0; j < co->co_argcount; j++) {
2443 PyObject *nm = PyTuple_GET_ITEM(
2444 co->co_varnames, j);
2445 int cmp = PyObject_RichCompareBool(
2446 keyword, nm, Py_EQ);
2447 if (cmp > 0)
2448 break;
2449 else if (cmp < 0)
2450 goto fail;
2452 /* Check errors from Compare */
2453 if (PyErr_Occurred())
2454 goto fail;
2455 if (j >= co->co_argcount) {
2456 if (kwdict == NULL) {
2457 PyErr_Format(PyExc_TypeError,
2458 "%.200s() got an unexpected "
2459 "keyword argument '%.400s'",
2460 PyString_AsString(co->co_name),
2461 PyString_AsString(keyword));
2462 goto fail;
2464 PyDict_SetItem(kwdict, keyword, value);
2466 else {
2467 if (GETLOCAL(j) != NULL) {
2468 PyErr_Format(PyExc_TypeError,
2469 "%.200s() got multiple "
2470 "values for keyword "
2471 "argument '%.400s'",
2472 PyString_AsString(co->co_name),
2473 PyString_AsString(keyword));
2474 goto fail;
2476 Py_INCREF(value);
2477 SETLOCAL(j, value);
2480 if (argcount < co->co_argcount) {
2481 int m = co->co_argcount - defcount;
2482 for (i = argcount; i < m; i++) {
2483 if (GETLOCAL(i) == NULL) {
2484 PyErr_Format(PyExc_TypeError,
2485 "%.200s() takes %s %d "
2486 "%sargument%s (%d given)",
2487 PyString_AsString(co->co_name),
2488 ((co->co_flags & CO_VARARGS) ||
2489 defcount) ? "at least"
2490 : "exactly",
2491 m, kwcount ? "non-keyword " : "",
2492 m == 1 ? "" : "s", i);
2493 goto fail;
2496 if (n > m)
2497 i = n - m;
2498 else
2499 i = 0;
2500 for (; i < defcount; i++) {
2501 if (GETLOCAL(m+i) == NULL) {
2502 PyObject *def = defs[i];
2503 Py_INCREF(def);
2504 SETLOCAL(m+i, def);
2509 else {
2510 if (argcount > 0 || kwcount > 0) {
2511 PyErr_Format(PyExc_TypeError,
2512 "%.200s() takes no arguments (%d given)",
2513 PyString_AsString(co->co_name),
2514 argcount + kwcount);
2515 goto fail;
2518 /* Allocate and initialize storage for cell vars, and copy free
2519 vars into frame. This isn't too efficient right now. */
2520 if (f->f_ncells) {
2521 int i = 0, j = 0, nargs, found;
2522 char *cellname, *argname;
2523 PyObject *c;
2525 nargs = co->co_argcount;
2526 if (co->co_flags & CO_VARARGS)
2527 nargs++;
2528 if (co->co_flags & CO_VARKEYWORDS)
2529 nargs++;
2531 /* Check for cells that shadow args */
2532 for (i = 0; i < f->f_ncells && j < nargs; ++i) {
2533 cellname = PyString_AS_STRING(
2534 PyTuple_GET_ITEM(co->co_cellvars, i));
2535 found = 0;
2536 while (j < nargs) {
2537 argname = PyString_AS_STRING(
2538 PyTuple_GET_ITEM(co->co_varnames, j));
2539 if (strcmp(cellname, argname) == 0) {
2540 c = PyCell_New(GETLOCAL(j));
2541 if (c == NULL)
2542 goto fail;
2543 GETLOCAL(f->f_nlocals + i) = c;
2544 found = 1;
2545 break;
2547 j++;
2549 if (found == 0) {
2550 c = PyCell_New(NULL);
2551 if (c == NULL)
2552 goto fail;
2553 SETLOCAL(f->f_nlocals + i, c);
2556 /* Initialize any that are left */
2557 while (i < f->f_ncells) {
2558 c = PyCell_New(NULL);
2559 if (c == NULL)
2560 goto fail;
2561 SETLOCAL(f->f_nlocals + i, c);
2562 i++;
2565 if (f->f_nfreevars) {
2566 int i;
2567 for (i = 0; i < f->f_nfreevars; ++i) {
2568 PyObject *o = PyTuple_GET_ITEM(closure, i);
2569 Py_INCREF(o);
2570 freevars[f->f_ncells + i] = o;
2574 if (co->co_flags & CO_GENERATOR) {
2575 /* Don't need to keep the reference to f_back, it will be set
2576 * when the generator is resumed. */
2577 Py_XDECREF(f->f_back);
2578 f->f_back = NULL;
2580 /* Create a new generator that owns the ready to run frame
2581 * and return that as the value. */
2582 return gen_new(f);
2585 retval = eval_frame(f);
2587 fail: /* Jump here from prelude on failure */
2589 /* decref'ing the frame can cause __del__ methods to get invoked,
2590 which can call back into Python. While we're done with the
2591 current Python frame (f), the associated C stack is still in use,
2592 so recursion_depth must be boosted for the duration.
2594 assert(tstate != NULL);
2595 ++tstate->recursion_depth;
2596 Py_DECREF(f);
2597 --tstate->recursion_depth;
2598 return retval;
2602 static void
2603 set_exc_info(PyThreadState *tstate,
2604 PyObject *type, PyObject *value, PyObject *tb)
2606 PyFrameObject *frame;
2607 PyObject *tmp_type, *tmp_value, *tmp_tb;
2609 frame = tstate->frame;
2610 if (frame->f_exc_type == NULL) {
2611 /* This frame didn't catch an exception before */
2612 /* Save previous exception of this thread in this frame */
2613 if (tstate->exc_type == NULL) {
2614 Py_INCREF(Py_None);
2615 tstate->exc_type = Py_None;
2617 tmp_type = frame->f_exc_type;
2618 tmp_value = frame->f_exc_value;
2619 tmp_tb = frame->f_exc_traceback;
2620 Py_XINCREF(tstate->exc_type);
2621 Py_XINCREF(tstate->exc_value);
2622 Py_XINCREF(tstate->exc_traceback);
2623 frame->f_exc_type = tstate->exc_type;
2624 frame->f_exc_value = tstate->exc_value;
2625 frame->f_exc_traceback = tstate->exc_traceback;
2626 Py_XDECREF(tmp_type);
2627 Py_XDECREF(tmp_value);
2628 Py_XDECREF(tmp_tb);
2630 /* Set new exception for this thread */
2631 tmp_type = tstate->exc_type;
2632 tmp_value = tstate->exc_value;
2633 tmp_tb = tstate->exc_traceback;
2634 Py_XINCREF(type);
2635 Py_XINCREF(value);
2636 Py_XINCREF(tb);
2637 tstate->exc_type = type;
2638 tstate->exc_value = value;
2639 tstate->exc_traceback = tb;
2640 Py_XDECREF(tmp_type);
2641 Py_XDECREF(tmp_value);
2642 Py_XDECREF(tmp_tb);
2643 /* For b/w compatibility */
2644 PySys_SetObject("exc_type", type);
2645 PySys_SetObject("exc_value", value);
2646 PySys_SetObject("exc_traceback", tb);
2649 static void
2650 reset_exc_info(PyThreadState *tstate)
2652 PyFrameObject *frame;
2653 PyObject *tmp_type, *tmp_value, *tmp_tb;
2654 frame = tstate->frame;
2655 if (frame->f_exc_type != NULL) {
2656 /* This frame caught an exception */
2657 tmp_type = tstate->exc_type;
2658 tmp_value = tstate->exc_value;
2659 tmp_tb = tstate->exc_traceback;
2660 Py_XINCREF(frame->f_exc_type);
2661 Py_XINCREF(frame->f_exc_value);
2662 Py_XINCREF(frame->f_exc_traceback);
2663 tstate->exc_type = frame->f_exc_type;
2664 tstate->exc_value = frame->f_exc_value;
2665 tstate->exc_traceback = frame->f_exc_traceback;
2666 Py_XDECREF(tmp_type);
2667 Py_XDECREF(tmp_value);
2668 Py_XDECREF(tmp_tb);
2669 /* For b/w compatibility */
2670 PySys_SetObject("exc_type", frame->f_exc_type);
2671 PySys_SetObject("exc_value", frame->f_exc_value);
2672 PySys_SetObject("exc_traceback", frame->f_exc_traceback);
2674 tmp_type = frame->f_exc_type;
2675 tmp_value = frame->f_exc_value;
2676 tmp_tb = frame->f_exc_traceback;
2677 frame->f_exc_type = NULL;
2678 frame->f_exc_value = NULL;
2679 frame->f_exc_traceback = NULL;
2680 Py_XDECREF(tmp_type);
2681 Py_XDECREF(tmp_value);
2682 Py_XDECREF(tmp_tb);
2685 /* Logic for the raise statement (too complicated for inlining).
2686 This *consumes* a reference count to each of its arguments. */
2687 static enum why_code
2688 do_raise(PyObject *type, PyObject *value, PyObject *tb)
2690 if (type == NULL) {
2691 /* Reraise */
2692 PyThreadState *tstate = PyThreadState_Get();
2693 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
2694 value = tstate->exc_value;
2695 tb = tstate->exc_traceback;
2696 Py_XINCREF(type);
2697 Py_XINCREF(value);
2698 Py_XINCREF(tb);
2701 /* We support the following forms of raise:
2702 raise <class>, <classinstance>
2703 raise <class>, <argument tuple>
2704 raise <class>, None
2705 raise <class>, <argument>
2706 raise <classinstance>, None
2707 raise <string>, <object>
2708 raise <string>, None
2710 An omitted second argument is the same as None.
2712 In addition, raise <tuple>, <anything> is the same as
2713 raising the tuple's first item (and it better have one!);
2714 this rule is applied recursively.
2716 Finally, an optional third argument can be supplied, which
2717 gives the traceback to be substituted (useful when
2718 re-raising an exception after examining it). */
2720 /* First, check the traceback argument, replacing None with
2721 NULL. */
2722 if (tb == Py_None) {
2723 Py_DECREF(tb);
2724 tb = NULL;
2726 else if (tb != NULL && !PyTraceBack_Check(tb)) {
2727 PyErr_SetString(PyExc_TypeError,
2728 "raise: arg 3 must be a traceback or None");
2729 goto raise_error;
2732 /* Next, replace a missing value with None */
2733 if (value == NULL) {
2734 value = Py_None;
2735 Py_INCREF(value);
2738 /* Next, repeatedly, replace a tuple exception with its first item */
2739 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
2740 PyObject *tmp = type;
2741 type = PyTuple_GET_ITEM(type, 0);
2742 Py_INCREF(type);
2743 Py_DECREF(tmp);
2746 if (PyString_Check(type))
2749 else if (PyClass_Check(type))
2750 PyErr_NormalizeException(&type, &value, &tb);
2752 else if (PyInstance_Check(type)) {
2753 /* Raising an instance. The value should be a dummy. */
2754 if (value != Py_None) {
2755 PyErr_SetString(PyExc_TypeError,
2756 "instance exception may not have a separate value");
2757 goto raise_error;
2759 else {
2760 /* Normalize to raise <class>, <instance> */
2761 Py_DECREF(value);
2762 value = type;
2763 type = (PyObject*) ((PyInstanceObject*)type)->in_class;
2764 Py_INCREF(type);
2767 else {
2768 /* Not something you can raise. You get an exception
2769 anyway, just not what you specified :-) */
2770 PyErr_Format(PyExc_TypeError,
2771 "exceptions must be strings, classes, or "
2772 "instances, not %s", type->ob_type->tp_name);
2773 goto raise_error;
2775 PyErr_Restore(type, value, tb);
2776 if (tb == NULL)
2777 return WHY_EXCEPTION;
2778 else
2779 return WHY_RERAISE;
2780 raise_error:
2781 Py_XDECREF(value);
2782 Py_XDECREF(type);
2783 Py_XDECREF(tb);
2784 return WHY_EXCEPTION;
2787 /* Iterate v argcnt times and store the results on the stack (via decreasing
2788 sp). Return 1 for success, 0 if error. */
2790 static int
2791 unpack_iterable(PyObject *v, int argcnt, PyObject **sp)
2793 int i = 0;
2794 PyObject *it; /* iter(v) */
2795 PyObject *w;
2797 assert(v != NULL);
2799 it = PyObject_GetIter(v);
2800 if (it == NULL)
2801 goto Error;
2803 for (; i < argcnt; i++) {
2804 w = PyIter_Next(it);
2805 if (w == NULL) {
2806 /* Iterator done, via error or exhaustion. */
2807 if (!PyErr_Occurred()) {
2808 PyErr_Format(PyExc_ValueError,
2809 "need more than %d value%s to unpack",
2810 i, i == 1 ? "" : "s");
2812 goto Error;
2814 *--sp = w;
2817 /* We better have exhausted the iterator now. */
2818 w = PyIter_Next(it);
2819 if (w == NULL) {
2820 if (PyErr_Occurred())
2821 goto Error;
2822 Py_DECREF(it);
2823 return 1;
2825 Py_DECREF(w);
2826 PyErr_SetString(PyExc_ValueError, "too many values to unpack");
2827 /* fall through */
2828 Error:
2829 for (; i > 0; i--, sp++)
2830 Py_DECREF(*sp);
2831 Py_XDECREF(it);
2832 return 0;
2836 #ifdef LLTRACE
2837 static int
2838 prtrace(PyObject *v, char *str)
2840 printf("%s ", str);
2841 if (PyObject_Print(v, stdout, 0) != 0)
2842 PyErr_Clear(); /* Don't know what else to do */
2843 printf("\n");
2844 return 1;
2846 #endif
2848 static void
2849 call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
2851 PyObject *type, *value, *traceback, *arg;
2852 int err;
2853 PyErr_Fetch(&type, &value, &traceback);
2854 if (value == NULL) {
2855 value = Py_None;
2856 Py_INCREF(value);
2858 arg = Py_BuildValue("(OOO)", type, value, traceback);
2859 if (arg == NULL) {
2860 PyErr_Restore(type, value, traceback);
2861 return;
2863 err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
2864 Py_DECREF(arg);
2865 if (err == 0)
2866 PyErr_Restore(type, value, traceback);
2867 else {
2868 Py_XDECREF(type);
2869 Py_XDECREF(value);
2870 Py_XDECREF(traceback);
2874 static void
2875 call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
2876 int what)
2878 PyObject *type, *value, *traceback;
2879 int err;
2880 PyErr_Fetch(&type, &value, &traceback);
2881 err = call_trace(func, obj, frame, what, NULL);
2882 if (err == 0)
2883 PyErr_Restore(type, value, traceback);
2884 else {
2885 Py_XDECREF(type);
2886 Py_XDECREF(value);
2887 Py_XDECREF(traceback);
2891 static int
2892 call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
2893 int what, PyObject *arg)
2895 register PyThreadState *tstate = frame->f_tstate;
2896 int result;
2897 if (tstate->tracing)
2898 return 0;
2899 tstate->tracing++;
2900 tstate->use_tracing = 0;
2901 result = func(obj, frame, what, arg);
2902 tstate->use_tracing = ((tstate->c_tracefunc != NULL)
2903 || (tstate->c_profilefunc != NULL));
2904 tstate->tracing--;
2905 return result;
2908 void
2909 PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
2911 PyThreadState *tstate = PyThreadState_Get();
2912 PyObject *temp = tstate->c_profileobj;
2913 Py_XINCREF(arg);
2914 tstate->c_profilefunc = NULL;
2915 tstate->c_profileobj = NULL;
2916 tstate->use_tracing = tstate->c_tracefunc != NULL;
2917 Py_XDECREF(temp);
2918 tstate->c_profilefunc = func;
2919 tstate->c_profileobj = arg;
2920 tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
2923 void
2924 PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
2926 PyThreadState *tstate = PyThreadState_Get();
2927 PyObject *temp = tstate->c_traceobj;
2928 Py_XINCREF(arg);
2929 tstate->c_tracefunc = NULL;
2930 tstate->c_traceobj = NULL;
2931 tstate->use_tracing = tstate->c_profilefunc != NULL;
2932 Py_XDECREF(temp);
2933 tstate->c_tracefunc = func;
2934 tstate->c_traceobj = arg;
2935 tstate->use_tracing = ((func != NULL)
2936 || (tstate->c_profilefunc != NULL));
2939 PyObject *
2940 PyEval_GetBuiltins(void)
2942 PyThreadState *tstate = PyThreadState_Get();
2943 PyFrameObject *current_frame = tstate->frame;
2944 if (current_frame == NULL)
2945 return tstate->interp->builtins;
2946 else
2947 return current_frame->f_builtins;
2950 PyObject *
2951 PyEval_GetLocals(void)
2953 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2954 if (current_frame == NULL)
2955 return NULL;
2956 PyFrame_FastToLocals(current_frame);
2957 return current_frame->f_locals;
2960 PyObject *
2961 PyEval_GetGlobals(void)
2963 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2964 if (current_frame == NULL)
2965 return NULL;
2966 else
2967 return current_frame->f_globals;
2970 PyObject *
2971 PyEval_GetFrame(void)
2973 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2974 return (PyObject *)current_frame;
2978 PyEval_GetRestricted(void)
2980 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2981 return current_frame == NULL ? 0 : current_frame->f_restricted;
2985 PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
2987 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2988 int result = 0;
2990 if (current_frame != NULL) {
2991 const int codeflags = current_frame->f_code->co_flags;
2992 const int compilerflags = codeflags & PyCF_MASK;
2993 if (compilerflags) {
2994 result = 1;
2995 cf->cf_flags |= compilerflags;
2998 return result;
3002 Py_FlushLine(void)
3004 PyObject *f = PySys_GetObject("stdout");
3005 if (f == NULL)
3006 return 0;
3007 if (!PyFile_SoftSpace(f, 0))
3008 return 0;
3009 return PyFile_WriteString("\n", f);
3013 /* External interface to call any callable object.
3014 The arg must be a tuple or NULL. */
3016 #undef PyEval_CallObject
3017 /* for backward compatibility: export this interface */
3019 PyObject *
3020 PyEval_CallObject(PyObject *func, PyObject *arg)
3022 return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL);
3024 #define PyEval_CallObject(func,arg) \
3025 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
3027 PyObject *
3028 PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
3030 PyObject *result;
3032 if (arg == NULL)
3033 arg = PyTuple_New(0);
3034 else if (!PyTuple_Check(arg)) {
3035 PyErr_SetString(PyExc_TypeError,
3036 "argument list must be a tuple");
3037 return NULL;
3039 else
3040 Py_INCREF(arg);
3042 if (kw != NULL && !PyDict_Check(kw)) {
3043 PyErr_SetString(PyExc_TypeError,
3044 "keyword list must be a dictionary");
3045 Py_DECREF(arg);
3046 return NULL;
3049 result = PyObject_Call(func, arg, kw);
3050 Py_DECREF(arg);
3051 return result;
3054 char *
3055 PyEval_GetFuncName(PyObject *func)
3057 if (PyMethod_Check(func))
3058 return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
3059 else if (PyFunction_Check(func))
3060 return PyString_AsString(((PyFunctionObject*)func)->func_name);
3061 else if (PyCFunction_Check(func))
3062 return ((PyCFunctionObject*)func)->m_ml->ml_name;
3063 else if (PyClass_Check(func))
3064 return PyString_AsString(((PyClassObject*)func)->cl_name);
3065 else if (PyInstance_Check(func)) {
3066 return PyString_AsString(
3067 ((PyInstanceObject*)func)->in_class->cl_name);
3068 } else {
3069 return func->ob_type->tp_name;
3073 char *
3074 PyEval_GetFuncDesc(PyObject *func)
3076 if (PyMethod_Check(func))
3077 return "()";
3078 else if (PyFunction_Check(func))
3079 return "()";
3080 else if (PyCFunction_Check(func))
3081 return "()";
3082 else if (PyClass_Check(func))
3083 return " constructor";
3084 else if (PyInstance_Check(func)) {
3085 return " instance";
3086 } else {
3087 return " object";
3091 #define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
3093 /* The two fast_xxx() functions optimize calls for which no argument
3094 tuple is necessary; the objects are passed directly from the stack.
3095 fast_cfunction() is called for METH_OLDARGS functions.
3096 fast_function() is for functions with no special argument handling.
3099 static PyObject *
3100 fast_cfunction(PyObject *func, PyObject ***pp_stack, int na)
3102 PyCFunction meth = PyCFunction_GET_FUNCTION(func);
3103 PyObject *self = PyCFunction_GET_SELF(func);
3104 int flags = PyCFunction_GET_FLAGS(func);
3106 switch (flags) {
3107 case METH_OLDARGS:
3108 if (na == 0)
3109 return (*meth)(self, NULL);
3110 else if (na == 1) {
3111 PyObject *arg = EXT_POP(*pp_stack);
3112 PyObject *result = (*meth)(self, arg);
3113 Py_DECREF(arg);
3114 return result;
3115 } else {
3116 PyObject *args = load_args(pp_stack, na);
3117 PyObject *result = (*meth)(self, args);
3118 Py_DECREF(args);
3119 return result;
3121 case METH_NOARGS:
3122 if (na == 0)
3123 return (*meth)(self, NULL);
3124 PyErr_Format(PyExc_TypeError,
3125 "%.200s() takes no arguments (%d given)",
3126 ((PyCFunctionObject*)func)->m_ml->ml_name, na);
3127 return NULL;
3128 case METH_O:
3129 if (na == 1) {
3130 PyObject *arg = EXT_POP(*pp_stack);
3131 PyObject *result = (*meth)(self, arg);
3132 Py_DECREF(arg);
3133 return result;
3135 PyErr_Format(PyExc_TypeError,
3136 "%.200s() takes exactly one argument (%d given)",
3137 ((PyCFunctionObject*)func)->m_ml->ml_name, na);
3138 return NULL;
3139 default:
3140 fprintf(stderr, "%.200s() flags = %d\n",
3141 ((PyCFunctionObject*)func)->m_ml->ml_name, flags);
3142 PyErr_BadInternalCall();
3143 return NULL;
3147 static PyObject *
3148 fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
3150 PyObject *co = PyFunction_GET_CODE(func);
3151 PyObject *globals = PyFunction_GET_GLOBALS(func);
3152 PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
3153 PyObject *closure = PyFunction_GET_CLOSURE(func);
3154 PyObject **d = NULL;
3155 int nd = 0;
3157 if (argdefs != NULL) {
3158 d = &PyTuple_GET_ITEM(argdefs, 0);
3159 nd = ((PyTupleObject *)argdefs)->ob_size;
3161 return PyEval_EvalCodeEx((PyCodeObject *)co, globals,
3162 (PyObject *)NULL, (*pp_stack)-n, na,
3163 (*pp_stack)-2*nk, nk, d, nd,
3164 closure);
3167 static PyObject *
3168 update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
3169 PyObject *func)
3171 PyObject *kwdict = NULL;
3172 if (orig_kwdict == NULL)
3173 kwdict = PyDict_New();
3174 else {
3175 kwdict = PyDict_Copy(orig_kwdict);
3176 Py_DECREF(orig_kwdict);
3178 if (kwdict == NULL)
3179 return NULL;
3180 while (--nk >= 0) {
3181 int err;
3182 PyObject *value = EXT_POP(*pp_stack);
3183 PyObject *key = EXT_POP(*pp_stack);
3184 if (PyDict_GetItem(kwdict, key) != NULL) {
3185 PyErr_Format(PyExc_TypeError,
3186 "%.200s%s got multiple values "
3187 "for keyword argument '%.200s'",
3188 PyEval_GetFuncName(func),
3189 PyEval_GetFuncDesc(func),
3190 PyString_AsString(key));
3191 Py_DECREF(key);
3192 Py_DECREF(value);
3193 Py_DECREF(kwdict);
3194 return NULL;
3196 err = PyDict_SetItem(kwdict, key, value);
3197 Py_DECREF(key);
3198 Py_DECREF(value);
3199 if (err) {
3200 Py_DECREF(kwdict);
3201 return NULL;
3204 return kwdict;
3207 static PyObject *
3208 update_star_args(int nstack, int nstar, PyObject *stararg,
3209 PyObject ***pp_stack)
3211 PyObject *callargs, *w;
3213 callargs = PyTuple_New(nstack + nstar);
3214 if (callargs == NULL) {
3215 return NULL;
3217 if (nstar) {
3218 int i;
3219 for (i = 0; i < nstar; i++) {
3220 PyObject *a = PyTuple_GET_ITEM(stararg, i);
3221 Py_INCREF(a);
3222 PyTuple_SET_ITEM(callargs, nstack + i, a);
3225 while (--nstack >= 0) {
3226 w = EXT_POP(*pp_stack);
3227 PyTuple_SET_ITEM(callargs, nstack, w);
3229 return callargs;
3232 static PyObject *
3233 load_args(PyObject ***pp_stack, int na)
3235 PyObject *args = PyTuple_New(na);
3236 PyObject *w;
3238 if (args == NULL)
3239 return NULL;
3240 while (--na >= 0) {
3241 w = EXT_POP(*pp_stack);
3242 PyTuple_SET_ITEM(args, na, w);
3244 return args;
3247 static PyObject *
3248 do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
3250 PyObject *callargs = NULL;
3251 PyObject *kwdict = NULL;
3252 PyObject *result = NULL;
3254 if (nk > 0) {
3255 kwdict = update_keyword_args(NULL, nk, pp_stack, func);
3256 if (kwdict == NULL)
3257 goto call_fail;
3259 callargs = load_args(pp_stack, na);
3260 if (callargs == NULL)
3261 goto call_fail;
3262 result = PyObject_Call(func, callargs, kwdict);
3263 call_fail:
3264 Py_XDECREF(callargs);
3265 Py_XDECREF(kwdict);
3266 return result;
3269 static PyObject *
3270 ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
3272 int nstar = 0;
3273 PyObject *callargs = NULL;
3274 PyObject *stararg = NULL;
3275 PyObject *kwdict = NULL;
3276 PyObject *result = NULL;
3278 if (flags & CALL_FLAG_KW) {
3279 kwdict = EXT_POP(*pp_stack);
3280 if (!(kwdict && PyDict_Check(kwdict))) {
3281 PyErr_Format(PyExc_TypeError,
3282 "%s%s argument after ** "
3283 "must be a dictionary",
3284 PyEval_GetFuncName(func),
3285 PyEval_GetFuncDesc(func));
3286 goto ext_call_fail;
3289 if (flags & CALL_FLAG_VAR) {
3290 stararg = EXT_POP(*pp_stack);
3291 if (!PyTuple_Check(stararg)) {
3292 PyObject *t = NULL;
3293 t = PySequence_Tuple(stararg);
3294 if (t == NULL) {
3295 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3296 PyErr_Format(PyExc_TypeError,
3297 "%s%s argument after * "
3298 "must be a sequence",
3299 PyEval_GetFuncName(func),
3300 PyEval_GetFuncDesc(func));
3302 goto ext_call_fail;
3304 Py_DECREF(stararg);
3305 stararg = t;
3307 nstar = PyTuple_GET_SIZE(stararg);
3309 if (nk > 0) {
3310 kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
3311 if (kwdict == NULL)
3312 goto ext_call_fail;
3314 callargs = update_star_args(na, nstar, stararg, pp_stack);
3315 if (callargs == NULL)
3316 goto ext_call_fail;
3317 result = PyObject_Call(func, callargs, kwdict);
3318 ext_call_fail:
3319 Py_XDECREF(callargs);
3320 Py_XDECREF(kwdict);
3321 Py_XDECREF(stararg);
3322 return result;
3325 #define SLICE_ERROR_MSG \
3326 "standard sequence type does not support step size other than one"
3328 static PyObject *
3329 loop_subscript(PyObject *v, PyObject *w)
3331 PySequenceMethods *sq = v->ob_type->tp_as_sequence;
3332 int i;
3333 if (sq == NULL || sq->sq_item == NULL) {
3334 PyErr_SetString(PyExc_TypeError, "loop over non-sequence");
3335 return NULL;
3337 i = PyInt_AsLong(w);
3338 v = (*sq->sq_item)(v, i);
3339 if (v)
3340 return v;
3341 if (PyErr_ExceptionMatches(PyExc_IndexError))
3342 PyErr_Clear();
3343 return NULL;
3346 /* Extract a slice index from a PyInt or PyLong, and store in *pi.
3347 Silently reduce values larger than INT_MAX to INT_MAX, and silently
3348 boost values less than -INT_MAX to 0. Return 0 on error, 1 on success.
3350 /* Note: If v is NULL, return success without storing into *pi. This
3351 is because_PyEval_SliceIndex() is called by apply_slice(), which can be
3352 called by the SLICE opcode with v and/or w equal to NULL.
3355 _PyEval_SliceIndex(PyObject *v, int *pi)
3357 if (v != NULL) {
3358 long x;
3359 if (PyInt_Check(v)) {
3360 x = PyInt_AsLong(v);
3361 } else if (PyLong_Check(v)) {
3362 x = PyLong_AsLong(v);
3363 if (x==-1 && PyErr_Occurred()) {
3364 PyObject *long_zero;
3365 int cmp;
3367 if (!PyErr_ExceptionMatches(
3368 PyExc_OverflowError)) {
3369 /* It's not an overflow error, so just
3370 signal an error */
3371 return 0;
3374 /* Clear the OverflowError */
3375 PyErr_Clear();
3377 /* It's an overflow error, so we need to
3378 check the sign of the long integer,
3379 set the value to INT_MAX or 0, and clear
3380 the error. */
3382 /* Create a long integer with a value of 0 */
3383 long_zero = PyLong_FromLong(0L);
3384 if (long_zero == NULL)
3385 return 0;
3387 /* Check sign */
3388 cmp = PyObject_RichCompareBool(v, long_zero,
3389 Py_GT);
3390 Py_DECREF(long_zero);
3391 if (cmp < 0)
3392 return 0;
3393 else if (cmp > 0)
3394 x = INT_MAX;
3395 else
3396 x = 0;
3398 } else {
3399 PyErr_SetString(PyExc_TypeError,
3400 "slice indices must be integers");
3401 return 0;
3403 /* Truncate -- very long indices are truncated anyway */
3404 if (x > INT_MAX)
3405 x = INT_MAX;
3406 else if (x < -INT_MAX)
3407 x = 0;
3408 *pi = x;
3410 return 1;
3413 #undef ISINT
3414 #define ISINT(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x))
3416 static PyObject *
3417 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
3419 PyTypeObject *tp = u->ob_type;
3420 PySequenceMethods *sq = tp->tp_as_sequence;
3422 if (sq && sq->sq_slice && ISINT(v) && ISINT(w)) {
3423 int ilow = 0, ihigh = INT_MAX;
3424 if (!_PyEval_SliceIndex(v, &ilow))
3425 return NULL;
3426 if (!_PyEval_SliceIndex(w, &ihigh))
3427 return NULL;
3428 return PySequence_GetSlice(u, ilow, ihigh);
3430 else {
3431 PyObject *slice = PySlice_New(v, w, NULL);
3432 if (slice != NULL) {
3433 PyObject *res = PyObject_GetItem(u, slice);
3434 Py_DECREF(slice);
3435 return res;
3437 else
3438 return NULL;
3442 static int
3443 assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x)
3444 /* u[v:w] = x */
3446 PyTypeObject *tp = u->ob_type;
3447 PySequenceMethods *sq = tp->tp_as_sequence;
3449 if (sq && sq->sq_slice && ISINT(v) && ISINT(w)) {
3450 int ilow = 0, ihigh = INT_MAX;
3451 if (!_PyEval_SliceIndex(v, &ilow))
3452 return -1;
3453 if (!_PyEval_SliceIndex(w, &ihigh))
3454 return -1;
3455 if (x == NULL)
3456 return PySequence_DelSlice(u, ilow, ihigh);
3457 else
3458 return PySequence_SetSlice(u, ilow, ihigh, x);
3460 else {
3461 PyObject *slice = PySlice_New(v, w, NULL);
3462 if (slice != NULL) {
3463 int res;
3464 if (x != NULL)
3465 res = PyObject_SetItem(u, slice, x);
3466 else
3467 res = PyObject_DelItem(u, slice);
3468 Py_DECREF(slice);
3469 return res;
3471 else
3472 return -1;
3476 static PyObject *
3477 cmp_outcome(int op, register PyObject *v, register PyObject *w)
3479 int res = 0;
3480 switch (op) {
3481 case IS:
3482 case IS_NOT:
3483 res = (v == w);
3484 if (op == (int) IS_NOT)
3485 res = !res;
3486 break;
3487 case IN:
3488 case NOT_IN:
3489 res = PySequence_Contains(w, v);
3490 if (res < 0)
3491 return NULL;
3492 if (op == (int) NOT_IN)
3493 res = !res;
3494 break;
3495 case EXC_MATCH:
3496 res = PyErr_GivenExceptionMatches(v, w);
3497 break;
3498 default:
3499 return PyObject_RichCompare(v, w, op);
3501 v = res ? Py_True : Py_False;
3502 Py_INCREF(v);
3503 return v;
3506 static PyObject *
3507 import_from(PyObject *v, PyObject *name)
3509 PyObject *x;
3511 x = PyObject_GetAttr(v, name);
3512 if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
3513 PyErr_Format(PyExc_ImportError,
3514 "cannot import name %.230s",
3515 PyString_AsString(name));
3517 return x;
3520 static int
3521 import_all_from(PyObject *locals, PyObject *v)
3523 PyObject *all = PyObject_GetAttrString(v, "__all__");
3524 PyObject *dict, *name, *value;
3525 int skip_leading_underscores = 0;
3526 int pos, err;
3528 if (all == NULL) {
3529 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
3530 return -1; /* Unexpected error */
3531 PyErr_Clear();
3532 dict = PyObject_GetAttrString(v, "__dict__");
3533 if (dict == NULL) {
3534 if (!PyErr_ExceptionMatches(PyExc_AttributeError))
3535 return -1;
3536 PyErr_SetString(PyExc_ImportError,
3537 "from-import-* object has no __dict__ and no __all__");
3538 return -1;
3540 all = PyMapping_Keys(dict);
3541 Py_DECREF(dict);
3542 if (all == NULL)
3543 return -1;
3544 skip_leading_underscores = 1;
3547 for (pos = 0, err = 0; ; pos++) {
3548 name = PySequence_GetItem(all, pos);
3549 if (name == NULL) {
3550 if (!PyErr_ExceptionMatches(PyExc_IndexError))
3551 err = -1;
3552 else
3553 PyErr_Clear();
3554 break;
3556 if (skip_leading_underscores &&
3557 PyString_Check(name) &&
3558 PyString_AS_STRING(name)[0] == '_')
3560 Py_DECREF(name);
3561 continue;
3563 value = PyObject_GetAttr(v, name);
3564 if (value == NULL)
3565 err = -1;
3566 else
3567 err = PyDict_SetItem(locals, name, value);
3568 Py_DECREF(name);
3569 Py_XDECREF(value);
3570 if (err != 0)
3571 break;
3573 Py_DECREF(all);
3574 return err;
3577 static PyObject *
3578 build_class(PyObject *methods, PyObject *bases, PyObject *name)
3580 PyObject *metaclass = NULL, *result, *base;
3582 if (PyDict_Check(methods))
3583 metaclass = PyDict_GetItemString(methods, "__metaclass__");
3584 if (metaclass != NULL)
3585 Py_INCREF(metaclass);
3586 else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
3587 base = PyTuple_GET_ITEM(bases, 0);
3588 metaclass = PyObject_GetAttrString(base, "__class__");
3589 if (metaclass == NULL) {
3590 PyErr_Clear();
3591 metaclass = (PyObject *)base->ob_type;
3592 Py_INCREF(metaclass);
3595 else {
3596 PyObject *g = PyEval_GetGlobals();
3597 if (g != NULL && PyDict_Check(g))
3598 metaclass = PyDict_GetItemString(g, "__metaclass__");
3599 if (metaclass == NULL)
3600 metaclass = (PyObject *) &PyClass_Type;
3601 Py_INCREF(metaclass);
3603 result = PyObject_CallFunction(metaclass, "OOO", name, bases, methods);
3604 Py_DECREF(metaclass);
3605 return result;
3608 static int
3609 exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
3610 PyObject *locals)
3612 int n;
3613 PyObject *v;
3614 int plain = 0;
3616 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
3617 ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
3618 /* Backward compatibility hack */
3619 globals = PyTuple_GetItem(prog, 1);
3620 if (n == 3)
3621 locals = PyTuple_GetItem(prog, 2);
3622 prog = PyTuple_GetItem(prog, 0);
3624 if (globals == Py_None) {
3625 globals = PyEval_GetGlobals();
3626 if (locals == Py_None) {
3627 locals = PyEval_GetLocals();
3628 plain = 1;
3631 else if (locals == Py_None)
3632 locals = globals;
3633 if (!PyString_Check(prog) &&
3634 !PyUnicode_Check(prog) &&
3635 !PyCode_Check(prog) &&
3636 !PyFile_Check(prog)) {
3637 PyErr_SetString(PyExc_TypeError,
3638 "exec: arg 1 must be a string, file, or code object");
3639 return -1;
3641 if (!PyDict_Check(globals)) {
3642 PyErr_SetString(PyExc_TypeError,
3643 "exec: arg 2 must be a dictionary or None");
3644 return -1;
3646 if (!PyDict_Check(locals)) {
3647 PyErr_SetString(PyExc_TypeError,
3648 "exec: arg 3 must be a dictionary or None");
3649 return -1;
3651 if (PyDict_GetItemString(globals, "__builtins__") == NULL)
3652 PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
3653 if (PyCode_Check(prog)) {
3654 if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
3655 PyErr_SetString(PyExc_TypeError,
3656 "code object passed to exec may not contain free variables");
3657 return -1;
3659 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
3661 else if (PyFile_Check(prog)) {
3662 FILE *fp = PyFile_AsFile(prog);
3663 char *name = PyString_AsString(PyFile_Name(prog));
3664 PyCompilerFlags cf;
3665 cf.cf_flags = 0;
3666 if (PyEval_MergeCompilerFlags(&cf))
3667 v = PyRun_FileFlags(fp, name, Py_file_input, globals,
3668 locals, &cf);
3669 else
3670 v = PyRun_File(fp, name, Py_file_input, globals,
3671 locals);
3673 else {
3674 char *str;
3675 PyCompilerFlags cf;
3676 if (PyString_AsStringAndSize(prog, &str, NULL))
3677 return -1;
3678 cf.cf_flags = 0;
3679 if (PyEval_MergeCompilerFlags(&cf))
3680 v = PyRun_StringFlags(str, Py_file_input, globals,
3681 locals, &cf);
3682 else
3683 v = PyRun_String(str, Py_file_input, globals, locals);
3685 if (plain)
3686 PyFrame_LocalsToFast(f, 0);
3687 if (v == NULL)
3688 return -1;
3689 Py_DECREF(v);
3690 return 0;
3693 static void
3694 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
3696 char *obj_str;
3698 if (!obj)
3699 return;
3701 obj_str = PyString_AsString(obj);
3702 if (!obj_str)
3703 return;
3705 PyErr_Format(exc, format_str, obj_str);
3708 #ifdef DYNAMIC_EXECUTION_PROFILE
3710 static PyObject *
3711 getarray(long a[256])
3713 int i;
3714 PyObject *l = PyList_New(256);
3715 if (l == NULL) return NULL;
3716 for (i = 0; i < 256; i++) {
3717 PyObject *x = PyInt_FromLong(a[i]);
3718 if (x == NULL) {
3719 Py_DECREF(l);
3720 return NULL;
3722 PyList_SetItem(l, i, x);
3724 for (i = 0; i < 256; i++)
3725 a[i] = 0;
3726 return l;
3729 PyObject *
3730 _Py_GetDXProfile(PyObject *self, PyObject *args)
3732 #ifndef DXPAIRS
3733 return getarray(dxp);
3734 #else
3735 int i;
3736 PyObject *l = PyList_New(257);
3737 if (l == NULL) return NULL;
3738 for (i = 0; i < 257; i++) {
3739 PyObject *x = getarray(dxpairs[i]);
3740 if (x == NULL) {
3741 Py_DECREF(l);
3742 return NULL;
3744 PyList_SetItem(l, i, x);
3746 return l;
3747 #endif
3750 #endif