struct.pack has become picky about h (short) and H (unsigned short).
[python/dscho.git] / Python / ceval.c
bloba1c8190c752ce9404a446c2054505bbb27f6f949
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 */
581 w = NULL;
583 for (;;) {
584 /* Do periodic things. Doing this every time through
585 the loop would add too much overhead, so we do it
586 only every Nth instruction. We also do it if
587 ``things_to_do'' is set, i.e. when an asynchronous
588 event needs attention (e.g. a signal handler or
589 async I/O handler); see Py_AddPendingCall() and
590 Py_MakePendingCalls() above. */
592 if (things_to_do || --tstate->ticker < 0) {
593 tstate->ticker = tstate->interp->checkinterval;
594 if (things_to_do) {
595 if (Py_MakePendingCalls() < 0) {
596 why = WHY_EXCEPTION;
597 goto on_error;
600 #if !defined(HAVE_SIGNAL_H) || defined(macintosh)
601 /* If we have true signals, the signal handler
602 will call Py_AddPendingCall() so we don't
603 have to call sigcheck(). On the Mac and
604 DOS, alas, we have to call it. */
605 if (PyErr_CheckSignals()) {
606 why = WHY_EXCEPTION;
607 goto on_error;
609 #endif
611 #ifdef WITH_THREAD
612 if (interpreter_lock) {
613 /* Give another thread a chance */
615 if (PyThreadState_Swap(NULL) != tstate)
616 Py_FatalError("ceval: tstate mix-up");
617 PyThread_release_lock(interpreter_lock);
619 /* Other threads may run now */
621 PyThread_acquire_lock(interpreter_lock, 1);
622 if (PyThreadState_Swap(tstate) != NULL)
623 Py_FatalError("ceval: orphan tstate");
625 #endif
628 /* Extract opcode and argument */
630 #if defined(Py_DEBUG) || defined(LLTRACE)
631 f->f_lasti = INSTR_OFFSET();
632 #endif
634 opcode = NEXTOP();
635 if (HAS_ARG(opcode))
636 oparg = NEXTARG();
637 dispatch_opcode:
638 #ifdef DYNAMIC_EXECUTION_PROFILE
639 #ifdef DXPAIRS
640 dxpairs[lastopcode][opcode]++;
641 lastopcode = opcode;
642 #endif
643 dxp[opcode]++;
644 #endif
646 #ifdef LLTRACE
647 /* Instruction tracing */
649 if (lltrace) {
650 if (HAS_ARG(opcode)) {
651 printf("%d: %d, %d\n",
652 (int) (INSTR_OFFSET() - 3),
653 opcode, oparg);
655 else {
656 printf("%d: %d\n",
657 (int) (INSTR_OFFSET() - 1), opcode);
660 #endif
661 /* Main switch on opcode */
663 switch (opcode) {
665 /* BEWARE!
666 It is essential that any operation that fails sets either
667 x to NULL, err to nonzero, or why to anything but WHY_NOT,
668 and that no operation that succeeds does this! */
670 /* case STOP_CODE: this is an error! */
672 case POP_TOP:
673 v = POP();
674 Py_DECREF(v);
675 continue;
677 case ROT_TWO:
678 v = POP();
679 w = POP();
680 PUSH(v);
681 PUSH(w);
682 continue;
684 case ROT_THREE:
685 v = POP();
686 w = POP();
687 x = POP();
688 PUSH(v);
689 PUSH(x);
690 PUSH(w);
691 continue;
693 case ROT_FOUR:
694 u = POP();
695 v = POP();
696 w = POP();
697 x = POP();
698 PUSH(u);
699 PUSH(x);
700 PUSH(w);
701 PUSH(v);
702 continue;
704 case DUP_TOP:
705 v = TOP();
706 Py_INCREF(v);
707 PUSH(v);
708 continue;
710 case DUP_TOPX:
711 switch (oparg) {
712 case 1:
713 x = TOP();
714 Py_INCREF(x);
715 PUSH(x);
716 continue;
717 case 2:
718 x = POP();
719 Py_INCREF(x);
720 w = TOP();
721 Py_INCREF(w);
722 PUSH(x);
723 PUSH(w);
724 PUSH(x);
725 continue;
726 case 3:
727 x = POP();
728 Py_INCREF(x);
729 w = POP();
730 Py_INCREF(w);
731 v = TOP();
732 Py_INCREF(v);
733 PUSH(w);
734 PUSH(x);
735 PUSH(v);
736 PUSH(w);
737 PUSH(x);
738 continue;
739 case 4:
740 x = POP();
741 Py_INCREF(x);
742 w = POP();
743 Py_INCREF(w);
744 v = POP();
745 Py_INCREF(v);
746 u = TOP();
747 Py_INCREF(u);
748 PUSH(v);
749 PUSH(w);
750 PUSH(x);
751 PUSH(u);
752 PUSH(v);
753 PUSH(w);
754 PUSH(x);
755 continue;
756 case 5:
757 x = POP();
758 Py_INCREF(x);
759 w = POP();
760 Py_INCREF(w);
761 v = POP();
762 Py_INCREF(v);
763 u = POP();
764 Py_INCREF(u);
765 t = TOP();
766 Py_INCREF(t);
767 PUSH(u);
768 PUSH(v);
769 PUSH(w);
770 PUSH(x);
771 PUSH(t);
772 PUSH(u);
773 PUSH(v);
774 PUSH(w);
775 PUSH(x);
776 continue;
777 default:
778 Py_FatalError("invalid argument to DUP_TOPX"
779 " (bytecode corruption?)");
781 break;
783 case UNARY_POSITIVE:
784 v = POP();
785 x = PyNumber_Positive(v);
786 Py_DECREF(v);
787 PUSH(x);
788 if (x != NULL) continue;
789 break;
791 case UNARY_NEGATIVE:
792 v = POP();
793 x = PyNumber_Negative(v);
794 Py_DECREF(v);
795 PUSH(x);
796 if (x != NULL) continue;
797 break;
799 case UNARY_NOT:
800 v = POP();
801 err = PyObject_IsTrue(v);
802 Py_DECREF(v);
803 if (err == 0) {
804 Py_INCREF(Py_True);
805 PUSH(Py_True);
806 continue;
808 else if (err > 0) {
809 Py_INCREF(Py_False);
810 PUSH(Py_False);
811 err = 0;
812 continue;
814 break;
816 case UNARY_CONVERT:
817 v = POP();
818 x = PyObject_Repr(v);
819 Py_DECREF(v);
820 PUSH(x);
821 if (x != NULL) continue;
822 break;
824 case UNARY_INVERT:
825 v = POP();
826 x = PyNumber_Invert(v);
827 Py_DECREF(v);
828 PUSH(x);
829 if (x != NULL) continue;
830 break;
832 case BINARY_POWER:
833 w = POP();
834 v = POP();
835 x = PyNumber_Power(v, w, Py_None);
836 Py_DECREF(v);
837 Py_DECREF(w);
838 PUSH(x);
839 if (x != NULL) continue;
840 break;
842 case BINARY_MULTIPLY:
843 w = POP();
844 v = POP();
845 x = PyNumber_Multiply(v, w);
846 Py_DECREF(v);
847 Py_DECREF(w);
848 PUSH(x);
849 if (x != NULL) continue;
850 break;
852 case BINARY_DIVIDE:
853 w = POP();
854 v = POP();
855 x = PyNumber_Divide(v, w);
856 Py_DECREF(v);
857 Py_DECREF(w);
858 PUSH(x);
859 if (x != NULL) continue;
860 break;
862 case BINARY_MODULO:
863 w = POP();
864 v = POP();
865 x = PyNumber_Remainder(v, w);
866 Py_DECREF(v);
867 Py_DECREF(w);
868 PUSH(x);
869 if (x != NULL) continue;
870 break;
872 case BINARY_ADD:
873 w = POP();
874 v = POP();
875 if (PyInt_Check(v) && PyInt_Check(w)) {
876 /* INLINE: int + int */
877 register long a, b, i;
878 a = PyInt_AS_LONG(v);
879 b = PyInt_AS_LONG(w);
880 i = a + b;
881 if ((i^a) < 0 && (i^b) < 0) {
882 PyErr_SetString(PyExc_OverflowError,
883 "integer addition");
884 x = NULL;
886 else
887 x = PyInt_FromLong(i);
889 else
890 x = PyNumber_Add(v, w);
891 Py_DECREF(v);
892 Py_DECREF(w);
893 PUSH(x);
894 if (x != NULL) continue;
895 break;
897 case BINARY_SUBTRACT:
898 w = POP();
899 v = POP();
900 if (PyInt_Check(v) && PyInt_Check(w)) {
901 /* INLINE: int - int */
902 register long a, b, i;
903 a = PyInt_AS_LONG(v);
904 b = PyInt_AS_LONG(w);
905 i = a - b;
906 if ((i^a) < 0 && (i^~b) < 0) {
907 PyErr_SetString(PyExc_OverflowError,
908 "integer subtraction");
909 x = NULL;
911 else
912 x = PyInt_FromLong(i);
914 else
915 x = PyNumber_Subtract(v, w);
916 Py_DECREF(v);
917 Py_DECREF(w);
918 PUSH(x);
919 if (x != NULL) continue;
920 break;
922 case BINARY_SUBSCR:
923 w = POP();
924 v = POP();
925 if (PyList_Check(v) && PyInt_Check(w)) {
926 /* INLINE: list[int] */
927 long i = PyInt_AsLong(w);
928 if (i < 0)
929 i += PyList_GET_SIZE(v);
930 if (i < 0 ||
931 i >= PyList_GET_SIZE(v)) {
932 PyErr_SetString(PyExc_IndexError,
933 "list index out of range");
934 x = NULL;
936 else {
937 x = PyList_GET_ITEM(v, i);
938 Py_INCREF(x);
941 else
942 x = PyObject_GetItem(v, w);
943 Py_DECREF(v);
944 Py_DECREF(w);
945 PUSH(x);
946 if (x != NULL) continue;
947 break;
949 case BINARY_LSHIFT:
950 w = POP();
951 v = POP();
952 x = PyNumber_Lshift(v, w);
953 Py_DECREF(v);
954 Py_DECREF(w);
955 PUSH(x);
956 if (x != NULL) continue;
957 break;
959 case BINARY_RSHIFT:
960 w = POP();
961 v = POP();
962 x = PyNumber_Rshift(v, w);
963 Py_DECREF(v);
964 Py_DECREF(w);
965 PUSH(x);
966 if (x != NULL) continue;
967 break;
969 case BINARY_AND:
970 w = POP();
971 v = POP();
972 x = PyNumber_And(v, w);
973 Py_DECREF(v);
974 Py_DECREF(w);
975 PUSH(x);
976 if (x != NULL) continue;
977 break;
979 case BINARY_XOR:
980 w = POP();
981 v = POP();
982 x = PyNumber_Xor(v, w);
983 Py_DECREF(v);
984 Py_DECREF(w);
985 PUSH(x);
986 if (x != NULL) continue;
987 break;
989 case BINARY_OR:
990 w = POP();
991 v = POP();
992 x = PyNumber_Or(v, w);
993 Py_DECREF(v);
994 Py_DECREF(w);
995 PUSH(x);
996 if (x != NULL) continue;
997 break;
999 case INPLACE_POWER:
1000 w = POP();
1001 v = POP();
1002 x = PyNumber_InPlacePower(v, w, Py_None);
1003 Py_DECREF(v);
1004 Py_DECREF(w);
1005 PUSH(x);
1006 if (x != NULL) continue;
1007 break;
1009 case INPLACE_MULTIPLY:
1010 w = POP();
1011 v = POP();
1012 x = PyNumber_InPlaceMultiply(v, w);
1013 Py_DECREF(v);
1014 Py_DECREF(w);
1015 PUSH(x);
1016 if (x != NULL) continue;
1017 break;
1019 case INPLACE_DIVIDE:
1020 w = POP();
1021 v = POP();
1022 x = PyNumber_InPlaceDivide(v, w);
1023 Py_DECREF(v);
1024 Py_DECREF(w);
1025 PUSH(x);
1026 if (x != NULL) continue;
1027 break;
1029 case INPLACE_MODULO:
1030 w = POP();
1031 v = POP();
1032 x = PyNumber_InPlaceRemainder(v, w);
1033 Py_DECREF(v);
1034 Py_DECREF(w);
1035 PUSH(x);
1036 if (x != NULL) continue;
1037 break;
1039 case INPLACE_ADD:
1040 w = POP();
1041 v = POP();
1042 if (PyInt_Check(v) && PyInt_Check(w)) {
1043 /* INLINE: int + int */
1044 register long a, b, i;
1045 a = PyInt_AS_LONG(v);
1046 b = PyInt_AS_LONG(w);
1047 i = a + b;
1048 if ((i^a) < 0 && (i^b) < 0) {
1049 PyErr_SetString(PyExc_OverflowError,
1050 "integer addition");
1051 x = NULL;
1053 else
1054 x = PyInt_FromLong(i);
1056 else
1057 x = PyNumber_InPlaceAdd(v, w);
1058 Py_DECREF(v);
1059 Py_DECREF(w);
1060 PUSH(x);
1061 if (x != NULL) continue;
1062 break;
1064 case INPLACE_SUBTRACT:
1065 w = POP();
1066 v = POP();
1067 if (PyInt_Check(v) && PyInt_Check(w)) {
1068 /* INLINE: int - int */
1069 register long a, b, i;
1070 a = PyInt_AS_LONG(v);
1071 b = PyInt_AS_LONG(w);
1072 i = a - b;
1073 if ((i^a) < 0 && (i^~b) < 0) {
1074 PyErr_SetString(PyExc_OverflowError,
1075 "integer subtraction");
1076 x = NULL;
1078 else
1079 x = PyInt_FromLong(i);
1081 else
1082 x = PyNumber_InPlaceSubtract(v, w);
1083 Py_DECREF(v);
1084 Py_DECREF(w);
1085 PUSH(x);
1086 if (x != NULL) continue;
1087 break;
1089 case INPLACE_LSHIFT:
1090 w = POP();
1091 v = POP();
1092 x = PyNumber_InPlaceLshift(v, w);
1093 Py_DECREF(v);
1094 Py_DECREF(w);
1095 PUSH(x);
1096 if (x != NULL) continue;
1097 break;
1099 case INPLACE_RSHIFT:
1100 w = POP();
1101 v = POP();
1102 x = PyNumber_InPlaceRshift(v, w);
1103 Py_DECREF(v);
1104 Py_DECREF(w);
1105 PUSH(x);
1106 if (x != NULL) continue;
1107 break;
1109 case INPLACE_AND:
1110 w = POP();
1111 v = POP();
1112 x = PyNumber_InPlaceAnd(v, w);
1113 Py_DECREF(v);
1114 Py_DECREF(w);
1115 PUSH(x);
1116 if (x != NULL) continue;
1117 break;
1119 case INPLACE_XOR:
1120 w = POP();
1121 v = POP();
1122 x = PyNumber_InPlaceXor(v, w);
1123 Py_DECREF(v);
1124 Py_DECREF(w);
1125 PUSH(x);
1126 if (x != NULL) continue;
1127 break;
1129 case INPLACE_OR:
1130 w = POP();
1131 v = POP();
1132 x = PyNumber_InPlaceOr(v, w);
1133 Py_DECREF(v);
1134 Py_DECREF(w);
1135 PUSH(x);
1136 if (x != NULL) continue;
1137 break;
1139 case SLICE+0:
1140 case SLICE+1:
1141 case SLICE+2:
1142 case SLICE+3:
1143 if ((opcode-SLICE) & 2)
1144 w = POP();
1145 else
1146 w = NULL;
1147 if ((opcode-SLICE) & 1)
1148 v = POP();
1149 else
1150 v = NULL;
1151 u = POP();
1152 x = apply_slice(u, v, w);
1153 Py_DECREF(u);
1154 Py_XDECREF(v);
1155 Py_XDECREF(w);
1156 PUSH(x);
1157 if (x != NULL) continue;
1158 break;
1160 case STORE_SLICE+0:
1161 case STORE_SLICE+1:
1162 case STORE_SLICE+2:
1163 case STORE_SLICE+3:
1164 if ((opcode-STORE_SLICE) & 2)
1165 w = POP();
1166 else
1167 w = NULL;
1168 if ((opcode-STORE_SLICE) & 1)
1169 v = POP();
1170 else
1171 v = NULL;
1172 u = POP();
1173 t = POP();
1174 err = assign_slice(u, v, w, t); /* u[v:w] = t */
1175 Py_DECREF(t);
1176 Py_DECREF(u);
1177 Py_XDECREF(v);
1178 Py_XDECREF(w);
1179 if (err == 0) continue;
1180 break;
1182 case DELETE_SLICE+0:
1183 case DELETE_SLICE+1:
1184 case DELETE_SLICE+2:
1185 case DELETE_SLICE+3:
1186 if ((opcode-DELETE_SLICE) & 2)
1187 w = POP();
1188 else
1189 w = NULL;
1190 if ((opcode-DELETE_SLICE) & 1)
1191 v = POP();
1192 else
1193 v = NULL;
1194 u = POP();
1195 err = assign_slice(u, v, w, (PyObject *)NULL);
1196 /* del u[v:w] */
1197 Py_DECREF(u);
1198 Py_XDECREF(v);
1199 Py_XDECREF(w);
1200 if (err == 0) continue;
1201 break;
1203 case STORE_SUBSCR:
1204 w = POP();
1205 v = POP();
1206 u = POP();
1207 /* v[w] = u */
1208 err = PyObject_SetItem(v, w, u);
1209 Py_DECREF(u);
1210 Py_DECREF(v);
1211 Py_DECREF(w);
1212 if (err == 0) continue;
1213 break;
1215 case DELETE_SUBSCR:
1216 w = POP();
1217 v = POP();
1218 /* del v[w] */
1219 err = PyObject_DelItem(v, w);
1220 Py_DECREF(v);
1221 Py_DECREF(w);
1222 if (err == 0) continue;
1223 break;
1225 case PRINT_EXPR:
1226 v = POP();
1227 /* Print value except if None */
1228 /* After printing, also assign to '_' */
1229 /* Before, set '_' to None to avoid recursion */
1230 if (v != Py_None &&
1231 (err = PyDict_SetItemString(
1232 f->f_builtins, "_", Py_None)) == 0) {
1233 err = Py_FlushLine();
1234 if (err == 0) {
1235 x = PySys_GetObject("stdout");
1236 if (x == NULL) {
1237 PyErr_SetString(
1238 PyExc_RuntimeError,
1239 "lost sys.stdout");
1240 err = -1;
1243 if (err == 0)
1244 err = PyFile_WriteObject(v, x, 0);
1245 if (err == 0) {
1246 PyFile_SoftSpace(x, 1);
1247 err = Py_FlushLine();
1249 if (err == 0) {
1250 err = PyDict_SetItemString(
1251 f->f_builtins, "_", v);
1254 Py_DECREF(v);
1255 break;
1257 case PRINT_ITEM_TO:
1258 w = stream = POP();
1259 /* fall through to PRINT_ITEM */
1261 case PRINT_ITEM:
1262 v = POP();
1263 if (stream == NULL || stream == Py_None) {
1264 w = PySys_GetObject("stdout");
1265 if (w == NULL) {
1266 PyErr_SetString(PyExc_RuntimeError,
1267 "lost sys.stdout");
1268 err = -1;
1271 if (w != NULL && PyFile_SoftSpace(w, 1))
1272 err = PyFile_WriteString(" ", w);
1273 if (err == 0)
1274 err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
1275 if (err == 0 && PyString_Check(v)) {
1276 /* XXX move into writeobject() ? */
1277 char *s = PyString_AsString(v);
1278 int len = PyString_Size(v);
1279 if (len > 0 &&
1280 isspace(Py_CHARMASK(s[len-1])) &&
1281 s[len-1] != ' ')
1282 PyFile_SoftSpace(w, 0);
1284 Py_DECREF(v);
1285 Py_XDECREF(stream);
1286 stream = NULL;
1287 if (err == 0)
1288 continue;
1289 break;
1291 case PRINT_NEWLINE_TO:
1292 w = stream = POP();
1293 /* fall through to PRINT_NEWLINE */
1295 case PRINT_NEWLINE:
1296 if (stream == NULL || stream == Py_None) {
1297 w = PySys_GetObject("stdout");
1298 if (w == NULL)
1299 PyErr_SetString(PyExc_RuntimeError,
1300 "lost sys.stdout");
1302 if (w != NULL) {
1303 err = PyFile_WriteString("\n", w);
1304 if (err == 0)
1305 PyFile_SoftSpace(w, 0);
1307 Py_XDECREF(stream);
1308 stream = NULL;
1309 break;
1312 #ifdef CASE_TOO_BIG
1313 default: switch (opcode) {
1314 #endif
1315 case BREAK_LOOP:
1316 why = WHY_BREAK;
1317 break;
1319 case RAISE_VARARGS:
1320 u = v = w = NULL;
1321 switch (oparg) {
1322 case 3:
1323 u = POP(); /* traceback */
1324 /* Fallthrough */
1325 case 2:
1326 v = POP(); /* value */
1327 /* Fallthrough */
1328 case 1:
1329 w = POP(); /* exc */
1330 case 0: /* Fallthrough */
1331 why = do_raise(w, v, u);
1332 break;
1333 default:
1334 PyErr_SetString(PyExc_SystemError,
1335 "bad RAISE_VARARGS oparg");
1336 why = WHY_EXCEPTION;
1337 break;
1339 break;
1341 case LOAD_LOCALS:
1342 if ((x = f->f_locals) == NULL) {
1343 PyErr_SetString(PyExc_SystemError,
1344 "no locals");
1345 break;
1347 Py_INCREF(x);
1348 PUSH(x);
1349 break;
1351 case RETURN_VALUE:
1352 retval = POP();
1353 why = WHY_RETURN;
1354 break;
1356 case EXEC_STMT:
1357 w = POP();
1358 v = POP();
1359 u = POP();
1360 err = exec_statement(f, u, v, w);
1361 Py_DECREF(u);
1362 Py_DECREF(v);
1363 Py_DECREF(w);
1364 break;
1366 case POP_BLOCK:
1368 PyTryBlock *b = PyFrame_BlockPop(f);
1369 while (STACK_LEVEL() > b->b_level) {
1370 v = POP();
1371 Py_DECREF(v);
1374 break;
1376 case END_FINALLY:
1377 v = POP();
1378 if (PyInt_Check(v)) {
1379 why = (enum why_code) PyInt_AsLong(v);
1380 if (why == WHY_RETURN)
1381 retval = POP();
1383 else if (PyString_Check(v) || PyClass_Check(v)) {
1384 w = POP();
1385 u = POP();
1386 PyErr_Restore(v, w, u);
1387 why = WHY_RERAISE;
1388 break;
1390 else if (v != Py_None) {
1391 PyErr_SetString(PyExc_SystemError,
1392 "'finally' pops bad exception");
1393 why = WHY_EXCEPTION;
1395 Py_DECREF(v);
1396 break;
1398 case BUILD_CLASS:
1399 u = POP();
1400 v = POP();
1401 w = POP();
1402 x = build_class(u, v, w);
1403 PUSH(x);
1404 Py_DECREF(u);
1405 Py_DECREF(v);
1406 Py_DECREF(w);
1407 break;
1409 case STORE_NAME:
1410 w = GETNAMEV(oparg);
1411 v = POP();
1412 if ((x = f->f_locals) == NULL) {
1413 PyErr_SetString(PyExc_SystemError,
1414 "no locals");
1415 break;
1417 err = PyDict_SetItem(x, w, v);
1418 Py_DECREF(v);
1419 break;
1421 case DELETE_NAME:
1422 w = GETNAMEV(oparg);
1423 if ((x = f->f_locals) == NULL) {
1424 PyErr_SetString(PyExc_SystemError,
1425 "no locals");
1426 break;
1428 if ((err = PyDict_DelItem(x, w)) != 0)
1429 format_exc_check_arg(PyExc_NameError,
1430 NAME_ERROR_MSG ,w);
1431 break;
1433 case UNPACK_SEQUENCE:
1434 v = POP();
1435 if (PyTuple_Check(v)) {
1436 if (PyTuple_Size(v) != oparg) {
1437 PyErr_SetString(PyExc_ValueError,
1438 "unpack tuple of wrong size");
1439 why = WHY_EXCEPTION;
1441 else {
1442 for (; --oparg >= 0; ) {
1443 w = PyTuple_GET_ITEM(v, oparg);
1444 Py_INCREF(w);
1445 PUSH(w);
1449 else if (PyList_Check(v)) {
1450 if (PyList_Size(v) != oparg) {
1451 PyErr_SetString(PyExc_ValueError,
1452 "unpack list of wrong size");
1453 why = WHY_EXCEPTION;
1455 else {
1456 for (; --oparg >= 0; ) {
1457 w = PyList_GET_ITEM(v, oparg);
1458 Py_INCREF(w);
1459 PUSH(w);
1463 else if (PySequence_Check(v)) {
1464 if (unpack_sequence(v, oparg,
1465 stack_pointer + oparg))
1466 stack_pointer += oparg;
1467 else
1468 why = WHY_EXCEPTION;
1470 else {
1471 PyErr_SetString(PyExc_TypeError,
1472 "unpack non-sequence");
1473 why = WHY_EXCEPTION;
1475 Py_DECREF(v);
1476 break;
1478 case STORE_ATTR:
1479 w = GETNAMEV(oparg);
1480 v = POP();
1481 u = POP();
1482 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1483 Py_DECREF(v);
1484 Py_DECREF(u);
1485 break;
1487 case DELETE_ATTR:
1488 w = GETNAMEV(oparg);
1489 v = POP();
1490 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
1491 /* del v.w */
1492 Py_DECREF(v);
1493 break;
1495 case STORE_GLOBAL:
1496 w = GETNAMEV(oparg);
1497 v = POP();
1498 err = PyDict_SetItem(f->f_globals, w, v);
1499 Py_DECREF(v);
1500 break;
1502 case DELETE_GLOBAL:
1503 w = GETNAMEV(oparg);
1504 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
1505 format_exc_check_arg(
1506 PyExc_NameError, NAME_ERROR_MSG ,w);
1507 break;
1509 case LOAD_CONST:
1510 x = GETCONST(oparg);
1511 Py_INCREF(x);
1512 PUSH(x);
1513 break;
1515 case LOAD_NAME:
1516 w = GETNAMEV(oparg);
1517 if ((x = f->f_locals) == NULL) {
1518 PyErr_SetString(PyExc_SystemError,
1519 "no locals");
1520 break;
1522 x = PyDict_GetItem(x, w);
1523 if (x == NULL) {
1524 x = PyDict_GetItem(f->f_globals, w);
1525 if (x == NULL) {
1526 x = PyDict_GetItem(f->f_builtins, w);
1527 if (x == NULL) {
1528 format_exc_check_arg(
1529 PyExc_NameError,
1530 NAME_ERROR_MSG ,w);
1531 break;
1535 Py_INCREF(x);
1536 PUSH(x);
1537 break;
1539 case LOAD_GLOBAL:
1540 w = GETNAMEV(oparg);
1541 x = PyDict_GetItem(f->f_globals, w);
1542 if (x == NULL) {
1543 x = PyDict_GetItem(f->f_builtins, w);
1544 if (x == NULL) {
1545 format_exc_check_arg(
1546 PyExc_NameError,
1547 NAME_ERROR_MSG ,w);
1548 break;
1551 Py_INCREF(x);
1552 PUSH(x);
1553 break;
1555 case LOAD_FAST:
1556 x = GETLOCAL(oparg);
1557 if (x == NULL) {
1558 format_exc_check_arg(
1559 PyExc_UnboundLocalError,
1560 UNBOUNDLOCAL_ERROR_MSG,
1561 PyTuple_GetItem(co->co_varnames, oparg)
1563 break;
1565 Py_INCREF(x);
1566 PUSH(x);
1567 if (x != NULL) continue;
1568 break;
1570 case STORE_FAST:
1571 v = POP();
1572 SETLOCAL(oparg, v);
1573 continue;
1575 case DELETE_FAST:
1576 x = GETLOCAL(oparg);
1577 if (x == NULL) {
1578 format_exc_check_arg(
1579 PyExc_UnboundLocalError,
1580 UNBOUNDLOCAL_ERROR_MSG,
1581 PyTuple_GetItem(co->co_varnames, oparg)
1583 break;
1585 SETLOCAL(oparg, NULL);
1586 continue;
1588 case BUILD_TUPLE:
1589 x = PyTuple_New(oparg);
1590 if (x != NULL) {
1591 for (; --oparg >= 0;) {
1592 w = POP();
1593 PyTuple_SET_ITEM(x, oparg, w);
1595 PUSH(x);
1596 continue;
1598 break;
1600 case BUILD_LIST:
1601 x = PyList_New(oparg);
1602 if (x != NULL) {
1603 for (; --oparg >= 0;) {
1604 w = POP();
1605 PyList_SET_ITEM(x, oparg, w);
1607 PUSH(x);
1608 continue;
1610 break;
1612 case BUILD_MAP:
1613 x = PyDict_New();
1614 PUSH(x);
1615 if (x != NULL) continue;
1616 break;
1618 case LOAD_ATTR:
1619 w = GETNAMEV(oparg);
1620 v = POP();
1621 x = PyObject_GetAttr(v, w);
1622 Py_DECREF(v);
1623 PUSH(x);
1624 if (x != NULL) continue;
1625 break;
1627 case COMPARE_OP:
1628 w = POP();
1629 v = POP();
1630 if (PyInt_Check(v) && PyInt_Check(w)) {
1631 /* INLINE: cmp(int, int) */
1632 register long a, b;
1633 register int res;
1634 a = PyInt_AS_LONG(v);
1635 b = PyInt_AS_LONG(w);
1636 switch (oparg) {
1637 case LT: res = a < b; break;
1638 case LE: res = a <= b; break;
1639 case EQ: res = a == b; break;
1640 case NE: res = a != b; break;
1641 case GT: res = a > b; break;
1642 case GE: res = a >= b; break;
1643 case IS: res = v == w; break;
1644 case IS_NOT: res = v != w; break;
1645 default: goto slow_compare;
1647 x = res ? Py_True : Py_False;
1648 Py_INCREF(x);
1650 else {
1651 slow_compare:
1652 x = cmp_outcome(oparg, v, w);
1654 Py_DECREF(v);
1655 Py_DECREF(w);
1656 PUSH(x);
1657 if (x != NULL) continue;
1658 break;
1660 case IMPORT_NAME:
1661 w = GETNAMEV(oparg);
1662 x = PyDict_GetItemString(f->f_builtins, "__import__");
1663 if (x == NULL) {
1664 PyErr_SetString(PyExc_ImportError,
1665 "__import__ not found");
1666 break;
1668 u = POP();
1669 w = Py_BuildValue("(OOOO)",
1671 f->f_globals,
1672 f->f_locals == NULL ?
1673 Py_None : f->f_locals,
1675 Py_DECREF(u);
1676 if (w == NULL) {
1677 x = NULL;
1678 break;
1680 x = PyEval_CallObject(x, w);
1681 Py_DECREF(w);
1682 PUSH(x);
1683 if (x != NULL) continue;
1684 break;
1686 case IMPORT_STAR:
1687 v = POP();
1688 PyFrame_FastToLocals(f);
1689 if ((x = f->f_locals) == NULL) {
1690 PyErr_SetString(PyExc_SystemError,
1691 "no locals");
1692 break;
1694 err = import_all_from(x, v);
1695 PyFrame_LocalsToFast(f, 0);
1696 Py_DECREF(v);
1697 if (err == 0) continue;
1698 break;
1700 case IMPORT_FROM:
1701 w = GETNAMEV(oparg);
1702 v = TOP();
1703 x = import_from(v, w);
1704 PUSH(x);
1705 if (x != NULL) continue;
1706 break;
1708 case JUMP_FORWARD:
1709 JUMPBY(oparg);
1710 continue;
1712 case JUMP_IF_FALSE:
1713 err = PyObject_IsTrue(TOP());
1714 if (err > 0)
1715 err = 0;
1716 else if (err == 0)
1717 JUMPBY(oparg);
1718 else
1719 break;
1720 continue;
1722 case JUMP_IF_TRUE:
1723 err = PyObject_IsTrue(TOP());
1724 if (err > 0) {
1725 err = 0;
1726 JUMPBY(oparg);
1728 else if (err == 0)
1730 else
1731 break;
1732 continue;
1734 case JUMP_ABSOLUTE:
1735 JUMPTO(oparg);
1736 continue;
1738 case FOR_LOOP:
1739 /* for v in s: ...
1740 On entry: stack contains s, i.
1741 On exit: stack contains s, i+1, s[i];
1742 but if loop exhausted:
1743 s, i are popped, and we jump */
1744 w = POP(); /* Loop index */
1745 v = POP(); /* Sequence object */
1746 u = loop_subscript(v, w);
1747 if (u != NULL) {
1748 PUSH(v);
1749 x = PyInt_FromLong(PyInt_AsLong(w)+1);
1750 PUSH(x);
1751 Py_DECREF(w);
1752 PUSH(u);
1753 if (x != NULL) continue;
1755 else {
1756 Py_DECREF(v);
1757 Py_DECREF(w);
1758 /* A NULL can mean "s exhausted"
1759 but also an error: */
1760 if (PyErr_Occurred())
1761 why = WHY_EXCEPTION;
1762 else {
1763 JUMPBY(oparg);
1764 continue;
1767 break;
1769 case SETUP_LOOP:
1770 case SETUP_EXCEPT:
1771 case SETUP_FINALLY:
1772 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
1773 STACK_LEVEL());
1774 continue;
1776 case SET_LINENO:
1777 #ifdef LLTRACE
1778 if (lltrace)
1779 printf("--- %s:%d \n", filename, oparg);
1780 #endif
1781 f->f_lineno = oparg;
1782 if (f->f_trace == NULL)
1783 continue;
1784 /* Trace each line of code reached */
1785 f->f_lasti = INSTR_OFFSET();
1786 err = call_trace(&f->f_trace, &f->f_trace,
1787 f, "line", Py_None);
1788 break;
1790 case CALL_FUNCTION:
1791 case CALL_FUNCTION_VAR:
1792 case CALL_FUNCTION_KW:
1793 case CALL_FUNCTION_VAR_KW:
1795 int na = oparg & 0xff;
1796 int nk = (oparg>>8) & 0xff;
1797 int flags = (opcode - CALL_FUNCTION) & 3;
1798 int n = na + 2*nk + (flags & 1) + ((flags >> 1) & 1);
1799 PyObject **pfunc = stack_pointer - n - 1;
1800 PyObject *func = *pfunc;
1801 PyObject *self = NULL;
1802 PyObject *class = NULL;
1803 f->f_lasti = INSTR_OFFSET() - 3; /* For tracing */
1804 if (PyMethod_Check(func)) {
1805 self = PyMethod_Self(func);
1806 class = PyMethod_Class(func);
1807 func = PyMethod_Function(func);
1808 Py_INCREF(func);
1809 if (self != NULL) {
1810 Py_INCREF(self);
1811 Py_DECREF(*pfunc);
1812 *pfunc = self;
1813 na++;
1814 n++;
1816 else {
1817 /* Unbound methods must be called with an
1818 instance of the class (or a derived
1819 class) as first argument */
1820 if (na > 0 && (self = stack_pointer[-n]) != NULL
1821 && PyInstance_Check(self)
1822 && PyClass_IsSubclass((PyObject *)
1823 (((PyInstanceObject *)self)->in_class),
1824 class))
1825 /* Handy-dandy */ ;
1826 else {
1827 PyErr_SetString(PyExc_TypeError,
1828 "unbound method must be called with class instance 1st argument");
1829 x = NULL;
1830 break;
1834 else
1835 Py_INCREF(func);
1836 if (PyFunction_Check(func) && flags == 0) {
1837 PyObject *co = PyFunction_GetCode(func);
1838 PyObject *globals = PyFunction_GetGlobals(func);
1839 PyObject *argdefs = PyFunction_GetDefaults(func);
1840 PyObject **d;
1841 int nd;
1842 if (argdefs != NULL) {
1843 d = &PyTuple_GET_ITEM(argdefs, 0);
1844 nd = ((PyTupleObject *)argdefs)->ob_size;
1846 else {
1847 d = NULL;
1848 nd = 0;
1850 x = eval_code2((PyCodeObject *)co, globals,
1851 (PyObject *)NULL, stack_pointer-n, na,
1852 stack_pointer-2*nk, nk, d, nd,
1853 class);
1855 else {
1856 int nstar = 0;
1857 PyObject *callargs;
1858 PyObject *stararg = 0;
1859 PyObject *kwdict = NULL;
1860 if (flags & 2) {
1861 kwdict = POP();
1862 if (!PyDict_Check(kwdict)) {
1863 PyErr_SetString(PyExc_TypeError,
1864 "** argument must be a dictionary");
1865 goto extcall_fail;
1868 if (flags & 1) {
1869 stararg = POP();
1870 if (!PySequence_Check(stararg)) {
1871 PyErr_SetString(PyExc_TypeError,
1872 "* argument must be a sequence");
1873 goto extcall_fail;
1875 /* Convert abstract sequence to concrete tuple */
1876 if (!PyTuple_Check(stararg)) {
1877 PyObject *t = NULL;
1878 t = PySequence_Tuple(stararg);
1879 if (t == NULL) {
1880 goto extcall_fail;
1882 Py_DECREF(stararg);
1883 stararg = t;
1885 nstar = PyTuple_GET_SIZE(stararg);
1886 if (nstar < 0) {
1887 goto extcall_fail;
1890 if (nk > 0) {
1891 if (kwdict == NULL) {
1892 kwdict = PyDict_New();
1893 if (kwdict == NULL) {
1894 goto extcall_fail;
1897 else {
1898 PyObject *d = PyDict_Copy(kwdict);
1899 if (d == NULL) {
1900 goto extcall_fail;
1902 Py_DECREF(kwdict);
1903 kwdict = d;
1905 err = 0;
1906 while (--nk >= 0) {
1907 PyObject *value = POP();
1908 PyObject *key = POP();
1909 if (PyDict_GetItem(kwdict, key) != NULL) {
1910 err = 1;
1911 PyErr_Format(PyExc_TypeError,
1912 "keyword parameter redefined: %.400s",
1913 PyString_AsString(key));
1914 Py_DECREF(key);
1915 Py_DECREF(value);
1916 goto extcall_fail;
1918 err = PyDict_SetItem(kwdict, key, value);
1919 Py_DECREF(key);
1920 Py_DECREF(value);
1921 if (err)
1922 break;
1924 if (err) {
1925 extcall_fail:
1926 Py_XDECREF(kwdict);
1927 Py_XDECREF(stararg);
1928 Py_DECREF(func);
1929 x=NULL;
1930 break;
1933 callargs = PyTuple_New(na + nstar);
1934 if (callargs == NULL) {
1935 x = NULL;
1936 break;
1938 if (stararg) {
1939 int i;
1940 for (i = 0; i < nstar; i++) {
1941 PyObject *a = PyTuple_GET_ITEM(stararg, i);
1942 Py_INCREF(a);
1943 PyTuple_SET_ITEM(callargs, na + i, a);
1945 Py_DECREF(stararg);
1947 while (--na >= 0) {
1948 w = POP();
1949 PyTuple_SET_ITEM(callargs, na, w);
1951 x = PyEval_CallObjectWithKeywords(func,
1952 callargs,
1953 kwdict);
1954 Py_DECREF(callargs);
1955 Py_XDECREF(kwdict);
1957 Py_DECREF(func);
1958 while (stack_pointer > pfunc) {
1959 w = POP();
1960 Py_DECREF(w);
1962 PUSH(x);
1963 if (x != NULL) continue;
1964 break;
1967 case MAKE_FUNCTION:
1968 v = POP(); /* code object */
1969 x = PyFunction_New(v, f->f_globals);
1970 Py_DECREF(v);
1971 /* XXX Maybe this should be a separate opcode? */
1972 if (x != NULL && oparg > 0) {
1973 v = PyTuple_New(oparg);
1974 if (v == NULL) {
1975 Py_DECREF(x);
1976 x = NULL;
1977 break;
1979 while (--oparg >= 0) {
1980 w = POP();
1981 PyTuple_SET_ITEM(v, oparg, w);
1983 err = PyFunction_SetDefaults(x, v);
1984 Py_DECREF(v);
1986 PUSH(x);
1987 break;
1989 case BUILD_SLICE:
1990 if (oparg == 3)
1991 w = POP();
1992 else
1993 w = NULL;
1994 v = POP();
1995 u = POP();
1996 x = PySlice_New(u, v, w);
1997 Py_DECREF(u);
1998 Py_DECREF(v);
1999 Py_XDECREF(w);
2000 PUSH(x);
2001 if (x != NULL) continue;
2002 break;
2004 case EXTENDED_ARG:
2005 opcode = NEXTOP();
2006 oparg = oparg<<16 | NEXTARG();
2007 goto dispatch_opcode;
2008 break;
2010 default:
2011 fprintf(stderr,
2012 "XXX lineno: %d, opcode: %d\n",
2013 f->f_lineno, opcode);
2014 PyErr_SetString(PyExc_SystemError, "unknown opcode");
2015 why = WHY_EXCEPTION;
2016 break;
2018 #ifdef CASE_TOO_BIG
2020 #endif
2022 } /* switch */
2024 on_error:
2026 /* Quickly continue if no error occurred */
2028 if (why == WHY_NOT) {
2029 if (err == 0 && x != NULL) {
2030 #ifdef CHECKEXC
2031 /* This check is expensive! */
2032 if (PyErr_Occurred())
2033 fprintf(stderr,
2034 "XXX undetected error\n");
2035 else
2036 #endif
2037 continue; /* Normal, fast path */
2039 why = WHY_EXCEPTION;
2040 x = Py_None;
2041 err = 0;
2044 /* Double-check exception status */
2046 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
2047 if (!PyErr_Occurred()) {
2048 PyErr_SetString(PyExc_SystemError,
2049 "error return without exception set");
2050 why = WHY_EXCEPTION;
2053 #ifdef CHECKEXC
2054 else {
2055 /* This check is expensive! */
2056 if (PyErr_Occurred()) {
2057 fprintf(stderr,
2058 "XXX undetected error (why=%d)\n",
2059 why);
2060 why = WHY_EXCEPTION;
2063 #endif
2065 /* Log traceback info if this is a real exception */
2067 if (why == WHY_EXCEPTION) {
2068 f->f_lasti = INSTR_OFFSET() - 1;
2069 if (HAS_ARG(opcode))
2070 f->f_lasti -= 2;
2071 PyTraceBack_Here(f);
2073 if (f->f_trace)
2074 call_exc_trace(&f->f_trace, &f->f_trace, f);
2075 if (tstate->sys_profilefunc)
2076 call_exc_trace(&tstate->sys_profilefunc,
2077 (PyObject**)0, f);
2080 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
2082 if (why == WHY_RERAISE)
2083 why = WHY_EXCEPTION;
2085 /* Unwind stacks if a (pseudo) exception occurred */
2087 while (why != WHY_NOT && f->f_iblock > 0) {
2088 PyTryBlock *b = PyFrame_BlockPop(f);
2089 while (STACK_LEVEL() > b->b_level) {
2090 v = POP();
2091 Py_XDECREF(v);
2093 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
2094 why = WHY_NOT;
2095 JUMPTO(b->b_handler);
2096 break;
2098 if (b->b_type == SETUP_FINALLY ||
2099 (b->b_type == SETUP_EXCEPT &&
2100 why == WHY_EXCEPTION)) {
2101 if (why == WHY_EXCEPTION) {
2102 PyObject *exc, *val, *tb;
2103 PyErr_Fetch(&exc, &val, &tb);
2104 if (val == NULL) {
2105 val = Py_None;
2106 Py_INCREF(val);
2108 /* Make the raw exception data
2109 available to the handler,
2110 so a program can emulate the
2111 Python main loop. Don't do
2112 this for 'finally'. */
2113 if (b->b_type == SETUP_EXCEPT) {
2114 PyErr_NormalizeException(
2115 &exc, &val, &tb);
2116 set_exc_info(tstate,
2117 exc, val, tb);
2119 PUSH(tb);
2120 PUSH(val);
2121 PUSH(exc);
2123 else {
2124 if (why == WHY_RETURN)
2125 PUSH(retval);
2126 v = PyInt_FromLong((long)why);
2127 PUSH(v);
2129 why = WHY_NOT;
2130 JUMPTO(b->b_handler);
2131 break;
2133 } /* unwind stack */
2135 /* End the loop if we still have an error (or return) */
2137 if (why != WHY_NOT)
2138 break;
2140 } /* main loop */
2142 /* Pop remaining stack entries */
2144 while (!EMPTY()) {
2145 v = POP();
2146 Py_XDECREF(v);
2149 if (why != WHY_RETURN)
2150 retval = NULL;
2152 if (f->f_trace) {
2153 if (why == WHY_RETURN) {
2154 if (call_trace(&f->f_trace, &f->f_trace, f,
2155 "return", retval)) {
2156 Py_XDECREF(retval);
2157 retval = NULL;
2158 why = WHY_EXCEPTION;
2163 if (tstate->sys_profilefunc && why == WHY_RETURN) {
2164 if (call_trace(&tstate->sys_profilefunc, (PyObject**)0,
2165 f, "return", retval)) {
2166 Py_XDECREF(retval);
2167 retval = NULL;
2168 why = WHY_EXCEPTION;
2172 reset_exc_info(tstate);
2174 --tstate->recursion_depth;
2176 fail: /* Jump here from prelude on failure */
2178 /* Restore previous frame and release the current one */
2180 tstate->frame = f->f_back;
2181 Py_DECREF(f);
2183 return retval;
2186 static void
2187 set_exc_info(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb)
2189 PyFrameObject *frame;
2190 PyObject *tmp_type, *tmp_value, *tmp_tb;
2192 frame = tstate->frame;
2193 if (frame->f_exc_type == NULL) {
2194 /* This frame didn't catch an exception before */
2195 /* Save previous exception of this thread in this frame */
2196 if (tstate->exc_type == NULL) {
2197 Py_INCREF(Py_None);
2198 tstate->exc_type = Py_None;
2200 tmp_type = frame->f_exc_type;
2201 tmp_value = frame->f_exc_value;
2202 tmp_tb = frame->f_exc_traceback;
2203 Py_XINCREF(tstate->exc_type);
2204 Py_XINCREF(tstate->exc_value);
2205 Py_XINCREF(tstate->exc_traceback);
2206 frame->f_exc_type = tstate->exc_type;
2207 frame->f_exc_value = tstate->exc_value;
2208 frame->f_exc_traceback = tstate->exc_traceback;
2209 Py_XDECREF(tmp_type);
2210 Py_XDECREF(tmp_value);
2211 Py_XDECREF(tmp_tb);
2213 /* Set new exception for this thread */
2214 tmp_type = tstate->exc_type;
2215 tmp_value = tstate->exc_value;
2216 tmp_tb = tstate->exc_traceback;
2217 Py_XINCREF(type);
2218 Py_XINCREF(value);
2219 Py_XINCREF(tb);
2220 tstate->exc_type = type;
2221 tstate->exc_value = value;
2222 tstate->exc_traceback = tb;
2223 Py_XDECREF(tmp_type);
2224 Py_XDECREF(tmp_value);
2225 Py_XDECREF(tmp_tb);
2226 /* For b/w compatibility */
2227 PySys_SetObject("exc_type", type);
2228 PySys_SetObject("exc_value", value);
2229 PySys_SetObject("exc_traceback", tb);
2232 static void
2233 reset_exc_info(PyThreadState *tstate)
2235 PyFrameObject *frame;
2236 PyObject *tmp_type, *tmp_value, *tmp_tb;
2237 frame = tstate->frame;
2238 if (frame->f_exc_type != NULL) {
2239 /* This frame caught an exception */
2240 tmp_type = tstate->exc_type;
2241 tmp_value = tstate->exc_value;
2242 tmp_tb = tstate->exc_traceback;
2243 Py_XINCREF(frame->f_exc_type);
2244 Py_XINCREF(frame->f_exc_value);
2245 Py_XINCREF(frame->f_exc_traceback);
2246 tstate->exc_type = frame->f_exc_type;
2247 tstate->exc_value = frame->f_exc_value;
2248 tstate->exc_traceback = frame->f_exc_traceback;
2249 Py_XDECREF(tmp_type);
2250 Py_XDECREF(tmp_value);
2251 Py_XDECREF(tmp_tb);
2252 /* For b/w compatibility */
2253 PySys_SetObject("exc_type", frame->f_exc_type);
2254 PySys_SetObject("exc_value", frame->f_exc_value);
2255 PySys_SetObject("exc_traceback", frame->f_exc_traceback);
2257 tmp_type = frame->f_exc_type;
2258 tmp_value = frame->f_exc_value;
2259 tmp_tb = frame->f_exc_traceback;
2260 frame->f_exc_type = NULL;
2261 frame->f_exc_value = NULL;
2262 frame->f_exc_traceback = NULL;
2263 Py_XDECREF(tmp_type);
2264 Py_XDECREF(tmp_value);
2265 Py_XDECREF(tmp_tb);
2268 /* Logic for the raise statement (too complicated for inlining).
2269 This *consumes* a reference count to each of its arguments. */
2270 static enum why_code
2271 do_raise(PyObject *type, PyObject *value, PyObject *tb)
2273 if (type == NULL) {
2274 /* Reraise */
2275 PyThreadState *tstate = PyThreadState_Get();
2276 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
2277 value = tstate->exc_value;
2278 tb = tstate->exc_traceback;
2279 Py_XINCREF(type);
2280 Py_XINCREF(value);
2281 Py_XINCREF(tb);
2284 /* We support the following forms of raise:
2285 raise <class>, <classinstance>
2286 raise <class>, <argument tuple>
2287 raise <class>, None
2288 raise <class>, <argument>
2289 raise <classinstance>, None
2290 raise <string>, <object>
2291 raise <string>, None
2293 An omitted second argument is the same as None.
2295 In addition, raise <tuple>, <anything> is the same as
2296 raising the tuple's first item (and it better have one!);
2297 this rule is applied recursively.
2299 Finally, an optional third argument can be supplied, which
2300 gives the traceback to be substituted (useful when
2301 re-raising an exception after examining it). */
2303 /* First, check the traceback argument, replacing None with
2304 NULL. */
2305 if (tb == Py_None) {
2306 Py_DECREF(tb);
2307 tb = NULL;
2309 else if (tb != NULL && !PyTraceBack_Check(tb)) {
2310 PyErr_SetString(PyExc_TypeError,
2311 "raise 3rd arg must be traceback or None");
2312 goto raise_error;
2315 /* Next, replace a missing value with None */
2316 if (value == NULL) {
2317 value = Py_None;
2318 Py_INCREF(value);
2321 /* Next, repeatedly, replace a tuple exception with its first item */
2322 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
2323 PyObject *tmp = type;
2324 type = PyTuple_GET_ITEM(type, 0);
2325 Py_INCREF(type);
2326 Py_DECREF(tmp);
2329 if (PyString_Check(type))
2332 else if (PyClass_Check(type))
2333 PyErr_NormalizeException(&type, &value, &tb);
2335 else if (PyInstance_Check(type)) {
2336 /* Raising an instance. The value should be a dummy. */
2337 if (value != Py_None) {
2338 PyErr_SetString(PyExc_TypeError,
2339 "instance exception may not have a separate value");
2340 goto raise_error;
2342 else {
2343 /* Normalize to raise <class>, <instance> */
2344 Py_DECREF(value);
2345 value = type;
2346 type = (PyObject*) ((PyInstanceObject*)type)->in_class;
2347 Py_INCREF(type);
2350 else {
2351 /* Not something you can raise. You get an exception
2352 anyway, just not what you specified :-) */
2353 PyErr_SetString(PyExc_TypeError,
2354 "exceptions must be strings, classes, or instances");
2355 goto raise_error;
2357 PyErr_Restore(type, value, tb);
2358 if (tb == NULL)
2359 return WHY_EXCEPTION;
2360 else
2361 return WHY_RERAISE;
2362 raise_error:
2363 Py_XDECREF(value);
2364 Py_XDECREF(type);
2365 Py_XDECREF(tb);
2366 return WHY_EXCEPTION;
2369 static int
2370 unpack_sequence(PyObject *v, int argcnt, PyObject **sp)
2372 int i;
2373 PyObject *w;
2375 for (i = 0; i < argcnt; i++) {
2376 if (! (w = PySequence_GetItem(v, i))) {
2377 if (PyErr_ExceptionMatches(PyExc_IndexError))
2378 PyErr_SetString(PyExc_ValueError,
2379 "unpack sequence of wrong size");
2380 goto finally;
2382 *--sp = w;
2384 /* we better get an IndexError now */
2385 if (PySequence_GetItem(v, i) == NULL) {
2386 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2387 PyErr_Clear();
2388 return 1;
2390 /* some other exception occurred. fall through to finally */
2392 else
2393 PyErr_SetString(PyExc_ValueError,
2394 "unpack sequence of wrong size");
2395 /* fall through */
2396 finally:
2397 for (; i > 0; i--, sp++)
2398 Py_DECREF(*sp);
2400 return 0;
2404 #ifdef LLTRACE
2405 static int
2406 prtrace(PyObject *v, char *str)
2408 printf("%s ", str);
2409 if (PyObject_Print(v, stdout, 0) != 0)
2410 PyErr_Clear(); /* Don't know what else to do */
2411 printf("\n");
2412 return 1;
2414 #endif
2416 static void
2417 call_exc_trace(PyObject **p_trace, PyObject **p_newtrace, PyFrameObject *f)
2419 PyObject *type, *value, *traceback, *arg;
2420 int err;
2421 PyErr_Fetch(&type, &value, &traceback);
2422 if (value == NULL) {
2423 value = Py_None;
2424 Py_INCREF(value);
2426 arg = Py_BuildValue("(OOO)", type, value, traceback);
2427 if (arg == NULL) {
2428 PyErr_Restore(type, value, traceback);
2429 return;
2431 err = call_trace(p_trace, p_newtrace, f, "exception", arg);
2432 Py_DECREF(arg);
2433 if (err == 0)
2434 PyErr_Restore(type, value, traceback);
2435 else {
2436 Py_XDECREF(type);
2437 Py_XDECREF(value);
2438 Py_XDECREF(traceback);
2442 /* PyObject **p_trace: in/out; may not be NULL;
2443 may not point to NULL variable initially
2444 PyObject **p_newtrace: in/out; may be NULL;
2445 may point to NULL variable;
2446 may be same variable as p_newtrace */
2448 static int
2449 call_trace(PyObject **p_trace, PyObject **p_newtrace, PyFrameObject *f,
2450 char *msg, PyObject *arg)
2452 PyThreadState *tstate = f->f_tstate;
2453 PyObject *args, *what;
2454 PyObject *res = NULL;
2456 if (tstate->tracing) {
2457 /* Don't do recursive traces */
2458 if (p_newtrace) {
2459 Py_XDECREF(*p_newtrace);
2460 *p_newtrace = NULL;
2462 return 0;
2465 args = PyTuple_New(3);
2466 if (args == NULL)
2467 goto cleanup;
2468 what = PyString_FromString(msg);
2469 if (what == NULL)
2470 goto cleanup;
2471 Py_INCREF(f);
2472 PyTuple_SET_ITEM(args, 0, (PyObject *)f);
2473 PyTuple_SET_ITEM(args, 1, what);
2474 if (arg == NULL)
2475 arg = Py_None;
2476 Py_INCREF(arg);
2477 PyTuple_SET_ITEM(args, 2, arg);
2478 tstate->tracing++;
2479 PyFrame_FastToLocals(f);
2480 res = PyEval_CallObject(*p_trace, args); /* May clear *p_trace! */
2481 PyFrame_LocalsToFast(f, 1);
2482 tstate->tracing--;
2483 cleanup:
2484 Py_XDECREF(args);
2485 if (res == NULL) {
2486 /* The trace proc raised an exception */
2487 PyTraceBack_Here(f);
2488 Py_XDECREF(*p_trace);
2489 *p_trace = NULL;
2490 if (p_newtrace) {
2491 Py_XDECREF(*p_newtrace);
2492 *p_newtrace = NULL;
2494 /* to be extra double plus sure we don't get recursive
2495 * calls inf either tracefunc or profilefunc gets an
2496 * exception, zap the global variables.
2498 Py_XDECREF(tstate->sys_tracefunc);
2499 tstate->sys_tracefunc = NULL;
2500 Py_XDECREF(tstate->sys_profilefunc);
2501 tstate->sys_profilefunc = NULL;
2502 return -1;
2504 else {
2505 if (p_newtrace) {
2506 Py_XDECREF(*p_newtrace);
2507 if (res == Py_None)
2508 *p_newtrace = NULL;
2509 else {
2510 Py_INCREF(res);
2511 *p_newtrace = res;
2514 Py_DECREF(res);
2515 return 0;
2519 PyObject *
2520 PyEval_GetBuiltins(void)
2522 PyThreadState *tstate = PyThreadState_Get();
2523 PyFrameObject *current_frame = tstate->frame;
2524 if (current_frame == NULL)
2525 return tstate->interp->builtins;
2526 else
2527 return current_frame->f_builtins;
2530 PyObject *
2531 PyEval_GetLocals(void)
2533 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2534 if (current_frame == NULL)
2535 return NULL;
2536 PyFrame_FastToLocals(current_frame);
2537 return current_frame->f_locals;
2540 PyObject *
2541 PyEval_GetGlobals(void)
2543 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2544 if (current_frame == NULL)
2545 return NULL;
2546 else
2547 return current_frame->f_globals;
2550 PyObject *
2551 PyEval_GetFrame(void)
2553 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2554 return (PyObject *)current_frame;
2558 PyEval_GetRestricted(void)
2560 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2561 return current_frame == NULL ? 0 : current_frame->f_restricted;
2565 Py_FlushLine(void)
2567 PyObject *f = PySys_GetObject("stdout");
2568 if (f == NULL)
2569 return 0;
2570 if (!PyFile_SoftSpace(f, 0))
2571 return 0;
2572 return PyFile_WriteString("\n", f);
2576 /* External interface to call any callable object.
2577 The arg must be a tuple or NULL. */
2579 #undef PyEval_CallObject
2580 /* for backward compatibility: export this interface */
2582 PyObject *
2583 PyEval_CallObject(PyObject *func, PyObject *arg)
2585 return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL);
2587 #define PyEval_CallObject(func,arg) \
2588 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
2590 PyObject *
2591 PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
2593 ternaryfunc call;
2594 PyObject *result;
2596 if (arg == NULL)
2597 arg = PyTuple_New(0);
2598 else if (!PyTuple_Check(arg)) {
2599 PyErr_SetString(PyExc_TypeError,
2600 "argument list must be a tuple");
2601 return NULL;
2603 else
2604 Py_INCREF(arg);
2606 if (kw != NULL && !PyDict_Check(kw)) {
2607 PyErr_SetString(PyExc_TypeError,
2608 "keyword list must be a dictionary");
2609 Py_DECREF(arg);
2610 return NULL;
2613 if ((call = func->ob_type->tp_call) != NULL)
2614 result = (*call)(func, arg, kw);
2615 else if (PyMethod_Check(func) || PyFunction_Check(func))
2616 result = call_function(func, arg, kw);
2617 else
2618 result = call_builtin(func, arg, kw);
2620 Py_DECREF(arg);
2622 if (result == NULL && !PyErr_Occurred())
2623 PyErr_SetString(PyExc_SystemError,
2624 "NULL result without error in call_object");
2626 return result;
2629 static PyObject *
2630 call_builtin(PyObject *func, PyObject *arg, PyObject *kw)
2632 if (PyCFunction_Check(func)) {
2633 PyCFunction meth = PyCFunction_GetFunction(func);
2634 PyObject *self = PyCFunction_GetSelf(func);
2635 int flags = PyCFunction_GetFlags(func);
2636 if (!(flags & METH_VARARGS)) {
2637 int size = PyTuple_Size(arg);
2638 if (size == 1)
2639 arg = PyTuple_GET_ITEM(arg, 0);
2640 else if (size == 0)
2641 arg = NULL;
2643 if (flags & METH_KEYWORDS)
2644 return (*(PyCFunctionWithKeywords)meth)(self, arg, kw);
2645 if (kw != NULL && PyDict_Size(kw) != 0) {
2646 PyErr_SetString(PyExc_TypeError,
2647 "this function takes no keyword arguments");
2648 return NULL;
2650 return (*meth)(self, arg);
2652 if (PyClass_Check(func)) {
2653 return PyInstance_New(func, arg, kw);
2655 if (PyInstance_Check(func)) {
2656 PyObject *res, *call = PyObject_GetAttrString(func,"__call__");
2657 if (call == NULL) {
2658 PyErr_Clear();
2659 PyErr_SetString(PyExc_AttributeError,
2660 "no __call__ method defined");
2661 return NULL;
2663 res = PyEval_CallObjectWithKeywords(call, arg, kw);
2664 Py_DECREF(call);
2665 return res;
2667 PyErr_Format(PyExc_TypeError, "call of non-function (type %.400s)",
2668 func->ob_type->tp_name);
2669 return NULL;
2672 static PyObject *
2673 call_function(PyObject *func, PyObject *arg, PyObject *kw)
2675 PyObject *class = NULL; /* == owner */
2676 PyObject *argdefs;
2677 PyObject **d, **k;
2678 int nk, nd;
2679 PyObject *result;
2681 if (kw != NULL && !PyDict_Check(kw)) {
2682 PyErr_BadInternalCall();
2683 return NULL;
2686 if (PyMethod_Check(func)) {
2687 PyObject *self = PyMethod_Self(func);
2688 class = PyMethod_Class(func);
2689 func = PyMethod_Function(func);
2690 if (self == NULL) {
2691 /* Unbound methods must be called with an instance of
2692 the class (or a derived class) as first argument */
2693 if (PyTuple_Size(arg) >= 1) {
2694 self = PyTuple_GET_ITEM(arg, 0);
2695 if (self != NULL &&
2696 PyInstance_Check(self) &&
2697 PyClass_IsSubclass((PyObject *)
2698 (((PyInstanceObject *)self)->in_class),
2699 class))
2700 /* Handy-dandy */ ;
2701 else
2702 self = NULL;
2704 if (self == NULL) {
2705 PyErr_SetString(PyExc_TypeError,
2706 "unbound method must be called with class instance 1st argument");
2707 return NULL;
2709 Py_INCREF(arg);
2711 else {
2712 int argcount = PyTuple_Size(arg);
2713 PyObject *newarg = PyTuple_New(argcount + 1);
2714 int i;
2715 if (newarg == NULL)
2716 return NULL;
2717 Py_INCREF(self);
2718 PyTuple_SET_ITEM(newarg, 0, self);
2719 for (i = 0; i < argcount; i++) {
2720 PyObject *v = PyTuple_GET_ITEM(arg, i);
2721 Py_XINCREF(v);
2722 PyTuple_SET_ITEM(newarg, i+1, v);
2724 arg = newarg;
2726 if (!PyFunction_Check(func)) {
2727 result = PyEval_CallObjectWithKeywords(func, arg, kw);
2728 Py_DECREF(arg);
2729 return result;
2732 else {
2733 if (!PyFunction_Check(func)) {
2734 PyErr_Format(PyExc_TypeError,
2735 "call of non-function (type %.200s)",
2736 func->ob_type->tp_name);
2737 return NULL;
2739 Py_INCREF(arg);
2742 argdefs = PyFunction_GetDefaults(func);
2743 if (argdefs != NULL && PyTuple_Check(argdefs)) {
2744 d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
2745 nd = PyTuple_Size(argdefs);
2747 else {
2748 d = NULL;
2749 nd = 0;
2752 if (kw != NULL) {
2753 int pos, i;
2754 nk = PyDict_Size(kw);
2755 k = PyMem_NEW(PyObject *, 2*nk);
2756 if (k == NULL) {
2757 PyErr_NoMemory();
2758 Py_DECREF(arg);
2759 return NULL;
2761 pos = i = 0;
2762 while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
2763 i += 2;
2764 nk = i/2;
2765 /* XXX This is broken if the caller deletes dict items! */
2767 else {
2768 k = NULL;
2769 nk = 0;
2772 result = eval_code2(
2773 (PyCodeObject *)PyFunction_GetCode(func),
2774 PyFunction_GetGlobals(func), (PyObject *)NULL,
2775 &PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
2776 k, nk,
2777 d, nd,
2778 class);
2780 Py_DECREF(arg);
2781 if (k != NULL)
2782 PyMem_DEL(k);
2784 return result;
2787 #define SLICE_ERROR_MSG \
2788 "standard sequence type does not support step size other than one"
2790 static PyObject *
2791 loop_subscript(PyObject *v, PyObject *w)
2793 PySequenceMethods *sq = v->ob_type->tp_as_sequence;
2794 int i;
2795 if (sq == NULL || sq->sq_item == NULL) {
2796 PyErr_SetString(PyExc_TypeError, "loop over non-sequence");
2797 return NULL;
2799 i = PyInt_AsLong(w);
2800 v = (*sq->sq_item)(v, i);
2801 if (v)
2802 return v;
2803 if (PyErr_ExceptionMatches(PyExc_IndexError))
2804 PyErr_Clear();
2805 return NULL;
2808 /* Extract a slice index from a PyInt or PyLong, the index is bound to
2809 the range [-INT_MAX+1, INTMAX]. Returns 0 and an exception if there is
2810 and error. Returns 1 on success.*/
2813 _PyEval_SliceIndex(PyObject *v, int *pi)
2815 if (v != NULL) {
2816 long x;
2817 if (PyInt_Check(v)) {
2818 x = PyInt_AsLong(v);
2819 } else if (PyLong_Check(v)) {
2820 x = PyLong_AsLong(v);
2821 if (x==-1 && PyErr_Occurred()) {
2822 PyObject *long_zero;
2824 if (!PyErr_ExceptionMatches( PyExc_OverflowError ) ) {
2825 /* It's not an overflow error, so just
2826 signal an error */
2827 return 0;
2830 /* It's an overflow error, so we need to
2831 check the sign of the long integer,
2832 set the value to INT_MAX or 0, and clear
2833 the error. */
2835 /* Create a long integer with a value of 0 */
2836 long_zero = PyLong_FromLong( 0L );
2837 if (long_zero == NULL) return 0;
2839 /* Check sign */
2840 if (PyObject_Compare(long_zero, v) < 0)
2841 x = INT_MAX;
2842 else
2843 x = 0;
2845 /* Free the long integer we created, and clear the
2846 OverflowError */
2847 Py_DECREF(long_zero);
2848 PyErr_Clear();
2850 } else {
2851 PyErr_SetString(PyExc_TypeError,
2852 "slice index must be int");
2853 return 0;
2855 /* Truncate -- very long indices are truncated anyway */
2856 if (x > INT_MAX)
2857 x = INT_MAX;
2858 else if (x < -INT_MAX)
2859 x = 0;
2860 *pi = x;
2862 return 1;
2865 static PyObject *
2866 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
2868 int ilow = 0, ihigh = INT_MAX;
2869 if (!_PyEval_SliceIndex(v, &ilow))
2870 return NULL;
2871 if (!_PyEval_SliceIndex(w, &ihigh))
2872 return NULL;
2873 return PySequence_GetSlice(u, ilow, ihigh);
2876 static int
2877 assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x) /* u[v:w] = x */
2879 int ilow = 0, ihigh = INT_MAX;
2880 if (!_PyEval_SliceIndex(v, &ilow))
2881 return -1;
2882 if (!_PyEval_SliceIndex(w, &ihigh))
2883 return -1;
2884 if (x == NULL)
2885 return PySequence_DelSlice(u, ilow, ihigh);
2886 else
2887 return PySequence_SetSlice(u, ilow, ihigh, x);
2890 static PyObject *
2891 cmp_outcome(int op, register PyObject *v, register PyObject *w)
2893 register int cmp;
2894 register int res = 0;
2895 switch (op) {
2896 case IS:
2897 case IS_NOT:
2898 res = (v == w);
2899 if (op == (int) IS_NOT)
2900 res = !res;
2901 break;
2902 case IN:
2903 case NOT_IN:
2904 res = PySequence_Contains(w, v);
2905 if (res < 0)
2906 return NULL;
2907 if (op == (int) NOT_IN)
2908 res = !res;
2909 break;
2910 case EXC_MATCH:
2911 res = PyErr_GivenExceptionMatches(v, w);
2912 break;
2913 default:
2914 cmp = PyObject_Compare(v, w);
2915 if (cmp && PyErr_Occurred())
2916 return NULL;
2917 switch (op) {
2918 case LT: res = cmp < 0; break;
2919 case LE: res = cmp <= 0; break;
2920 case EQ: res = cmp == 0; break;
2921 case NE: res = cmp != 0; break;
2922 case GT: res = cmp > 0; break;
2923 case GE: res = cmp >= 0; break;
2924 /* XXX no default? (res is initialized to 0 though) */
2927 v = res ? Py_True : Py_False;
2928 Py_INCREF(v);
2929 return v;
2932 static PyObject *
2933 import_from(PyObject *v, PyObject *name)
2935 PyObject *w, *x;
2936 if (!PyModule_Check(v)) {
2937 PyErr_SetString(PyExc_TypeError,
2938 "import-from requires module object");
2939 return NULL;
2941 w = PyModule_GetDict(v); /* TDB: can this not fail ? */
2942 x = PyDict_GetItem(w, name);
2943 if (x == NULL) {
2944 PyErr_Format(PyExc_ImportError,
2945 "cannot import name %.230s",
2946 PyString_AsString(name));
2947 } else
2948 Py_INCREF(x);
2949 return x;
2952 static int
2953 import_all_from(PyObject *locals, PyObject *v)
2955 int pos = 0, err;
2956 PyObject *name, *value;
2957 PyObject *w;
2959 if (!PyModule_Check(v)) {
2960 PyErr_SetString(PyExc_TypeError,
2961 "import-from requires module object");
2962 return -1;
2964 w = PyModule_GetDict(v); /* TBD: can this not fail ? */
2966 while (PyDict_Next(w, &pos, &name, &value)) {
2967 if (!PyString_Check(name) ||
2968 PyString_AsString(name)[0] == '_')
2969 continue;
2970 Py_INCREF(value);
2971 err = PyDict_SetItem(locals, name, value);
2972 Py_DECREF(value);
2973 if (err != 0)
2974 return -1;
2976 return 0;
2979 static PyObject *
2980 build_class(PyObject *methods, PyObject *bases, PyObject *name)
2982 int i, n;
2983 if (!PyTuple_Check(bases)) {
2984 PyErr_SetString(PyExc_SystemError,
2985 "build_class with non-tuple bases");
2986 return NULL;
2988 if (!PyDict_Check(methods)) {
2989 PyErr_SetString(PyExc_SystemError,
2990 "build_class with non-dictionary");
2991 return NULL;
2993 if (!PyString_Check(name)) {
2994 PyErr_SetString(PyExc_SystemError,
2995 "build_class with non-string name");
2996 return NULL;
2998 n = PyTuple_Size(bases);
2999 for (i = 0; i < n; i++) {
3000 PyObject *base = PyTuple_GET_ITEM(bases, i);
3001 if (!PyClass_Check(base)) {
3002 /* Call the base's *type*, if it is callable.
3003 This code is a hook for Donald Beaudry's
3004 and Jim Fulton's type extensions. In
3005 unextended Python it will never be triggered
3006 since its types are not callable.
3007 Ditto: call the bases's *class*, if it has
3008 one. This makes the same thing possible
3009 without writing C code. A true meta-object
3010 protocol! */
3011 PyObject *basetype = (PyObject *)base->ob_type;
3012 PyObject *callable = NULL;
3013 if (PyCallable_Check(basetype))
3014 callable = basetype;
3015 else
3016 callable = PyObject_GetAttrString(
3017 base, "__class__");
3018 if (callable) {
3019 PyObject *args;
3020 PyObject *newclass = NULL;
3021 args = Py_BuildValue(
3022 "(OOO)", name, bases, methods);
3023 if (args != NULL) {
3024 newclass = PyEval_CallObject(
3025 callable, args);
3026 Py_DECREF(args);
3028 if (callable != basetype) {
3029 Py_DECREF(callable);
3031 return newclass;
3033 PyErr_SetString(PyExc_TypeError,
3034 "base is not a class object");
3035 return NULL;
3038 return PyClass_New(bases, methods, name);
3041 static int
3042 exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
3043 PyObject *locals)
3045 int n;
3046 PyObject *v;
3047 int plain = 0;
3049 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
3050 ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
3051 /* Backward compatibility hack */
3052 globals = PyTuple_GetItem(prog, 1);
3053 if (n == 3)
3054 locals = PyTuple_GetItem(prog, 2);
3055 prog = PyTuple_GetItem(prog, 0);
3057 if (globals == Py_None) {
3058 globals = PyEval_GetGlobals();
3059 if (locals == Py_None) {
3060 locals = PyEval_GetLocals();
3061 plain = 1;
3064 else if (locals == Py_None)
3065 locals = globals;
3066 if (!PyString_Check(prog) &&
3067 !PyUnicode_Check(prog) &&
3068 !PyCode_Check(prog) &&
3069 !PyFile_Check(prog)) {
3070 PyErr_SetString(PyExc_TypeError,
3071 "exec 1st arg must be string, code or file object");
3072 return -1;
3074 if (!PyDict_Check(globals) || !PyDict_Check(locals)) {
3075 PyErr_SetString(PyExc_TypeError,
3076 "exec 2nd/3rd args must be dict or None");
3077 return -1;
3079 if (PyDict_GetItemString(globals, "__builtins__") == NULL)
3080 PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
3081 if (PyCode_Check(prog)) {
3082 v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
3084 else if (PyFile_Check(prog)) {
3085 FILE *fp = PyFile_AsFile(prog);
3086 char *name = PyString_AsString(PyFile_Name(prog));
3087 v = PyRun_File(fp, name, Py_file_input, globals, locals);
3089 else {
3090 char *str;
3091 if (PyString_AsStringAndSize(prog, &str, NULL))
3092 return -1;
3093 v = PyRun_String(str, Py_file_input, globals, locals);
3095 if (plain)
3096 PyFrame_LocalsToFast(f, 0);
3097 if (v == NULL)
3098 return -1;
3099 Py_DECREF(v);
3100 return 0;
3103 static void
3104 format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
3106 char *obj_str;
3108 if (!obj)
3109 return;
3111 obj_str = PyString_AsString(obj);
3112 if (!obj_str)
3113 return;
3115 PyErr_Format(exc, format_str, obj_str);
3118 #ifdef DYNAMIC_EXECUTION_PROFILE
3120 PyObject *
3121 getarray(long a[256])
3123 int i;
3124 PyObject *l = PyList_New(256);
3125 if (l == NULL) return NULL;
3126 for (i = 0; i < 256; i++) {
3127 PyObject *x = PyInt_FromLong(a[i]);
3128 if (x == NULL) {
3129 Py_DECREF(l);
3130 return NULL;
3132 PyList_SetItem(l, i, x);
3134 for (i = 0; i < 256; i++)
3135 a[i] = 0;
3136 return l;
3139 PyObject *
3140 _Py_GetDXProfile(PyObject *self, PyObject *args)
3142 #ifndef DXPAIRS
3143 return getarray(dxp);
3144 #else
3145 int i;
3146 PyObject *l = PyList_New(257);
3147 if (l == NULL) return NULL;
3148 for (i = 0; i < 257; i++) {
3149 PyObject *x = getarray(dxpairs[i]);
3150 if (x == NULL) {
3151 Py_DECREF(l);
3152 return NULL;
3154 PyList_SetItem(l, i, x);
3156 return l;
3157 #endif
3160 #endif