Bump version to 1.0.
[python/dscho.git] / Python / ceval.c
blob36cdab84e5839de04d7d7623ec3b7acb02af38fd
2 /* Execute compiled code */
4 /* XXX TO DO:
5 XXX how to pass arguments to call_trace?
6 XXX speed up searching for keywords by using a dictionary
7 XXX document it!
8 */
10 #include "Python.h"
12 #include "compile.h"
13 #include "frameobject.h"
14 #include "eval.h"
15 #include "opcode.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
33 /* Forward declarations */
35 static PyObject *eval_code2(PyCodeObject *,
36 PyObject *, PyObject *,
37 PyObject **, int,
38 PyObject **, int,
39 PyObject **, int,
40 PyObject *);
41 #ifdef LLTRACE
42 static int prtrace(PyObject *, char *);
43 #endif
44 static void call_exc_trace(PyObject **, PyObject**, PyFrameObject *);
45 static int call_trace(PyObject **, PyObject **,
46 PyFrameObject *, char *, PyObject *);
47 static PyObject *call_builtin(PyObject *, PyObject *, PyObject *);
48 static PyObject *call_function(PyObject *, PyObject *, PyObject *);
49 static PyObject *loop_subscript(PyObject *, PyObject *);
50 static PyObject *apply_slice(PyObject *, PyObject *, PyObject *);
51 static int assign_slice(PyObject *, PyObject *,
52 PyObject *, PyObject *);
53 static PyObject *cmp_outcome(int, PyObject *, PyObject *);
54 static PyObject *import_from(PyObject *, PyObject *);
55 static int import_all_from(PyObject *, PyObject *);
56 static PyObject *build_class(PyObject *, PyObject *, PyObject *);
57 static int exec_statement(PyFrameObject *,
58 PyObject *, PyObject *, PyObject *);
59 static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
60 static void reset_exc_info(PyThreadState *);
61 static void format_exc_check_arg(PyObject *, char *, PyObject *);
63 #define NAME_ERROR_MSG \
64 "There is no variable named '%s'"
65 #define UNBOUNDLOCAL_ERROR_MSG \
66 "Local variable '%.200s' referenced before assignment"
68 /* Dynamic execution profile */
69 #ifdef DYNAMIC_EXECUTION_PROFILE
70 #ifdef DXPAIRS
71 static long dxpairs[257][256];
72 #define dxp dxpairs[256]
73 #else
74 static long dxp[256];
75 #endif
76 #endif
79 #ifdef WITH_THREAD
81 #ifndef DONT_HAVE_ERRNO_H
82 #include <errno.h>
83 #endif
84 #include "pythread.h"
86 extern int _PyThread_Started; /* Flag for Py_Exit */
88 static PyThread_type_lock interpreter_lock = 0;
89 static long main_thread = 0;
91 void
92 PyEval_InitThreads(void)
94 if (interpreter_lock)
95 return;
96 _PyThread_Started = 1;
97 interpreter_lock = PyThread_allocate_lock();
98 PyThread_acquire_lock(interpreter_lock, 1);
99 main_thread = PyThread_get_thread_ident();
102 void
103 PyEval_AcquireLock(void)
105 PyThread_acquire_lock(interpreter_lock, 1);
108 void
109 PyEval_ReleaseLock(void)
111 PyThread_release_lock(interpreter_lock);
114 void
115 PyEval_AcquireThread(PyThreadState *tstate)
117 if (tstate == NULL)
118 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
119 PyThread_acquire_lock(interpreter_lock, 1);
120 if (PyThreadState_Swap(tstate) != NULL)
121 Py_FatalError(
122 "PyEval_AcquireThread: non-NULL old thread state");
125 void
126 PyEval_ReleaseThread(PyThreadState *tstate)
128 if (tstate == NULL)
129 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
130 if (PyThreadState_Swap(NULL) != tstate)
131 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
132 PyThread_release_lock(interpreter_lock);
135 /* This function is called from PyOS_AfterFork to ensure that newly
136 created child processes don't hold locks referring to threads which
137 are not running in the child process. (This could also be done using
138 pthread_atfork mechanism, at least for the pthreads implementation.) */
140 void
141 PyEval_ReInitThreads(void)
143 if (!interpreter_lock)
144 return;
145 /*XXX Can't use PyThread_free_lock here because it does too
146 much error-checking. Doing this cleanly would require
147 adding a new function to each thread_*.h. Instead, just
148 create a new lock and waste a little bit of memory */
149 interpreter_lock = PyThread_allocate_lock();
150 PyThread_acquire_lock(interpreter_lock, 1);
151 main_thread = PyThread_get_thread_ident();
153 #endif
155 /* Functions save_thread and restore_thread are always defined so
156 dynamically loaded modules needn't be compiled separately for use
157 with and without threads: */
159 PyThreadState *
160 PyEval_SaveThread(void)
162 PyThreadState *tstate = PyThreadState_Swap(NULL);
163 if (tstate == NULL)
164 Py_FatalError("PyEval_SaveThread: NULL tstate");
165 #ifdef WITH_THREAD
166 if (interpreter_lock)
167 PyThread_release_lock(interpreter_lock);
168 #endif
169 return tstate;
172 void
173 PyEval_RestoreThread(PyThreadState *tstate)
175 if (tstate == NULL)
176 Py_FatalError("PyEval_RestoreThread: NULL tstate");
177 #ifdef WITH_THREAD
178 if (interpreter_lock) {
179 int err = errno;
180 PyThread_acquire_lock(interpreter_lock, 1);
181 errno = err;
183 #endif
184 PyThreadState_Swap(tstate);
188 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
189 signal handlers or Mac I/O completion routines) can schedule calls
190 to a function to be called synchronously.
191 The synchronous function is called with one void* argument.
192 It should return 0 for success or -1 for failure -- failure should
193 be accompanied by an exception.
195 If registry succeeds, the registry function returns 0; if it fails
196 (e.g. due to too many pending calls) it returns -1 (without setting
197 an exception condition).
199 Note that because registry may occur from within signal handlers,
200 or other asynchronous events, calling malloc() is unsafe!
202 #ifdef WITH_THREAD
203 Any thread can schedule pending calls, but only the main thread
204 will execute them.
205 #endif
207 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
208 There are two possible race conditions:
209 (1) nested asynchronous registry calls;
210 (2) registry calls made while pending calls are being processed.
211 While (1) is very unlikely, (2) is a real possibility.
212 The current code is safe against (2), but not against (1).
213 The safety against (2) is derived from the fact that only one
214 thread (the main thread) ever takes things out of the queue.
216 XXX Darn! With the advent of thread state, we should have an array
217 of pending calls per thread in the thread state! Later...
220 #define NPENDINGCALLS 32
221 static struct {
222 int (*func)(void *);
223 void *arg;
224 } pendingcalls[NPENDINGCALLS];
225 static volatile int pendingfirst = 0;
226 static volatile int pendinglast = 0;
227 static volatile int things_to_do = 0;
230 Py_AddPendingCall(int (*func)(void *), void *arg)
232 static int busy = 0;
233 int i, j;
234 /* XXX Begin critical section */
235 /* XXX If you want this to be safe against nested
236 XXX asynchronous calls, you'll have to work harder! */
237 if (busy)
238 return -1;
239 busy = 1;
240 i = pendinglast;
241 j = (i + 1) % NPENDINGCALLS;
242 if (j == pendingfirst)
243 return -1; /* Queue full */
244 pendingcalls[i].func = func;
245 pendingcalls[i].arg = arg;
246 pendinglast = j;
247 things_to_do = 1; /* Signal main loop */
248 busy = 0;
249 /* XXX End critical section */
250 return 0;
254 Py_MakePendingCalls(void)
256 static int busy = 0;
257 #ifdef WITH_THREAD
258 if (main_thread && PyThread_get_thread_ident() != main_thread)
259 return 0;
260 #endif
261 if (busy)
262 return 0;
263 busy = 1;
264 things_to_do = 0;
265 for (;;) {
266 int i;
267 int (*func)(void *);
268 void *arg;
269 i = pendingfirst;
270 if (i == pendinglast)
271 break; /* Queue empty */
272 func = pendingcalls[i].func;
273 arg = pendingcalls[i].arg;
274 pendingfirst = (i + 1) % NPENDINGCALLS;
275 if (func(arg) < 0) {
276 busy = 0;
277 things_to_do = 1; /* We're not done yet */
278 return -1;
281 busy = 0;
282 return 0;
286 /* The interpreter's recursion limit */
288 static int recursion_limit = 1000;
291 Py_GetRecursionLimit(void)
293 return recursion_limit;
296 void
297 Py_SetRecursionLimit(int new_limit)
299 recursion_limit = new_limit;
302 /* Status code for main loop (reason for stack unwind) */
304 enum why_code {
305 WHY_NOT, /* No error */
306 WHY_EXCEPTION, /* Exception occurred */
307 WHY_RERAISE, /* Exception re-raised by 'finally' */
308 WHY_RETURN, /* 'return' statement */
309 WHY_BREAK /* 'break' statement */
312 static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
313 static int unpack_sequence(PyObject *, int, PyObject **);
316 PyObject *
317 PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
319 return eval_code2(co,
320 globals, locals,
321 (PyObject **)NULL, 0,
322 (PyObject **)NULL, 0,
323 (PyObject **)NULL, 0,
324 (PyObject *)NULL);
328 /* Interpreter main loop */
330 static PyObject *
331 eval_code2(PyCodeObject *co, PyObject *globals, PyObject *locals,
332 PyObject **args, int argcount, PyObject **kws, int kwcount,
333 PyObject **defs, int defcount, PyObject *owner)
335 #ifdef DXPAIRS
336 int lastopcode = 0;
337 #endif
338 register unsigned char *next_instr;
339 register int opcode=0; /* Current opcode */
340 register int oparg=0; /* Current opcode argument, if any */
341 register PyObject **stack_pointer;
342 register enum why_code why; /* Reason for block stack unwind */
343 register int err; /* Error status -- nonzero if error */
344 register PyObject *x; /* Result object -- NULL if error */
345 register PyObject *v; /* Temporary objects popped off stack */
346 register PyObject *w;
347 register PyObject *u;
348 register PyObject *t;
349 register PyObject *stream = NULL; /* for PRINT opcodes */
350 register PyFrameObject *f; /* Current frame */
351 register PyObject **fastlocals;
352 PyObject *retval = NULL; /* Return value */
353 PyThreadState *tstate = PyThreadState_GET();
354 unsigned char *first_instr;
355 #ifdef LLTRACE
356 int lltrace;
357 #endif
358 #if defined(Py_DEBUG) || defined(LLTRACE)
359 /* Make it easier to find out where we are with a debugger */
360 char *filename = PyString_AsString(co->co_filename);
361 #endif
363 /* Code access macros */
365 #define GETCONST(i) Getconst(f, i)
366 #define GETNAME(i) Getname(f, i)
367 #define GETNAMEV(i) Getnamev(f, i)
368 #define INSTR_OFFSET() (next_instr - first_instr)
369 #define NEXTOP() (*next_instr++)
370 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
371 #define JUMPTO(x) (next_instr = first_instr + (x))
372 #define JUMPBY(x) (next_instr += (x))
374 /* Stack manipulation macros */
376 #define STACK_LEVEL() (stack_pointer - f->f_valuestack)
377 #define EMPTY() (STACK_LEVEL() == 0)
378 #define TOP() (stack_pointer[-1])
379 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
380 #define BASIC_POP() (*--stack_pointer)
382 #ifdef LLTRACE
383 #define PUSH(v) (BASIC_PUSH(v), lltrace && prtrace(TOP(), "push"))
384 #define POP() (lltrace && prtrace(TOP(), "pop"), BASIC_POP())
385 #else
386 #define PUSH(v) BASIC_PUSH(v)
387 #define POP() BASIC_POP()
388 #endif
390 /* Local variable macros */
392 #define GETLOCAL(i) (fastlocals[i])
393 #define SETLOCAL(i, value) do { Py_XDECREF(GETLOCAL(i)); \
394 GETLOCAL(i) = value; } while (0)
396 /* Start of code */
398 #ifdef USE_STACKCHECK
399 if (tstate->recursion_depth%10 == 0 && PyOS_CheckStack()) {
400 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
401 return NULL;
403 #endif
405 if (globals == NULL) {
406 PyErr_SetString(PyExc_SystemError, "eval_code2: NULL globals");
407 return NULL;
410 #ifdef LLTRACE
411 lltrace = PyDict_GetItemString(globals, "__lltrace__") != NULL;
412 #endif
414 f = PyFrame_New(
415 tstate, /*back*/
416 co, /*code*/
417 globals, /*globals*/
418 locals); /*locals*/
419 if (f == NULL)
420 return NULL;
422 tstate->frame = f;
423 fastlocals = f->f_localsplus;
425 if (co->co_argcount > 0 ||
426 co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
427 int i;
428 int n = argcount;
429 PyObject *kwdict = NULL;
430 if (co->co_flags & CO_VARKEYWORDS) {
431 kwdict = PyDict_New();
432 if (kwdict == NULL)
433 goto fail;
434 i = co->co_argcount;
435 if (co->co_flags & CO_VARARGS)
436 i++;
437 SETLOCAL(i, kwdict);
439 if (argcount > co->co_argcount) {
440 if (!(co->co_flags & CO_VARARGS)) {
441 PyErr_Format(PyExc_TypeError,
442 "too many arguments; expected %d, got %d",
443 co->co_argcount, argcount);
444 goto fail;
446 n = co->co_argcount;
448 for (i = 0; i < n; i++) {
449 x = args[i];
450 Py_INCREF(x);
451 SETLOCAL(i, x);
453 if (co->co_flags & CO_VARARGS) {
454 u = PyTuple_New(argcount - n);
455 if (u == NULL)
456 goto fail;
457 SETLOCAL(co->co_argcount, u);
458 for (i = n; i < argcount; i++) {
459 x = args[i];
460 Py_INCREF(x);
461 PyTuple_SET_ITEM(u, i-n, x);
464 for (i = 0; i < kwcount; i++) {
465 PyObject *keyword = kws[2*i];
466 PyObject *value = kws[2*i + 1];
467 int j;
468 if (keyword == NULL || !PyString_Check(keyword)) {
469 PyErr_SetString(PyExc_TypeError,
470 "keywords must be strings");
471 goto fail;
473 /* XXX slow -- speed up using dictionary? */
474 for (j = 0; j < co->co_argcount; j++) {
475 PyObject *nm = PyTuple_GET_ITEM(
476 co->co_varnames, j);
477 if (PyObject_Compare(keyword, nm) == 0)
478 break;
480 /* Check errors from Compare */
481 if (PyErr_Occurred())
482 goto fail;
483 if (j >= co->co_argcount) {
484 if (kwdict == NULL) {
485 PyErr_Format(PyExc_TypeError,
486 "unexpected keyword argument: %.400s",
487 PyString_AsString(keyword));
488 goto fail;
490 PyDict_SetItem(kwdict, keyword, value);
492 else {
493 if (GETLOCAL(j) != NULL) {
494 PyErr_Format(PyExc_TypeError,
495 "keyword parameter redefined: %.400s",
496 PyString_AsString(keyword));
497 goto fail;
499 Py_INCREF(value);
500 SETLOCAL(j, value);
503 if (argcount < co->co_argcount) {
504 int m = co->co_argcount - defcount;
505 for (i = argcount; i < m; i++) {
506 if (GETLOCAL(i) == NULL) {
507 PyErr_Format(PyExc_TypeError,
508 "not enough arguments; expected %d, got %d",
509 m, i);
510 goto fail;
513 if (n > m)
514 i = n - m;
515 else
516 i = 0;
517 for (; i < defcount; i++) {
518 if (GETLOCAL(m+i) == NULL) {
519 PyObject *def = defs[i];
520 Py_INCREF(def);
521 SETLOCAL(m+i, def);
526 else {
527 if (argcount > 0 || kwcount > 0) {
528 PyErr_SetString(PyExc_TypeError,
529 "no arguments expected");
530 goto fail;
534 if (tstate->sys_tracefunc != NULL) {
535 /* tstate->sys_tracefunc, if defined, is a function that
536 will be called on *every* entry to a code block.
537 Its return value, if not None, is a function that
538 will be called at the start of each executed line
539 of code. (Actually, the function must return
540 itself in order to continue tracing.)
541 The trace functions are called with three arguments:
542 a pointer to the current frame, a string indicating
543 why the function is called, and an argument which
544 depends on the situation. The global trace function
545 (sys.trace) is also called whenever an exception
546 is detected. */
547 if (call_trace(&tstate->sys_tracefunc,
548 &f->f_trace, f, "call",
549 Py_None/*XXX how to compute arguments now?*/)) {
550 /* Trace function raised an error */
551 goto fail;
555 if (tstate->sys_profilefunc != NULL) {
556 /* Similar for sys_profilefunc, except it needn't return
557 itself and isn't called for "line" events */
558 if (call_trace(&tstate->sys_profilefunc,
559 (PyObject**)0, f, "call",
560 Py_None/*XXX*/)) {
561 goto fail;
565 if (++tstate->recursion_depth > recursion_limit) {
566 --tstate->recursion_depth;
567 PyErr_SetString(PyExc_RuntimeError,
568 "Maximum recursion depth exceeded");
569 tstate->frame = f->f_back;
570 Py_DECREF(f);
571 return NULL;
574 _PyCode_GETCODEPTR(co, &first_instr);
575 next_instr = first_instr;
576 stack_pointer = f->f_valuestack;
578 why = WHY_NOT;
579 err = 0;
580 x = Py_None; /* Not a reference, just anything non-NULL */
582 for (;;) {
583 /* Do periodic things. Doing this every time through
584 the loop would add too much overhead, so we do it
585 only every Nth instruction. We also do it if
586 ``things_to_do'' is set, i.e. when an asynchronous
587 event needs attention (e.g. a signal handler or
588 async I/O handler); see Py_AddPendingCall() and
589 Py_MakePendingCalls() above. */
591 if (things_to_do || --tstate->ticker < 0) {
592 tstate->ticker = tstate->interp->checkinterval;
593 if (things_to_do) {
594 if (Py_MakePendingCalls() < 0) {
595 why = WHY_EXCEPTION;
596 goto on_error;
599 #if !defined(HAVE_SIGNAL_H) || defined(macintosh)
600 /* If we have true signals, the signal handler
601 will call Py_AddPendingCall() so we don't
602 have to call sigcheck(). On the Mac and
603 DOS, alas, we have to call it. */
604 if (PyErr_CheckSignals()) {
605 why = WHY_EXCEPTION;
606 goto on_error;
608 #endif
610 #ifdef WITH_THREAD
611 if (interpreter_lock) {
612 /* Give another thread a chance */
614 if (PyThreadState_Swap(NULL) != tstate)
615 Py_FatalError("ceval: tstate mix-up");
616 PyThread_release_lock(interpreter_lock);
618 /* Other threads may run now */
620 PyThread_acquire_lock(interpreter_lock, 1);
621 if (PyThreadState_Swap(tstate) != NULL)
622 Py_FatalError("ceval: orphan tstate");
624 #endif
627 /* Extract opcode and argument */
629 #if defined(Py_DEBUG) || defined(LLTRACE)
630 f->f_lasti = INSTR_OFFSET();
631 #endif
633 opcode = NEXTOP();
634 if (HAS_ARG(opcode))
635 oparg = NEXTARG();
636 dispatch_opcode:
637 #ifdef DYNAMIC_EXECUTION_PROFILE
638 #ifdef DXPAIRS
639 dxpairs[lastopcode][opcode]++;
640 lastopcode = opcode;
641 #endif
642 dxp[opcode]++;
643 #endif
645 #ifdef LLTRACE
646 /* Instruction tracing */
648 if (lltrace) {
649 if (HAS_ARG(opcode)) {
650 printf("%d: %d, %d\n",
651 (int) (INSTR_OFFSET() - 3),
652 opcode, oparg);
654 else {
655 printf("%d: %d\n",
656 (int) (INSTR_OFFSET() - 1), opcode);
659 #endif
660 /* Main switch on opcode */
662 switch (opcode) {
664 /* BEWARE!
665 It is essential that any operation that fails sets either
666 x to NULL, err to nonzero, or why to anything but WHY_NOT,
667 and that no operation that succeeds does this! */
669 /* case STOP_CODE: this is an error! */
671 case POP_TOP:
672 v = POP();
673 Py_DECREF(v);
674 continue;
676 case ROT_TWO:
677 v = POP();
678 w = POP();
679 PUSH(v);
680 PUSH(w);
681 continue;
683 case ROT_THREE:
684 v = POP();
685 w = POP();
686 x = POP();
687 PUSH(v);
688 PUSH(x);
689 PUSH(w);
690 continue;
692 case ROT_FOUR:
693 u = POP();
694 v = POP();
695 w = POP();
696 x = POP();
697 PUSH(u);
698 PUSH(x);
699 PUSH(w);
700 PUSH(v);
701 continue;
703 case DUP_TOP:
704 v = TOP();
705 Py_INCREF(v);
706 PUSH(v);
707 continue;
709 case DUP_TOPX:
710 switch (oparg) {
711 case 5:
712 case 4:
713 case 3:
714 case 2:
715 case 1:
716 x = POP();
717 if (oparg == 1) break;
718 w = POP();
719 if (oparg == 2) break;
720 v = POP();
721 if (oparg == 3) break;
722 u = POP();
723 if (oparg == 4) break;
724 t = POP();
725 break;
726 default:
727 fprintf(stderr, "Invalid argument to DUP_TOPX: %d!\n", oparg);
728 PyErr_SetString(PyExc_SystemError,
729 "invalid argument to DUP_TOPX");
730 x = NULL;
732 if (x == NULL)
733 break;
734 switch (oparg) {
735 case 5: PUSH(t);
736 Py_INCREF(t); /* Fallthrough */
737 case 4: PUSH(u);
738 Py_INCREF(u); /* Fallthrough */
739 case 3: PUSH(v);
740 Py_INCREF(v); /* Fallthrough */
741 case 2: PUSH(w);
742 Py_INCREF(w); /* Fallthrough */
743 case 1: PUSH(x);
744 Py_INCREF(x); /* Fallthrough */
746 switch (oparg) {
747 case 5: PUSH(t); /* Fallthrough */
748 case 4: PUSH(u); /* Fallthrough */
749 case 3: PUSH(v); /* Fallthrough */
750 case 2: PUSH(w); /* Fallthrough */
751 case 1: PUSH(x); /* Fallthrough */
753 continue;
755 case UNARY_POSITIVE:
756 v = POP();
757 x = PyNumber_Positive(v);
758 Py_DECREF(v);
759 PUSH(x);
760 if (x != NULL) continue;
761 break;
763 case UNARY_NEGATIVE:
764 v = POP();
765 x = PyNumber_Negative(v);
766 Py_DECREF(v);
767 PUSH(x);
768 if (x != NULL) continue;
769 break;
771 case UNARY_NOT:
772 v = POP();
773 err = PyObject_IsTrue(v);
774 Py_DECREF(v);
775 if (err == 0) {
776 Py_INCREF(Py_True);
777 PUSH(Py_True);
778 continue;
780 else if (err > 0) {
781 Py_INCREF(Py_False);
782 PUSH(Py_False);
783 err = 0;
784 continue;
786 break;
788 case UNARY_CONVERT:
789 v = POP();
790 x = PyObject_Repr(v);
791 Py_DECREF(v);
792 PUSH(x);
793 if (x != NULL) continue;
794 break;
796 case UNARY_INVERT:
797 v = POP();
798 x = PyNumber_Invert(v);
799 Py_DECREF(v);
800 PUSH(x);
801 if (x != NULL) continue;
802 break;
804 case BINARY_POWER:
805 w = POP();
806 v = POP();
807 x = PyNumber_Power(v, w, Py_None);
808 Py_DECREF(v);
809 Py_DECREF(w);
810 PUSH(x);
811 if (x != NULL) continue;
812 break;
814 case BINARY_MULTIPLY:
815 w = POP();
816 v = POP();
817 x = PyNumber_Multiply(v, w);
818 Py_DECREF(v);
819 Py_DECREF(w);
820 PUSH(x);
821 if (x != NULL) continue;
822 break;
824 case BINARY_DIVIDE:
825 w = POP();
826 v = POP();
827 x = PyNumber_Divide(v, w);
828 Py_DECREF(v);
829 Py_DECREF(w);
830 PUSH(x);
831 if (x != NULL) continue;
832 break;
834 case BINARY_MODULO:
835 w = POP();
836 v = POP();
837 x = PyNumber_Remainder(v, w);
838 Py_DECREF(v);
839 Py_DECREF(w);
840 PUSH(x);
841 if (x != NULL) continue;
842 break;
844 case BINARY_ADD:
845 w = POP();
846 v = POP();
847 if (PyInt_Check(v) && PyInt_Check(w)) {
848 /* INLINE: int + int */
849 register long a, b, i;
850 a = PyInt_AS_LONG(v);
851 b = PyInt_AS_LONG(w);
852 i = a + b;
853 if ((i^a) < 0 && (i^b) < 0) {
854 PyErr_SetString(PyExc_OverflowError,
855 "integer addition");
856 x = NULL;
858 else
859 x = PyInt_FromLong(i);
861 else
862 x = PyNumber_Add(v, w);
863 Py_DECREF(v);
864 Py_DECREF(w);
865 PUSH(x);
866 if (x != NULL) continue;
867 break;
869 case BINARY_SUBTRACT:
870 w = POP();
871 v = POP();
872 if (PyInt_Check(v) && PyInt_Check(w)) {
873 /* INLINE: int - int */
874 register long a, b, i;
875 a = PyInt_AS_LONG(v);
876 b = PyInt_AS_LONG(w);
877 i = a - b;
878 if ((i^a) < 0 && (i^~b) < 0) {
879 PyErr_SetString(PyExc_OverflowError,
880 "integer subtraction");
881 x = NULL;
883 else
884 x = PyInt_FromLong(i);
886 else
887 x = PyNumber_Subtract(v, w);
888 Py_DECREF(v);
889 Py_DECREF(w);
890 PUSH(x);
891 if (x != NULL) continue;
892 break;
894 case BINARY_SUBSCR:
895 w = POP();
896 v = POP();
897 if (PyList_Check(v) && PyInt_Check(w)) {
898 /* INLINE: list[int] */
899 long i = PyInt_AsLong(w);
900 if (i < 0)
901 i += PyList_GET_SIZE(v);
902 if (i < 0 ||
903 i >= PyList_GET_SIZE(v)) {
904 PyErr_SetString(PyExc_IndexError,
905 "list index out of range");
906 x = NULL;
908 else {
909 x = PyList_GET_ITEM(v, i);
910 Py_INCREF(x);
913 else
914 x = PyObject_GetItem(v, w);
915 Py_DECREF(v);
916 Py_DECREF(w);
917 PUSH(x);
918 if (x != NULL) continue;
919 break;
921 case BINARY_LSHIFT:
922 w = POP();
923 v = POP();
924 x = PyNumber_Lshift(v, w);
925 Py_DECREF(v);
926 Py_DECREF(w);
927 PUSH(x);
928 if (x != NULL) continue;
929 break;
931 case BINARY_RSHIFT:
932 w = POP();
933 v = POP();
934 x = PyNumber_Rshift(v, w);
935 Py_DECREF(v);
936 Py_DECREF(w);
937 PUSH(x);
938 if (x != NULL) continue;
939 break;
941 case BINARY_AND:
942 w = POP();
943 v = POP();
944 x = PyNumber_And(v, w);
945 Py_DECREF(v);
946 Py_DECREF(w);
947 PUSH(x);
948 if (x != NULL) continue;
949 break;
951 case BINARY_XOR:
952 w = POP();
953 v = POP();
954 x = PyNumber_Xor(v, w);
955 Py_DECREF(v);
956 Py_DECREF(w);
957 PUSH(x);
958 if (x != NULL) continue;
959 break;
961 case BINARY_OR:
962 w = POP();
963 v = POP();
964 x = PyNumber_Or(v, w);
965 Py_DECREF(v);
966 Py_DECREF(w);
967 PUSH(x);
968 if (x != NULL) continue;
969 break;
971 case INPLACE_POWER:
972 w = POP();
973 v = POP();
974 x = PyNumber_InPlacePower(v, w, Py_None);
975 Py_DECREF(v);
976 Py_DECREF(w);
977 PUSH(x);
978 if (x != NULL) continue;
979 break;
981 case INPLACE_MULTIPLY:
982 w = POP();
983 v = POP();
984 x = PyNumber_InPlaceMultiply(v, w);
985 Py_DECREF(v);
986 Py_DECREF(w);
987 PUSH(x);
988 if (x != NULL) continue;
989 break;
991 case INPLACE_DIVIDE:
992 w = POP();
993 v = POP();
994 x = PyNumber_InPlaceDivide(v, w);
995 Py_DECREF(v);
996 Py_DECREF(w);
997 PUSH(x);
998 if (x != NULL) continue;
999 break;
1001 case INPLACE_MODULO:
1002 w = POP();
1003 v = POP();
1004 x = PyNumber_InPlaceRemainder(v, w);
1005 Py_DECREF(v);
1006 Py_DECREF(w);
1007 PUSH(x);
1008 if (x != NULL) continue;
1009 break;
1011 case INPLACE_ADD:
1012 w = POP();
1013 v = POP();
1014 if (PyInt_Check(v) && PyInt_Check(w)) {
1015 /* INLINE: int + int */
1016 register long a, b, i;
1017 a = PyInt_AS_LONG(v);
1018 b = PyInt_AS_LONG(w);
1019 i = a + b;
1020 if ((i^a) < 0 && (i^b) < 0) {
1021 PyErr_SetString(PyExc_OverflowError,
1022 "integer addition");
1023 x = NULL;
1025 else
1026 x = PyInt_FromLong(i);
1028 else
1029 x = PyNumber_InPlaceAdd(v, w);
1030 Py_DECREF(v);
1031 Py_DECREF(w);
1032 PUSH(x);
1033 if (x != NULL) continue;
1034 break;
1036 case INPLACE_SUBTRACT:
1037 w = POP();
1038 v = POP();
1039 if (PyInt_Check(v) && PyInt_Check(w)) {
1040 /* INLINE: int - int */
1041 register long a, b, i;
1042 a = PyInt_AS_LONG(v);
1043 b = PyInt_AS_LONG(w);
1044 i = a - b;
1045 if ((i^a) < 0 && (i^~b) < 0) {
1046 PyErr_SetString(PyExc_OverflowError,
1047 "integer subtraction");
1048 x = NULL;
1050 else
1051 x = PyInt_FromLong(i);
1053 else
1054 x = PyNumber_InPlaceSubtract(v, w);
1055 Py_DECREF(v);
1056 Py_DECREF(w);
1057 PUSH(x);
1058 if (x != NULL) continue;
1059 break;
1061 case INPLACE_LSHIFT:
1062 w = POP();
1063 v = POP();
1064 x = PyNumber_InPlaceLshift(v, w);
1065 Py_DECREF(v);
1066 Py_DECREF(w);
1067 PUSH(x);
1068 if (x != NULL) continue;
1069 break;
1071 case INPLACE_RSHIFT:
1072 w = POP();
1073 v = POP();
1074 x = PyNumber_InPlaceRshift(v, w);
1075 Py_DECREF(v);
1076 Py_DECREF(w);
1077 PUSH(x);
1078 if (x != NULL) continue;
1079 break;
1081 case INPLACE_AND:
1082 w = POP();
1083 v = POP();
1084 x = PyNumber_InPlaceAnd(v, w);
1085 Py_DECREF(v);
1086 Py_DECREF(w);
1087 PUSH(x);
1088 if (x != NULL) continue;
1089 break;
1091 case INPLACE_XOR:
1092 w = POP();
1093 v = POP();
1094 x = PyNumber_InPlaceXor(v, w);
1095 Py_DECREF(v);
1096 Py_DECREF(w);
1097 PUSH(x);
1098 if (x != NULL) continue;
1099 break;
1101 case INPLACE_OR:
1102 w = POP();
1103 v = POP();
1104 x = PyNumber_InPlaceOr(v, w);
1105 Py_DECREF(v);
1106 Py_DECREF(w);
1107 PUSH(x);
1108 if (x != NULL) continue;
1109 break;
1111 case SLICE+0:
1112 case SLICE+1:
1113 case SLICE+2:
1114 case SLICE+3:
1115 if ((opcode-SLICE) & 2)
1116 w = POP();
1117 else
1118 w = NULL;
1119 if ((opcode-SLICE) & 1)
1120 v = POP();
1121 else
1122 v = NULL;
1123 u = POP();
1124 x = apply_slice(u, v, w);
1125 Py_DECREF(u);
1126 Py_XDECREF(v);
1127 Py_XDECREF(w);
1128 PUSH(x);
1129 if (x != NULL) continue;
1130 break;
1132 case STORE_SLICE+0:
1133 case STORE_SLICE+1:
1134 case STORE_SLICE+2:
1135 case STORE_SLICE+3:
1136 if ((opcode-STORE_SLICE) & 2)
1137 w = POP();
1138 else
1139 w = NULL;
1140 if ((opcode-STORE_SLICE) & 1)
1141 v = POP();
1142 else
1143 v = NULL;
1144 u = POP();
1145 t = POP();
1146 err = assign_slice(u, v, w, t); /* u[v:w] = t */
1147 Py_DECREF(t);
1148 Py_DECREF(u);
1149 Py_XDECREF(v);
1150 Py_XDECREF(w);
1151 if (err == 0) continue;
1152 break;
1154 case DELETE_SLICE+0:
1155 case DELETE_SLICE+1:
1156 case DELETE_SLICE+2:
1157 case DELETE_SLICE+3:
1158 if ((opcode-DELETE_SLICE) & 2)
1159 w = POP();
1160 else
1161 w = NULL;
1162 if ((opcode-DELETE_SLICE) & 1)
1163 v = POP();
1164 else
1165 v = NULL;
1166 u = POP();
1167 err = assign_slice(u, v, w, (PyObject *)NULL);
1168 /* del u[v:w] */
1169 Py_DECREF(u);
1170 Py_XDECREF(v);
1171 Py_XDECREF(w);
1172 if (err == 0) continue;
1173 break;
1175 case STORE_SUBSCR:
1176 w = POP();
1177 v = POP();
1178 u = POP();
1179 /* v[w] = u */
1180 err = PyObject_SetItem(v, w, u);
1181 Py_DECREF(u);
1182 Py_DECREF(v);
1183 Py_DECREF(w);
1184 if (err == 0) continue;
1185 break;
1187 case DELETE_SUBSCR:
1188 w = POP();
1189 v = POP();
1190 /* del v[w] */
1191 err = PyObject_DelItem(v, w);
1192 Py_DECREF(v);
1193 Py_DECREF(w);
1194 if (err == 0) continue;
1195 break;
1197 case PRINT_EXPR:
1198 v = POP();
1199 /* Print value except if None */
1200 /* After printing, also assign to '_' */
1201 /* Before, set '_' to None to avoid recursion */
1202 if (v != Py_None &&
1203 (err = PyDict_SetItemString(
1204 f->f_builtins, "_", Py_None)) == 0) {
1205 err = Py_FlushLine();
1206 if (err == 0) {
1207 x = PySys_GetObject("stdout");
1208 if (x == NULL) {
1209 PyErr_SetString(
1210 PyExc_RuntimeError,
1211 "lost sys.stdout");
1212 err = -1;
1215 if (err == 0)
1216 err = PyFile_WriteObject(v, x, 0);
1217 if (err == 0) {
1218 PyFile_SoftSpace(x, 1);
1219 err = Py_FlushLine();
1221 if (err == 0) {
1222 err = PyDict_SetItemString(
1223 f->f_builtins, "_", v);
1226 Py_DECREF(v);
1227 break;
1229 case PRINT_ITEM_TO:
1230 w = stream = POP();
1231 /* fall through to PRINT_ITEM */
1233 case PRINT_ITEM:
1234 v = POP();
1235 if (stream == NULL || stream == Py_None) {
1236 w = PySys_GetObject("stdout");
1237 if (w == NULL) {
1238 PyErr_SetString(PyExc_RuntimeError,
1239 "lost sys.stdout");
1240 err = -1;
1243 if (w != NULL && PyFile_SoftSpace(w, 1))
1244 err = PyFile_WriteString(" ", w);
1245 if (err == 0)
1246 err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
1247 if (err == 0 && PyString_Check(v)) {
1248 /* XXX move into writeobject() ? */
1249 char *s = PyString_AsString(v);
1250 int len = PyString_Size(v);
1251 if (len > 0 &&
1252 isspace(Py_CHARMASK(s[len-1])) &&
1253 s[len-1] != ' ')
1254 PyFile_SoftSpace(w, 0);
1256 Py_DECREF(v);
1257 Py_XDECREF(stream);
1258 stream = NULL;
1259 if (err == 0)
1260 continue;
1261 break;
1263 case PRINT_NEWLINE_TO:
1264 w = stream = POP();
1265 /* fall through to PRINT_NEWLINE */
1267 case PRINT_NEWLINE:
1268 if (stream == NULL || stream == Py_None) {
1269 w = PySys_GetObject("stdout");
1270 if (w == NULL)
1271 PyErr_SetString(PyExc_RuntimeError,
1272 "lost sys.stdout");
1274 if (w != NULL) {
1275 err = PyFile_WriteString("\n", w);
1276 if (err == 0)
1277 PyFile_SoftSpace(w, 0);
1279 Py_XDECREF(stream);
1280 stream = NULL;
1281 break;
1284 #ifdef CASE_TOO_BIG
1285 default: switch (opcode) {
1286 #endif
1287 case BREAK_LOOP:
1288 why = WHY_BREAK;
1289 break;
1291 case RAISE_VARARGS:
1292 u = v = w = NULL;
1293 switch (oparg) {
1294 case 3:
1295 u = POP(); /* traceback */
1296 /* Fallthrough */
1297 case 2:
1298 v = POP(); /* value */
1299 /* Fallthrough */
1300 case 1:
1301 w = POP(); /* exc */
1302 case 0: /* Fallthrough */
1303 why = do_raise(w, v, u);
1304 break;
1305 default:
1306 PyErr_SetString(PyExc_SystemError,
1307 "bad RAISE_VARARGS oparg");
1308 why = WHY_EXCEPTION;
1309 break;
1311 break;
1313 case LOAD_LOCALS:
1314 if ((x = f->f_locals) == NULL) {
1315 PyErr_SetString(PyExc_SystemError,
1316 "no locals");
1317 break;
1319 Py_INCREF(x);
1320 PUSH(x);
1321 break;
1323 case RETURN_VALUE:
1324 retval = POP();
1325 why = WHY_RETURN;
1326 break;
1328 case EXEC_STMT:
1329 w = POP();
1330 v = POP();
1331 u = POP();
1332 err = exec_statement(f, u, v, w);
1333 Py_DECREF(u);
1334 Py_DECREF(v);
1335 Py_DECREF(w);
1336 break;
1338 case POP_BLOCK:
1340 PyTryBlock *b = PyFrame_BlockPop(f);
1341 while (STACK_LEVEL() > b->b_level) {
1342 v = POP();
1343 Py_DECREF(v);
1346 break;
1348 case END_FINALLY:
1349 v = POP();
1350 if (PyInt_Check(v)) {
1351 why = (enum why_code) PyInt_AsLong(v);
1352 if (why == WHY_RETURN)
1353 retval = POP();
1355 else if (PyString_Check(v) || PyClass_Check(v)) {
1356 w = POP();
1357 u = POP();
1358 PyErr_Restore(v, w, u);
1359 why = WHY_RERAISE;
1360 break;
1362 else if (v != Py_None) {
1363 PyErr_SetString(PyExc_SystemError,
1364 "'finally' pops bad exception");
1365 why = WHY_EXCEPTION;
1367 Py_DECREF(v);
1368 break;
1370 case BUILD_CLASS:
1371 u = POP();
1372 v = POP();
1373 w = POP();
1374 x = build_class(u, v, w);
1375 PUSH(x);
1376 Py_DECREF(u);
1377 Py_DECREF(v);
1378 Py_DECREF(w);
1379 break;
1381 case STORE_NAME:
1382 w = GETNAMEV(oparg);
1383 v = POP();
1384 if ((x = f->f_locals) == NULL) {
1385 PyErr_SetString(PyExc_SystemError,
1386 "no locals");
1387 break;
1389 err = PyDict_SetItem(x, w, v);
1390 Py_DECREF(v);
1391 break;
1393 case DELETE_NAME:
1394 w = GETNAMEV(oparg);
1395 if ((x = f->f_locals) == NULL) {
1396 PyErr_SetString(PyExc_SystemError,
1397 "no locals");
1398 break;
1400 if ((err = PyDict_DelItem(x, w)) != 0)
1401 format_exc_check_arg(PyExc_NameError,
1402 NAME_ERROR_MSG ,w);
1403 break;
1405 case UNPACK_SEQUENCE:
1406 v = POP();
1407 if (PyTuple_Check(v)) {
1408 if (PyTuple_Size(v) != oparg) {
1409 PyErr_SetString(PyExc_ValueError,
1410 "unpack tuple of wrong size");
1411 why = WHY_EXCEPTION;
1413 else {
1414 for (; --oparg >= 0; ) {
1415 w = PyTuple_GET_ITEM(v, oparg);
1416 Py_INCREF(w);
1417 PUSH(w);
1421 else if (PyList_Check(v)) {
1422 if (PyList_Size(v) != oparg) {
1423 PyErr_SetString(PyExc_ValueError,
1424 "unpack list of wrong size");
1425 why = WHY_EXCEPTION;
1427 else {
1428 for (; --oparg >= 0; ) {
1429 w = PyList_GET_ITEM(v, oparg);
1430 Py_INCREF(w);
1431 PUSH(w);
1435 else if (PySequence_Check(v)) {
1436 if (unpack_sequence(v, oparg,
1437 stack_pointer + oparg))
1438 stack_pointer += oparg;
1439 else
1440 why = WHY_EXCEPTION;
1442 else {
1443 PyErr_SetString(PyExc_TypeError,
1444 "unpack non-sequence");
1445 why = WHY_EXCEPTION;
1447 Py_DECREF(v);
1448 break;
1450 case STORE_ATTR:
1451 w = GETNAMEV(oparg);
1452 v = POP();
1453 u = POP();
1454 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1455 Py_DECREF(v);
1456 Py_DECREF(u);
1457 break;
1459 case DELETE_ATTR:
1460 w = GETNAMEV(oparg);
1461 v = POP();
1462 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
1463 /* del v.w */
1464 Py_DECREF(v);
1465 break;
1467 case STORE_GLOBAL:
1468 w = GETNAMEV(oparg);
1469 v = POP();
1470 err = PyDict_SetItem(f->f_globals, w, v);
1471 Py_DECREF(v);
1472 break;
1474 case DELETE_GLOBAL:
1475 w = GETNAMEV(oparg);
1476 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
1477 format_exc_check_arg(
1478 PyExc_NameError, NAME_ERROR_MSG ,w);
1479 break;
1481 case LOAD_CONST:
1482 x = GETCONST(oparg);
1483 Py_INCREF(x);
1484 PUSH(x);
1485 break;
1487 case LOAD_NAME:
1488 w = GETNAMEV(oparg);
1489 if ((x = f->f_locals) == NULL) {
1490 PyErr_SetString(PyExc_SystemError,
1491 "no locals");
1492 break;
1494 x = PyDict_GetItem(x, w);
1495 if (x == NULL) {
1496 x = PyDict_GetItem(f->f_globals, w);
1497 if (x == NULL) {
1498 x = PyDict_GetItem(f->f_builtins, w);
1499 if (x == NULL) {
1500 format_exc_check_arg(
1501 PyExc_NameError,
1502 NAME_ERROR_MSG ,w);
1503 break;
1507 Py_INCREF(x);
1508 PUSH(x);
1509 break;
1511 case LOAD_GLOBAL:
1512 w = GETNAMEV(oparg);
1513 x = PyDict_GetItem(f->f_globals, w);
1514 if (x == NULL) {
1515 x = PyDict_GetItem(f->f_builtins, w);
1516 if (x == NULL) {
1517 format_exc_check_arg(
1518 PyExc_NameError,
1519 NAME_ERROR_MSG ,w);
1520 break;
1523 Py_INCREF(x);
1524 PUSH(x);
1525 break;
1527 case LOAD_FAST:
1528 x = GETLOCAL(oparg);
1529 if (x == NULL) {
1530 format_exc_check_arg(
1531 PyExc_UnboundLocalError,
1532 UNBOUNDLOCAL_ERROR_MSG,
1533 PyTuple_GetItem(co->co_varnames, oparg)
1535 break;
1537 Py_INCREF(x);
1538 PUSH(x);
1539 if (x != NULL) continue;
1540 break;
1542 case STORE_FAST:
1543 v = POP();
1544 SETLOCAL(oparg, v);
1545 continue;
1547 case DELETE_FAST:
1548 x = GETLOCAL(oparg);
1549 if (x == NULL) {
1550 format_exc_check_arg(
1551 PyExc_UnboundLocalError,
1552 UNBOUNDLOCAL_ERROR_MSG,
1553 PyTuple_GetItem(co->co_varnames, oparg)
1555 break;
1557 SETLOCAL(oparg, NULL);
1558 continue;
1560 case BUILD_TUPLE:
1561 x = PyTuple_New(oparg);
1562 if (x != NULL) {
1563 for (; --oparg >= 0;) {
1564 w = POP();
1565 PyTuple_SET_ITEM(x, oparg, w);
1567 PUSH(x);
1568 continue;
1570 break;
1572 case BUILD_LIST:
1573 x = PyList_New(oparg);
1574 if (x != NULL) {
1575 for (; --oparg >= 0;) {
1576 w = POP();
1577 PyList_SET_ITEM(x, oparg, w);
1579 PUSH(x);
1580 continue;
1582 break;
1584 case BUILD_MAP:
1585 x = PyDict_New();
1586 PUSH(x);
1587 if (x != NULL) continue;
1588 break;
1590 case LOAD_ATTR:
1591 w = GETNAMEV(oparg);
1592 v = POP();
1593 x = PyObject_GetAttr(v, w);
1594 Py_DECREF(v);
1595 PUSH(x);
1596 if (x != NULL) continue;
1597 break;
1599 case COMPARE_OP:
1600 w = POP();
1601 v = POP();
1602 if (PyInt_Check(v) && PyInt_Check(w)) {
1603 /* INLINE: cmp(int, int) */
1604 register long a, b;
1605 register int res;
1606 a = PyInt_AS_LONG(v);
1607 b = PyInt_AS_LONG(w);
1608 switch (oparg) {
1609 case LT: res = a < b; break;
1610 case LE: res = a <= b; break;
1611 case EQ: res = a == b; break;
1612 case NE: res = a != b; break;
1613 case GT: res = a > b; break;
1614 case GE: res = a >= b; break;
1615 case IS: res = v == w; break;
1616 case IS_NOT: res = v != w; break;
1617 default: goto slow_compare;
1619 x = res ? Py_True : Py_False;
1620 Py_INCREF(x);
1622 else {
1623 slow_compare:
1624 x = cmp_outcome(oparg, v, w);
1626 Py_DECREF(v);
1627 Py_DECREF(w);
1628 PUSH(x);
1629 if (x != NULL) continue;
1630 break;
1632 case IMPORT_NAME:
1633 w = GETNAMEV(oparg);
1634 x = PyDict_GetItemString(f->f_builtins, "__import__");
1635 if (x == NULL) {
1636 PyErr_SetString(PyExc_ImportError,
1637 "__import__ not found");
1638 break;
1640 u = POP();
1641 w = Py_BuildValue("(OOOO)",
1643 f->f_globals,
1644 f->f_locals == NULL ?
1645 Py_None : f->f_locals,
1647 Py_DECREF(u);
1648 if (w == NULL) {
1649 x = NULL;
1650 break;
1652 x = PyEval_CallObject(x, w);
1653 Py_DECREF(w);
1654 PUSH(x);
1655 if (x != NULL) continue;
1656 break;
1658 case IMPORT_STAR:
1659 v = POP();
1660 PyFrame_FastToLocals(f);
1661 if ((x = f->f_locals) == NULL) {
1662 PyErr_SetString(PyExc_SystemError,
1663 "no locals");
1664 break;
1666 err = import_all_from(x, v);
1667 PyFrame_LocalsToFast(f, 0);
1668 Py_DECREF(v);
1669 if (err == 0) continue;
1670 break;
1672 case IMPORT_FROM:
1673 w = GETNAMEV(oparg);
1674 v = TOP();
1675 x = import_from(v, w);
1676 PUSH(x);
1677 if (x != NULL) continue;
1678 break;
1680 case JUMP_FORWARD:
1681 JUMPBY(oparg);
1682 continue;
1684 case JUMP_IF_FALSE:
1685 err = PyObject_IsTrue(TOP());
1686 if (err > 0)
1687 err = 0;
1688 else if (err == 0)
1689 JUMPBY(oparg);
1690 else
1691 break;
1692 continue;
1694 case JUMP_IF_TRUE:
1695 err = PyObject_IsTrue(TOP());
1696 if (err > 0) {
1697 err = 0;
1698 JUMPBY(oparg);
1700 else if (err == 0)
1702 else
1703 break;
1704 continue;
1706 case JUMP_ABSOLUTE:
1707 JUMPTO(oparg);
1708 continue;
1710 case FOR_LOOP:
1711 /* for v in s: ...
1712 On entry: stack contains s, i.
1713 On exit: stack contains s, i+1, s[i];
1714 but if loop exhausted:
1715 s, i are popped, and we jump */
1716 w = POP(); /* Loop index */
1717 v = POP(); /* Sequence object */
1718 u = loop_subscript(v, w);
1719 if (u != NULL) {
1720 PUSH(v);
1721 x = PyInt_FromLong(PyInt_AsLong(w)+1);
1722 PUSH(x);
1723 Py_DECREF(w);
1724 PUSH(u);
1725 if (x != NULL) continue;
1727 else {
1728 Py_DECREF(v);
1729 Py_DECREF(w);
1730 /* A NULL can mean "s exhausted"
1731 but also an error: */
1732 if (PyErr_Occurred())
1733 why = WHY_EXCEPTION;
1734 else {
1735 JUMPBY(oparg);
1736 continue;
1739 break;
1741 case SETUP_LOOP:
1742 case SETUP_EXCEPT:
1743 case SETUP_FINALLY:
1744 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
1745 STACK_LEVEL());
1746 continue;
1748 case SET_LINENO:
1749 #ifdef LLTRACE
1750 if (lltrace)
1751 printf("--- %s:%d \n", filename, oparg);
1752 #endif
1753 f->f_lineno = oparg;
1754 if (f->f_trace == NULL)
1755 continue;
1756 /* Trace each line of code reached */
1757 f->f_lasti = INSTR_OFFSET();
1758 err = call_trace(&f->f_trace, &f->f_trace,
1759 f, "line", Py_None);
1760 break;
1762 case CALL_FUNCTION:
1763 case CALL_FUNCTION_VAR:
1764 case CALL_FUNCTION_KW:
1765 case CALL_FUNCTION_VAR_KW:
1767 int na = oparg & 0xff;
1768 int nk = (oparg>>8) & 0xff;
1769 int flags = (opcode - CALL_FUNCTION) & 3;
1770 int n = na + 2*nk + (flags & 1) + ((flags >> 1) & 1);
1771 PyObject **pfunc = stack_pointer - n - 1;
1772 PyObject *func = *pfunc;
1773 PyObject *self = NULL;
1774 PyObject *class = NULL;
1775 f->f_lasti = INSTR_OFFSET() - 3; /* For tracing */
1776 if (PyMethod_Check(func)) {
1777 self = PyMethod_Self(func);
1778 class = PyMethod_Class(func);
1779 func = PyMethod_Function(func);
1780 Py_INCREF(func);
1781 if (self != NULL) {
1782 Py_INCREF(self);
1783 Py_DECREF(*pfunc);
1784 *pfunc = self;
1785 na++;
1786 n++;
1788 else {
1789 /* Unbound methods must be called with an
1790 instance of the class (or a derived
1791 class) as first argument */
1792 if (na > 0 && (self = stack_pointer[-n]) != NULL
1793 && PyInstance_Check(self)
1794 && PyClass_IsSubclass((PyObject *)
1795 (((PyInstanceObject *)self)->in_class),
1796 class))
1797 /* Handy-dandy */ ;
1798 else {
1799 PyErr_SetString(PyExc_TypeError,
1800 "unbound method must be called with class instance 1st argument");
1801 x = NULL;
1802 break;
1806 else
1807 Py_INCREF(func);
1808 if (PyFunction_Check(func) && flags == 0) {
1809 PyObject *co = PyFunction_GetCode(func);
1810 PyObject *globals = PyFunction_GetGlobals(func);
1811 PyObject *argdefs = PyFunction_GetDefaults(func);
1812 PyObject **d;
1813 int nd;
1814 if (argdefs != NULL) {
1815 d = &PyTuple_GET_ITEM(argdefs, 0);
1816 nd = ((PyTupleObject *)argdefs)->ob_size;
1818 else {
1819 d = NULL;
1820 nd = 0;
1822 x = eval_code2((PyCodeObject *)co, globals,
1823 (PyObject *)NULL, stack_pointer-n, na,
1824 stack_pointer-2*nk, nk, d, nd,
1825 class);
1827 else {
1828 int nstar = 0;
1829 PyObject *callargs;
1830 PyObject *stararg = 0;
1831 PyObject *kwdict = NULL;
1832 if (flags & 2) {
1833 kwdict = POP();
1834 if (!PyDict_Check(kwdict)) {
1835 PyErr_SetString(PyExc_TypeError,
1836 "** argument must be a dictionary");
1837 goto extcall_fail;
1840 if (flags & 1) {
1841 stararg = POP();
1842 if (!PySequence_Check(stararg)) {
1843 PyErr_SetString(PyExc_TypeError,
1844 "* argument must be a sequence");
1845 goto extcall_fail;
1847 /* Convert abstract sequence to concrete tuple */
1848 if (!PyTuple_Check(stararg)) {
1849 PyObject *t = NULL;
1850 t = PySequence_Tuple(stararg);
1851 if (t == NULL) {
1852 goto extcall_fail;
1854 Py_DECREF(stararg);
1855 stararg = t;
1857 nstar = PyTuple_GET_SIZE(stararg);
1858 if (nstar < 0) {
1859 goto extcall_fail;
1862 if (nk > 0) {
1863 if (kwdict == NULL) {
1864 kwdict = PyDict_New();
1865 if (kwdict == NULL) {
1866 goto extcall_fail;
1869 else {
1870 PyObject *d = PyDict_Copy(kwdict);
1871 if (d == NULL) {
1872 goto extcall_fail;
1874 Py_DECREF(kwdict);
1875 kwdict = d;
1877 err = 0;
1878 while (--nk >= 0) {
1879 PyObject *value = POP();
1880 PyObject *key = POP();
1881 if (PyDict_GetItem(kwdict, key) != NULL) {
1882 err = 1;
1883 PyErr_Format(PyExc_TypeError,
1884 "keyword parameter redefined: %.400s",
1885 PyString_AsString(key));
1886 Py_DECREF(key);
1887 Py_DECREF(value);
1888 goto extcall_fail;
1890 err = PyDict_SetItem(kwdict, key, value);
1891 Py_DECREF(key);
1892 Py_DECREF(value);
1893 if (err)
1894 break;
1896 if (err) {
1897 extcall_fail:
1898 Py_XDECREF(kwdict);
1899 Py_XDECREF(stararg);
1900 Py_DECREF(func);
1901 x=NULL;
1902 break;
1905 callargs = PyTuple_New(na + nstar);
1906 if (callargs == NULL) {
1907 x = NULL;
1908 break;
1910 if (stararg) {
1911 int i;
1912 for (i = 0; i < nstar; i++) {
1913 PyObject *a = PyTuple_GET_ITEM(stararg, i);
1914 Py_INCREF(a);
1915 PyTuple_SET_ITEM(callargs, na + i, a);
1917 Py_DECREF(stararg);
1919 while (--na >= 0) {
1920 w = POP();
1921 PyTuple_SET_ITEM(callargs, na, w);
1923 x = PyEval_CallObjectWithKeywords(func,
1924 callargs,
1925 kwdict);
1926 Py_DECREF(callargs);
1927 Py_XDECREF(kwdict);
1929 Py_DECREF(func);
1930 while (stack_pointer > pfunc) {
1931 w = POP();
1932 Py_DECREF(w);
1934 PUSH(x);
1935 if (x != NULL) continue;
1936 break;
1939 case MAKE_FUNCTION:
1940 v = POP(); /* code object */
1941 x = PyFunction_New(v, f->f_globals);
1942 Py_DECREF(v);
1943 /* XXX Maybe this should be a separate opcode? */
1944 if (x != NULL && oparg > 0) {
1945 v = PyTuple_New(oparg);
1946 if (v == NULL) {
1947 Py_DECREF(x);
1948 x = NULL;
1949 break;
1951 while (--oparg >= 0) {
1952 w = POP();
1953 PyTuple_SET_ITEM(v, oparg, w);
1955 err = PyFunction_SetDefaults(x, v);
1956 Py_DECREF(v);
1958 PUSH(x);
1959 break;
1961 case BUILD_SLICE:
1962 if (oparg == 3)
1963 w = POP();
1964 else
1965 w = NULL;
1966 v = POP();
1967 u = POP();
1968 x = PySlice_New(u, v, w);
1969 Py_DECREF(u);
1970 Py_DECREF(v);
1971 Py_XDECREF(w);
1972 PUSH(x);
1973 if (x != NULL) continue;
1974 break;
1976 case EXTENDED_ARG:
1977 opcode = NEXTOP();
1978 oparg = oparg<<16 | NEXTARG();
1979 goto dispatch_opcode;
1980 break;
1982 default:
1983 fprintf(stderr,
1984 "XXX lineno: %d, opcode: %d\n",
1985 f->f_lineno, opcode);
1986 PyErr_SetString(PyExc_SystemError, "unknown opcode");
1987 why = WHY_EXCEPTION;
1988 break;
1990 #ifdef CASE_TOO_BIG
1992 #endif
1994 } /* switch */
1996 on_error:
1998 /* Quickly continue if no error occurred */
2000 if (why == WHY_NOT) {
2001 if (err == 0 && x != NULL) {
2002 #ifdef CHECKEXC
2003 /* This check is expensive! */
2004 if (PyErr_Occurred())
2005 fprintf(stderr,
2006 "XXX undetected error\n");
2007 else
2008 #endif
2009 continue; /* Normal, fast path */
2011 why = WHY_EXCEPTION;
2012 x = Py_None;
2013 err = 0;
2016 /* Double-check exception status */
2018 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2019 if (!PyErr_Occurred()) {
2020 PyErr_SetString(PyExc_SystemError,
2021 "error return without exception set");
2022 why = WHY_EXCEPTION;
2025 #ifdef CHECKEXC
2026 else {
2027 /* This check is expensive! */
2028 if (PyErr_Occurred()) {
2029 fprintf(stderr,
2030 "XXX undetected error (why=%d)\n",
2031 why);
2032 why = WHY_EXCEPTION;
2035 #endif
2037 /* Log traceback info if this is a real exception */
2039 if (why == WHY_EXCEPTION) {
2040 f->f_lasti = INSTR_OFFSET() - 1;
2041 if (HAS_ARG(opcode))
2042 f->f_lasti -= 2;
2043 PyTraceBack_Here(f);
2045 if (f->f_trace)
2046 call_exc_trace(&f->f_trace, &f->f_trace, f);
2047 if (tstate->sys_profilefunc)
2048 call_exc_trace(&tstate->sys_profilefunc,
2049 (PyObject**)0, f);
2052 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2054 if (why == WHY_RERAISE)
2055 why = WHY_EXCEPTION;
2057 /* Unwind stacks if a (pseudo) exception occurred */
2059 while (why != WHY_NOT && f->f_iblock > 0) {
2060 PyTryBlock *b = PyFrame_BlockPop(f);
2061 while (STACK_LEVEL() > b->b_level) {
2062 v = POP();
2063 Py_XDECREF(v);
2065 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2066 why = WHY_NOT;
2067 JUMPTO(b->b_handler);
2068 break;
2070 if (b->b_type == SETUP_FINALLY ||
2071 (b->b_type == SETUP_EXCEPT &&
2072 why == WHY_EXCEPTION)) {
2073 if (why == WHY_EXCEPTION) {
2074 PyObject *exc, *val, *tb;
2075 PyErr_Fetch(&exc, &val, &tb);
2076 if (val == NULL) {
2077 val = Py_None;
2078 Py_INCREF(val);
2080 /* Make the raw exception data
2081 available to the handler,
2082 so a program can emulate the
2083 Python main loop. Don't do
2084 this for 'finally'. */
2085 if (b->b_type == SETUP_EXCEPT) {
2086 PyErr_NormalizeException(
2087 &exc, &val, &tb);
2088 set_exc_info(tstate,
2089 exc, val, tb);
2091 PUSH(tb);
2092 PUSH(val);
2093 PUSH(exc);
2095 else {
2096 if (why == WHY_RETURN)
2097 PUSH(retval);
2098 v = PyInt_FromLong((long)why);
2099 PUSH(v);
2101 why = WHY_NOT;
2102 JUMPTO(b->b_handler);
2103 break;
2105 } /* unwind stack */
2107 /* End the loop if we still have an error (or return) */
2109 if (why != WHY_NOT)
2110 break;
2112 } /* main loop */
2114 /* Pop remaining stack entries */
2116 while (!EMPTY()) {
2117 v = POP();
2118 Py_XDECREF(v);
2121 if (why != WHY_RETURN)
2122 retval = NULL;
2124 if (f->f_trace) {
2125 if (why == WHY_RETURN) {
2126 if (call_trace(&f->f_trace, &f->f_trace, f,
2127 "return", retval)) {
2128 Py_XDECREF(retval);
2129 retval = NULL;
2130 why = WHY_EXCEPTION;
2135 if (tstate->sys_profilefunc && why == WHY_RETURN) {
2136 if (call_trace(&tstate->sys_profilefunc, (PyObject**)0,
2137 f, "return", retval)) {
2138 Py_XDECREF(retval);
2139 retval = NULL;
2140 why = WHY_EXCEPTION;
2144 reset_exc_info(tstate);
2146 --tstate->recursion_depth;
2148 fail: /* Jump here from prelude on failure */
2150 /* Restore previous frame and release the current one */
2152 tstate->frame = f->f_back;
2153 Py_DECREF(f);
2155 return retval;
2158 static void
2159 set_exc_info(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb)
2161 PyFrameObject *frame;
2162 PyObject *tmp_type, *tmp_value, *tmp_tb;
2164 frame = tstate->frame;
2165 if (frame->f_exc_type == NULL) {
2166 /* This frame didn't catch an exception before */
2167 /* Save previous exception of this thread in this frame */
2168 if (tstate->exc_type == NULL) {
2169 Py_INCREF(Py_None);
2170 tstate->exc_type = Py_None;
2172 tmp_type = frame->f_exc_type;
2173 tmp_value = frame->f_exc_value;
2174 tmp_tb = frame->f_exc_traceback;
2175 Py_XINCREF(tstate->exc_type);
2176 Py_XINCREF(tstate->exc_value);
2177 Py_XINCREF(tstate->exc_traceback);
2178 frame->f_exc_type = tstate->exc_type;
2179 frame->f_exc_value = tstate->exc_value;
2180 frame->f_exc_traceback = tstate->exc_traceback;
2181 Py_XDECREF(tmp_type);
2182 Py_XDECREF(tmp_value);
2183 Py_XDECREF(tmp_tb);
2185 /* Set new exception for this thread */
2186 tmp_type = tstate->exc_type;
2187 tmp_value = tstate->exc_value;
2188 tmp_tb = tstate->exc_traceback;
2189 Py_XINCREF(type);
2190 Py_XINCREF(value);
2191 Py_XINCREF(tb);
2192 tstate->exc_type = type;
2193 tstate->exc_value = value;
2194 tstate->exc_traceback = tb;
2195 Py_XDECREF(tmp_type);
2196 Py_XDECREF(tmp_value);
2197 Py_XDECREF(tmp_tb);
2198 /* For b/w compatibility */
2199 PySys_SetObject("exc_type", type);
2200 PySys_SetObject("exc_value", value);
2201 PySys_SetObject("exc_traceback", tb);
2204 static void
2205 reset_exc_info(PyThreadState *tstate)
2207 PyFrameObject *frame;
2208 PyObject *tmp_type, *tmp_value, *tmp_tb;
2209 frame = tstate->frame;
2210 if (frame->f_exc_type != NULL) {
2211 /* This frame caught an exception */
2212 tmp_type = tstate->exc_type;
2213 tmp_value = tstate->exc_value;
2214 tmp_tb = tstate->exc_traceback;
2215 Py_XINCREF(frame->f_exc_type);
2216 Py_XINCREF(frame->f_exc_value);
2217 Py_XINCREF(frame->f_exc_traceback);
2218 tstate->exc_type = frame->f_exc_type;
2219 tstate->exc_value = frame->f_exc_value;
2220 tstate->exc_traceback = frame->f_exc_traceback;
2221 Py_XDECREF(tmp_type);
2222 Py_XDECREF(tmp_value);
2223 Py_XDECREF(tmp_tb);
2224 /* For b/w compatibility */
2225 PySys_SetObject("exc_type", frame->f_exc_type);
2226 PySys_SetObject("exc_value", frame->f_exc_value);
2227 PySys_SetObject("exc_traceback", frame->f_exc_traceback);
2229 tmp_type = frame->f_exc_type;
2230 tmp_value = frame->f_exc_value;
2231 tmp_tb = frame->f_exc_traceback;
2232 frame->f_exc_type = NULL;
2233 frame->f_exc_value = NULL;
2234 frame->f_exc_traceback = NULL;
2235 Py_XDECREF(tmp_type);
2236 Py_XDECREF(tmp_value);
2237 Py_XDECREF(tmp_tb);
2240 /* Logic for the raise statement (too complicated for inlining).
2241 This *consumes* a reference count to each of its arguments. */
2242 static enum why_code
2243 do_raise(PyObject *type, PyObject *value, PyObject *tb)
2245 if (type == NULL) {
2246 /* Reraise */
2247 PyThreadState *tstate = PyThreadState_Get();
2248 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
2249 value = tstate->exc_value;
2250 tb = tstate->exc_traceback;
2251 Py_XINCREF(type);
2252 Py_XINCREF(value);
2253 Py_XINCREF(tb);
2256 /* We support the following forms of raise:
2257 raise <class>, <classinstance>
2258 raise <class>, <argument tuple>
2259 raise <class>, None
2260 raise <class>, <argument>
2261 raise <classinstance>, None
2262 raise <string>, <object>
2263 raise <string>, None
2265 An omitted second argument is the same as None.
2267 In addition, raise <tuple>, <anything> is the same as
2268 raising the tuple's first item (and it better have one!);
2269 this rule is applied recursively.
2271 Finally, an optional third argument can be supplied, which
2272 gives the traceback to be substituted (useful when
2273 re-raising an exception after examining it). */
2275 /* First, check the traceback argument, replacing None with
2276 NULL. */
2277 if (tb == Py_None) {
2278 Py_DECREF(tb);
2279 tb = NULL;
2281 else if (tb != NULL && !PyTraceBack_Check(tb)) {
2282 PyErr_SetString(PyExc_TypeError,
2283 "raise 3rd arg must be traceback or None");
2284 goto raise_error;
2287 /* Next, replace a missing value with None */
2288 if (value == NULL) {
2289 value = Py_None;
2290 Py_INCREF(value);
2293 /* Next, repeatedly, replace a tuple exception with its first item */
2294 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
2295 PyObject *tmp = type;
2296 type = PyTuple_GET_ITEM(type, 0);
2297 Py_INCREF(type);
2298 Py_DECREF(tmp);
2301 if (PyString_Check(type))
2304 else if (PyClass_Check(type))
2305 PyErr_NormalizeException(&type, &value, &tb);
2307 else if (PyInstance_Check(type)) {
2308 /* Raising an instance. The value should be a dummy. */
2309 if (value != Py_None) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "instance exception may not have a separate value");
2312 goto raise_error;
2314 else {
2315 /* Normalize to raise <class>, <instance> */
2316 Py_DECREF(value);
2317 value = type;
2318 type = (PyObject*) ((PyInstanceObject*)type)->in_class;
2319 Py_INCREF(type);
2322 else {
2323 /* Not something you can raise. You get an exception
2324 anyway, just not what you specified :-) */
2325 PyErr_SetString(PyExc_TypeError,
2326 "exceptions must be strings, classes, or instances");
2327 goto raise_error;
2329 PyErr_Restore(type, value, tb);
2330 if (tb == NULL)
2331 return WHY_EXCEPTION;
2332 else
2333 return WHY_RERAISE;
2334 raise_error:
2335 Py_XDECREF(value);
2336 Py_XDECREF(type);
2337 Py_XDECREF(tb);
2338 return WHY_EXCEPTION;
2341 static int
2342 unpack_sequence(PyObject *v, int argcnt, PyObject **sp)
2344 int i;
2345 PyObject *w;
2347 for (i = 0; i < argcnt; i++) {
2348 if (! (w = PySequence_GetItem(v, i))) {
2349 if (PyErr_ExceptionMatches(PyExc_IndexError))
2350 PyErr_SetString(PyExc_ValueError,
2351 "unpack sequence of wrong size");
2352 goto finally;
2354 *--sp = w;
2356 /* we better get an IndexError now */
2357 if (PySequence_GetItem(v, i) == NULL) {
2358 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2359 PyErr_Clear();
2360 return 1;
2362 /* some other exception occurred. fall through to finally */
2364 else
2365 PyErr_SetString(PyExc_ValueError,
2366 "unpack sequence of wrong size");
2367 /* fall through */
2368 finally:
2369 for (; i > 0; i--, sp++)
2370 Py_DECREF(*sp);
2372 return 0;
2376 #ifdef LLTRACE
2377 static int
2378 prtrace(PyObject *v, char *str)
2380 printf("%s ", str);
2381 if (PyObject_Print(v, stdout, 0) != 0)
2382 PyErr_Clear(); /* Don't know what else to do */
2383 printf("\n");
2384 return 1;
2386 #endif
2388 static void
2389 call_exc_trace(PyObject **p_trace, PyObject **p_newtrace, PyFrameObject *f)
2391 PyObject *type, *value, *traceback, *arg;
2392 int err;
2393 PyErr_Fetch(&type, &value, &traceback);
2394 if (value == NULL) {
2395 value = Py_None;
2396 Py_INCREF(value);
2398 arg = Py_BuildValue("(OOO)", type, value, traceback);
2399 if (arg == NULL) {
2400 PyErr_Restore(type, value, traceback);
2401 return;
2403 err = call_trace(p_trace, p_newtrace, f, "exception", arg);
2404 Py_DECREF(arg);
2405 if (err == 0)
2406 PyErr_Restore(type, value, traceback);
2407 else {
2408 Py_XDECREF(type);
2409 Py_XDECREF(value);
2410 Py_XDECREF(traceback);
2414 /* PyObject **p_trace: in/out; may not be NULL;
2415 may not point to NULL variable initially
2416 PyObject **p_newtrace: in/out; may be NULL;
2417 may point to NULL variable;
2418 may be same variable as p_newtrace */
2420 static int
2421 call_trace(PyObject **p_trace, PyObject **p_newtrace, PyFrameObject *f,
2422 char *msg, PyObject *arg)
2424 PyThreadState *tstate = f->f_tstate;
2425 PyObject *args, *what;
2426 PyObject *res = NULL;
2428 if (tstate->tracing) {
2429 /* Don't do recursive traces */
2430 if (p_newtrace) {
2431 Py_XDECREF(*p_newtrace);
2432 *p_newtrace = NULL;
2434 return 0;
2437 args = PyTuple_New(3);
2438 if (args == NULL)
2439 goto cleanup;
2440 what = PyString_FromString(msg);
2441 if (what == NULL)
2442 goto cleanup;
2443 Py_INCREF(f);
2444 PyTuple_SET_ITEM(args, 0, (PyObject *)f);
2445 PyTuple_SET_ITEM(args, 1, what);
2446 if (arg == NULL)
2447 arg = Py_None;
2448 Py_INCREF(arg);
2449 PyTuple_SET_ITEM(args, 2, arg);
2450 tstate->tracing++;
2451 PyFrame_FastToLocals(f);
2452 res = PyEval_CallObject(*p_trace, args); /* May clear *p_trace! */
2453 PyFrame_LocalsToFast(f, 1);
2454 tstate->tracing--;
2455 cleanup:
2456 Py_XDECREF(args);
2457 if (res == NULL) {
2458 /* The trace proc raised an exception */
2459 PyTraceBack_Here(f);
2460 Py_XDECREF(*p_trace);
2461 *p_trace = NULL;
2462 if (p_newtrace) {
2463 Py_XDECREF(*p_newtrace);
2464 *p_newtrace = NULL;
2466 /* to be extra double plus sure we don't get recursive
2467 * calls inf either tracefunc or profilefunc gets an
2468 * exception, zap the global variables.
2470 Py_XDECREF(tstate->sys_tracefunc);
2471 tstate->sys_tracefunc = NULL;
2472 Py_XDECREF(tstate->sys_profilefunc);
2473 tstate->sys_profilefunc = NULL;
2474 return -1;
2476 else {
2477 if (p_newtrace) {
2478 Py_XDECREF(*p_newtrace);
2479 if (res == Py_None)
2480 *p_newtrace = NULL;
2481 else {
2482 Py_INCREF(res);
2483 *p_newtrace = res;
2486 Py_DECREF(res);
2487 return 0;
2491 PyObject *
2492 PyEval_GetBuiltins(void)
2494 PyThreadState *tstate = PyThreadState_Get();
2495 PyFrameObject *current_frame = tstate->frame;
2496 if (current_frame == NULL)
2497 return tstate->interp->builtins;
2498 else
2499 return current_frame->f_builtins;
2502 PyObject *
2503 PyEval_GetLocals(void)
2505 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2506 if (current_frame == NULL)
2507 return NULL;
2508 PyFrame_FastToLocals(current_frame);
2509 return current_frame->f_locals;
2512 PyObject *
2513 PyEval_GetGlobals(void)
2515 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2516 if (current_frame == NULL)
2517 return NULL;
2518 else
2519 return current_frame->f_globals;
2522 PyObject *
2523 PyEval_GetFrame(void)
2525 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2526 return (PyObject *)current_frame;
2530 PyEval_GetRestricted(void)
2532 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2533 return current_frame == NULL ? 0 : current_frame->f_restricted;
2537 Py_FlushLine(void)
2539 PyObject *f = PySys_GetObject("stdout");
2540 if (f == NULL)
2541 return 0;
2542 if (!PyFile_SoftSpace(f, 0))
2543 return 0;
2544 return PyFile_WriteString("\n", f);
2548 /* External interface to call any callable object.
2549 The arg must be a tuple or NULL. */
2551 #undef PyEval_CallObject
2552 /* for backward compatibility: export this interface */
2554 PyObject *
2555 PyEval_CallObject(PyObject *func, PyObject *arg)
2557 return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL);
2559 #define PyEval_CallObject(func,arg) \
2560 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
2562 PyObject *
2563 PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
2565 ternaryfunc call;
2566 PyObject *result;
2568 if (arg == NULL)
2569 arg = PyTuple_New(0);
2570 else if (!PyTuple_Check(arg)) {
2571 PyErr_SetString(PyExc_TypeError,
2572 "argument list must be a tuple");
2573 return NULL;
2575 else
2576 Py_INCREF(arg);
2578 if (kw != NULL && !PyDict_Check(kw)) {
2579 PyErr_SetString(PyExc_TypeError,
2580 "keyword list must be a dictionary");
2581 Py_DECREF(arg);
2582 return NULL;
2585 if ((call = func->ob_type->tp_call) != NULL)
2586 result = (*call)(func, arg, kw);
2587 else if (PyMethod_Check(func) || PyFunction_Check(func))
2588 result = call_function(func, arg, kw);
2589 else
2590 result = call_builtin(func, arg, kw);
2592 Py_DECREF(arg);
2594 if (result == NULL && !PyErr_Occurred())
2595 PyErr_SetString(PyExc_SystemError,
2596 "NULL result without error in call_object");
2598 return result;
2601 static PyObject *
2602 call_builtin(PyObject *func, PyObject *arg, PyObject *kw)
2604 if (PyCFunction_Check(func)) {
2605 PyCFunction meth = PyCFunction_GetFunction(func);
2606 PyObject *self = PyCFunction_GetSelf(func);
2607 int flags = PyCFunction_GetFlags(func);
2608 if (!(flags & METH_VARARGS)) {
2609 int size = PyTuple_Size(arg);
2610 if (size == 1)
2611 arg = PyTuple_GET_ITEM(arg, 0);
2612 else if (size == 0)
2613 arg = NULL;
2615 if (flags & METH_KEYWORDS)
2616 return (*(PyCFunctionWithKeywords)meth)(self, arg, kw);
2617 if (kw != NULL && PyDict_Size(kw) != 0) {
2618 PyErr_SetString(PyExc_TypeError,
2619 "this function takes no keyword arguments");
2620 return NULL;
2622 return (*meth)(self, arg);
2624 if (PyClass_Check(func)) {
2625 return PyInstance_New(func, arg, kw);
2627 if (PyInstance_Check(func)) {
2628 PyObject *res, *call = PyObject_GetAttrString(func,"__call__");
2629 if (call == NULL) {
2630 PyErr_Clear();
2631 PyErr_SetString(PyExc_AttributeError,
2632 "no __call__ method defined");
2633 return NULL;
2635 res = PyEval_CallObjectWithKeywords(call, arg, kw);
2636 Py_DECREF(call);
2637 return res;
2639 PyErr_Format(PyExc_TypeError, "call of non-function (type %.400s)",
2640 func->ob_type->tp_name);
2641 return NULL;
2644 static PyObject *
2645 call_function(PyObject *func, PyObject *arg, PyObject *kw)
2647 PyObject *class = NULL; /* == owner */
2648 PyObject *argdefs;
2649 PyObject **d, **k;
2650 int nk, nd;
2651 PyObject *result;
2653 if (kw != NULL && !PyDict_Check(kw)) {
2654 PyErr_BadInternalCall();
2655 return NULL;
2658 if (PyMethod_Check(func)) {
2659 PyObject *self = PyMethod_Self(func);
2660 class = PyMethod_Class(func);
2661 func = PyMethod_Function(func);
2662 if (self == NULL) {
2663 /* Unbound methods must be called with an instance of
2664 the class (or a derived class) as first argument */
2665 if (PyTuple_Size(arg) >= 1) {
2666 self = PyTuple_GET_ITEM(arg, 0);
2667 if (self != NULL &&
2668 PyInstance_Check(self) &&
2669 PyClass_IsSubclass((PyObject *)
2670 (((PyInstanceObject *)self)->in_class),
2671 class))
2672 /* Handy-dandy */ ;
2673 else
2674 self = NULL;
2676 if (self == NULL) {
2677 PyErr_SetString(PyExc_TypeError,
2678 "unbound method must be called with class instance 1st argument");
2679 return NULL;
2681 Py_INCREF(arg);
2683 else {
2684 int argcount = PyTuple_Size(arg);
2685 PyObject *newarg = PyTuple_New(argcount + 1);
2686 int i;
2687 if (newarg == NULL)
2688 return NULL;
2689 Py_INCREF(self);
2690 PyTuple_SET_ITEM(newarg, 0, self);
2691 for (i = 0; i < argcount; i++) {
2692 PyObject *v = PyTuple_GET_ITEM(arg, i);
2693 Py_XINCREF(v);
2694 PyTuple_SET_ITEM(newarg, i+1, v);
2696 arg = newarg;
2698 if (!PyFunction_Check(func)) {
2699 result = PyEval_CallObjectWithKeywords(func, arg, kw);
2700 Py_DECREF(arg);
2701 return result;
2704 else {
2705 if (!PyFunction_Check(func)) {
2706 PyErr_Format(PyExc_TypeError,
2707 "call of non-function (type %.200s)",
2708 func->ob_type->tp_name);
2709 return NULL;
2711 Py_INCREF(arg);
2714 argdefs = PyFunction_GetDefaults(func);
2715 if (argdefs != NULL && PyTuple_Check(argdefs)) {
2716 d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
2717 nd = PyTuple_Size(argdefs);
2719 else {
2720 d = NULL;
2721 nd = 0;
2724 if (kw != NULL) {
2725 int pos, i;
2726 nk = PyDict_Size(kw);
2727 k = PyMem_NEW(PyObject *, 2*nk);
2728 if (k == NULL) {
2729 PyErr_NoMemory();
2730 Py_DECREF(arg);
2731 return NULL;
2733 pos = i = 0;
2734 while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
2735 i += 2;
2736 nk = i/2;
2737 /* XXX This is broken if the caller deletes dict items! */
2739 else {
2740 k = NULL;
2741 nk = 0;
2744 result = eval_code2(
2745 (PyCodeObject *)PyFunction_GetCode(func),
2746 PyFunction_GetGlobals(func), (PyObject *)NULL,
2747 &PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
2748 k, nk,
2749 d, nd,
2750 class);
2752 Py_DECREF(arg);
2753 if (k != NULL)
2754 PyMem_DEL(k);
2756 return result;
2759 #define SLICE_ERROR_MSG \
2760 "standard sequence type does not support step size other than one"
2762 static PyObject *
2763 loop_subscript(PyObject *v, PyObject *w)
2765 PySequenceMethods *sq = v->ob_type->tp_as_sequence;
2766 int i;
2767 if (sq == NULL || sq->sq_item == NULL) {
2768 PyErr_SetString(PyExc_TypeError, "loop over non-sequence");
2769 return NULL;
2771 i = PyInt_AsLong(w);
2772 v = (*sq->sq_item)(v, i);
2773 if (v)
2774 return v;
2775 if (PyErr_ExceptionMatches(PyExc_IndexError))
2776 PyErr_Clear();
2777 return NULL;
2780 /* Extract a slice index from a PyInt or PyLong, the index is bound to
2781 the range [-INT_MAX+1, INTMAX]. Returns 0 and an exception if there is
2782 and error. Returns 1 on success.*/
2785 _PyEval_SliceIndex(PyObject *v, int *pi)
2787 if (v != NULL) {
2788 long x;
2789 if (PyInt_Check(v)) {
2790 x = PyInt_AsLong(v);
2791 } else if (PyLong_Check(v)) {
2792 x = PyLong_AsLong(v);
2793 if (x==-1 && PyErr_Occurred()) {
2794 PyObject *long_zero;
2796 if (!PyErr_ExceptionMatches( PyExc_OverflowError ) ) {
2797 /* It's not an overflow error, so just
2798 signal an error */
2799 return 0;
2802 /* It's an overflow error, so we need to
2803 check the sign of the long integer,
2804 set the value to INT_MAX or 0, and clear
2805 the error. */
2807 /* Create a long integer with a value of 0 */
2808 long_zero = PyLong_FromLong( 0L );
2809 if (long_zero == NULL) return 0;
2811 /* Check sign */
2812 if (PyObject_Compare(long_zero, v) < 0)
2813 x = INT_MAX;
2814 else
2815 x = 0;
2817 /* Free the long integer we created, and clear the
2818 OverflowError */
2819 Py_DECREF(long_zero);
2820 PyErr_Clear();
2822 } else {
2823 PyErr_SetString(PyExc_TypeError,
2824 "slice index must be int");
2825 return 0;
2827 /* Truncate -- very long indices are truncated anyway */
2828 if (x > INT_MAX)
2829 x = INT_MAX;
2830 else if (x < -INT_MAX)
2831 x = 0;
2832 *pi = x;
2834 return 1;
2837 static PyObject *
2838 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
2840 int ilow = 0, ihigh = INT_MAX;
2841 if (!_PyEval_SliceIndex(v, &ilow))
2842 return NULL;
2843 if (!_PyEval_SliceIndex(w, &ihigh))
2844 return NULL;
2845 return PySequence_GetSlice(u, ilow, ihigh);
2848 static int
2849 assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x) /* u[v:w] = x */
2851 int ilow = 0, ihigh = INT_MAX;
2852 if (!_PyEval_SliceIndex(v, &ilow))
2853 return -1;
2854 if (!_PyEval_SliceIndex(w, &ihigh))
2855 return -1;
2856 if (x == NULL)
2857 return PySequence_DelSlice(u, ilow, ihigh);
2858 else
2859 return PySequence_SetSlice(u, ilow, ihigh, x);
2862 static PyObject *
2863 cmp_outcome(int op, register PyObject *v, register PyObject *w)
2865 register int cmp;
2866 register int res = 0;
2867 switch (op) {
2868 case IS:
2869 case IS_NOT:
2870 res = (v == w);
2871 if (op == (int) IS_NOT)
2872 res = !res;
2873 break;
2874 case IN:
2875 case NOT_IN:
2876 res = PySequence_Contains(w, v);
2877 if (res < 0)
2878 return NULL;
2879 if (op == (int) NOT_IN)
2880 res = !res;
2881 break;
2882 case EXC_MATCH:
2883 res = PyErr_GivenExceptionMatches(v, w);
2884 break;
2885 default:
2886 cmp = PyObject_Compare(v, w);
2887 if (cmp && PyErr_Occurred())
2888 return NULL;
2889 switch (op) {
2890 case LT: res = cmp < 0; break;
2891 case LE: res = cmp <= 0; break;
2892 case EQ: res = cmp == 0; break;
2893 case NE: res = cmp != 0; break;
2894 case GT: res = cmp > 0; break;
2895 case GE: res = cmp >= 0; break;
2896 /* XXX no default? (res is initialized to 0 though) */
2899 v = res ? Py_True : Py_False;
2900 Py_INCREF(v);
2901 return v;
2904 static PyObject *
2905 import_from(PyObject *v, PyObject *name)
2907 PyObject *w, *x;
2908 if (!PyModule_Check(v)) {
2909 PyErr_SetString(PyExc_TypeError,
2910 "import-from requires module object");
2911 return NULL;
2913 w = PyModule_GetDict(v); /* TDB: can this not fail ? */
2914 x = PyDict_GetItem(w, name);
2915 if (x == NULL) {
2916 PyErr_Format(PyExc_ImportError,
2917 "cannot import name %.230s",
2918 PyString_AsString(name));
2919 } else
2920 Py_INCREF(x);
2921 return x;
2924 static int
2925 import_all_from(PyObject *locals, PyObject *v)
2927 int pos = 0, err;
2928 PyObject *name, *value;
2929 PyObject *w;
2931 if (!PyModule_Check(v)) {
2932 PyErr_SetString(PyExc_TypeError,
2933 "import-from requires module object");
2934 return -1;
2936 w = PyModule_GetDict(v); /* TBD: can this not fail ? */
2938 while (PyDict_Next(w, &pos, &name, &value)) {
2939 if (!PyString_Check(name) ||
2940 PyString_AsString(name)[0] == '_')
2941 continue;
2942 Py_INCREF(value);
2943 err = PyDict_SetItem(locals, name, value);
2944 Py_DECREF(value);
2945 if (err != 0)
2946 return -1;
2948 return 0;
2951 static PyObject *
2952 build_class(PyObject *methods, PyObject *bases, PyObject *name)
2954 int i, n;
2955 if (!PyTuple_Check(bases)) {
2956 PyErr_SetString(PyExc_SystemError,
2957 "build_class with non-tuple bases");
2958 return NULL;
2960 if (!PyDict_Check(methods)) {
2961 PyErr_SetString(PyExc_SystemError,
2962 "build_class with non-dictionary");
2963 return NULL;
2965 if (!PyString_Check(name)) {
2966 PyErr_SetString(PyExc_SystemError,
2967 "build_class with non-string name");
2968 return NULL;
2970 n = PyTuple_Size(bases);
2971 for (i = 0; i < n; i++) {
2972 PyObject *base = PyTuple_GET_ITEM(bases, i);
2973 if (!PyClass_Check(base)) {
2974 /* Call the base's *type*, if it is callable.
2975 This code is a hook for Donald Beaudry's
2976 and Jim Fulton's type extensions. In
2977 unextended Python it will never be triggered
2978 since its types are not callable.
2979 Ditto: call the bases's *class*, if it has
2980 one. This makes the same thing possible
2981 without writing C code. A true meta-object
2982 protocol! */
2983 PyObject *basetype = (PyObject *)base->ob_type;
2984 PyObject *callable = NULL;
2985 if (PyCallable_Check(basetype))
2986 callable = basetype;
2987 else
2988 callable = PyObject_GetAttrString(
2989 base, "__class__");
2990 if (callable) {
2991 PyObject *args;
2992 PyObject *newclass = NULL;
2993 args = Py_BuildValue(
2994 "(OOO)", name, bases, methods);
2995 if (args != NULL) {
2996 newclass = PyEval_CallObject(
2997 callable, args);
2998 Py_DECREF(args);
3000 if (callable != basetype) {
3001 Py_DECREF(callable);
3003 return newclass;
3005 PyErr_SetString(PyExc_TypeError,
3006 "base is not a class object");
3007 return NULL;
3010 return PyClass_New(bases, methods, name);
3013 static int
3014 exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
3015 PyObject *locals)
3017 int n;
3018 PyObject *v;
3019 int plain = 0;
3021 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
3022 ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
3023 /* Backward compatibility hack */
3024 globals = PyTuple_GetItem(prog, 1);
3025 if (n == 3)
3026 locals = PyTuple_GetItem(prog, 2);
3027 prog = PyTuple_GetItem(prog, 0);
3029 if (globals == Py_None) {
3030 globals = PyEval_GetGlobals();
3031 if (locals == Py_None) {
3032 locals = PyEval_GetLocals();
3033 plain = 1;
3036 else if (locals == Py_None)
3037 locals = globals;
3038 if (!PyString_Check(prog) &&
3039 !PyUnicode_Check(prog) &&
3040 !PyCode_Check(prog) &&
3041 !PyFile_Check(prog)) {
3042 PyErr_SetString(PyExc_TypeError,
3043 "exec 1st arg must be string, code or file object");
3044 return -1;
3046 if (!PyDict_Check(globals) || !PyDict_Check(locals)) {
3047 PyErr_SetString(PyExc_TypeError,
3048 "exec 2nd/3rd args must be dict or None");
3049 return -1;
3051 if (PyDict_GetItemString(globals, "__builtins__") == NULL)
3052 PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
3053 if (PyCode_Check(prog)) {
3054 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
3056 else if (PyFile_Check(prog)) {
3057 FILE *fp = PyFile_AsFile(prog);
3058 char *name = PyString_AsString(PyFile_Name(prog));
3059 v = PyRun_File(fp, name, Py_file_input, globals, locals);
3061 else {
3062 char *str;
3063 if (PyString_AsStringAndSize(prog, &str, NULL))
3064 return -1;
3065 v = PyRun_String(str, Py_file_input, globals, locals);
3067 if (plain)
3068 PyFrame_LocalsToFast(f, 0);
3069 if (v == NULL)
3070 return -1;
3071 Py_DECREF(v);
3072 return 0;
3075 static void
3076 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
3078 char *obj_str;
3080 if (!obj)
3081 return;
3083 obj_str = PyString_AsString(obj);
3084 if (!obj_str)
3085 return;
3087 PyErr_Format(exc, format_str, obj_str);
3090 #ifdef DYNAMIC_EXECUTION_PROFILE
3092 PyObject *
3093 getarray(long a[256])
3095 int i;
3096 PyObject *l = PyList_New(256);
3097 if (l == NULL) return NULL;
3098 for (i = 0; i < 256; i++) {
3099 PyObject *x = PyInt_FromLong(a[i]);
3100 if (x == NULL) {
3101 Py_DECREF(l);
3102 return NULL;
3104 PyList_SetItem(l, i, x);
3106 for (i = 0; i < 256; i++)
3107 a[i] = 0;
3108 return l;
3111 PyObject *
3112 _Py_GetDXProfile(PyObject *self, PyObject *args)
3114 #ifndef DXPAIRS
3115 return getarray(dxp);
3116 #else
3117 int i;
3118 PyObject *l = PyList_New(257);
3119 if (l == NULL) return NULL;
3120 for (i = 0; i < 257; i++) {
3121 PyObject *x = getarray(dxpairs[i]);
3122 if (x == NULL) {
3123 Py_DECREF(l);
3124 return NULL;
3126 PyList_SetItem(l, i, x);
3128 return l;
3129 #endif
3132 #endif