Fix an amazing number of typos & malformed sentences reported by Detlef
[python/dscho.git] / Python / ceval.c
blobf52eb0e88ab864b1dce90f6100f44a62bdd524e2
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
15 permission.
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Execute compiled code */
34 /* XXX TO DO:
35 XXX how to pass arguments to call_trace?
36 XXX speed up searching for keywords by using a dictionary
37 XXX document it!
40 #include "Python.h"
42 #include "compile.h"
43 #include "frameobject.h"
44 #include "eval.h"
45 #include "opcode.h"
47 #include <ctype.h>
49 #ifdef HAVE_LIMITS_H
50 #include <limits.h>
51 #else
52 #define INT_MAX 2147483647
53 #endif
55 /* Turn this on if your compiler chokes on the big switch: */
56 /* #define CASE_TOO_BIG 1 */
58 #ifdef Py_DEBUG
59 /* For debugging the interpreter: */
60 #define LLTRACE 1 /* Low-level trace feature */
61 #define CHECKEXC 1 /* Double-check exception checking */
62 #endif
65 /* Forward declarations */
67 static PyObject *eval_code2 Py_PROTO((PyCodeObject *,
68 PyObject *, PyObject *,
69 PyObject **, int,
70 PyObject **, int,
71 PyObject **, int,
72 PyObject *));
73 #ifdef LLTRACE
74 static int prtrace Py_PROTO((PyObject *, char *));
75 #endif
76 static void call_exc_trace Py_PROTO((PyObject **, PyObject**,
77 PyFrameObject *));
78 static int call_trace Py_PROTO((PyObject **, PyObject **,
79 PyFrameObject *, char *, PyObject *));
80 static PyObject *call_builtin Py_PROTO((PyObject *, PyObject *, PyObject *));
81 static PyObject *call_function Py_PROTO((PyObject *, PyObject *, PyObject *));
82 static PyObject *loop_subscript Py_PROTO((PyObject *, PyObject *));
83 static int slice_index Py_PROTO((PyObject *, int *));
84 static PyObject *apply_slice Py_PROTO((PyObject *, PyObject *, PyObject *));
85 static int assign_slice Py_PROTO((PyObject *, PyObject *,
86 PyObject *, PyObject *));
87 static PyObject *cmp_outcome Py_PROTO((int, PyObject *, PyObject *));
88 static int import_from Py_PROTO((PyObject *, PyObject *, PyObject *));
89 static PyObject *build_class Py_PROTO((PyObject *, PyObject *, PyObject *));
90 static int exec_statement Py_PROTO((PyFrameObject *,
91 PyObject *, PyObject *, PyObject *));
92 static PyObject *find_from_args Py_PROTO((PyFrameObject *, int));
93 static void set_exc_info Py_PROTO((PyThreadState *,
94 PyObject *, PyObject *, PyObject *));
95 static void reset_exc_info Py_PROTO((PyThreadState *));
98 /* Dynamic execution profile */
99 #ifdef DYNAMIC_EXECUTION_PROFILE
100 #ifdef DXPAIRS
101 static long dxpairs[257][256];
102 #define dxp dxpairs[256]
103 #else
104 static long dxp[256];
105 #endif
106 #endif
109 #ifdef WITH_THREAD
111 #include <errno.h>
112 #include "pythread.h"
114 extern int _PyThread_Started; /* Flag for Py_Exit */
116 static PyThread_type_lock interpreter_lock = 0;
117 static long main_thread = 0;
119 void
120 PyEval_InitThreads()
122 if (interpreter_lock)
123 return;
124 _PyThread_Started = 1;
125 interpreter_lock = PyThread_allocate_lock();
126 PyThread_acquire_lock(interpreter_lock, 1);
127 main_thread = PyThread_get_thread_ident();
130 void
131 PyEval_AcquireLock()
133 PyThread_acquire_lock(interpreter_lock, 1);
136 void
137 PyEval_ReleaseLock()
139 PyThread_release_lock(interpreter_lock);
142 void
143 PyEval_AcquireThread(tstate)
144 PyThreadState *tstate;
146 if (tstate == NULL)
147 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
148 PyThread_acquire_lock(interpreter_lock, 1);
149 if (PyThreadState_Swap(tstate) != NULL)
150 Py_FatalError(
151 "PyEval_AcquireThread: non-NULL old thread state");
154 void
155 PyEval_ReleaseThread(tstate)
156 PyThreadState *tstate;
158 if (tstate == NULL)
159 Py_FatalError("PyEval_ReleaseThread: NULL thread state");
160 if (PyThreadState_Swap(NULL) != tstate)
161 Py_FatalError("PyEval_ReleaseThread: wrong thread state");
162 PyThread_release_lock(interpreter_lock);
164 #endif
166 /* Functions save_thread and restore_thread are always defined so
167 dynamically loaded modules needn't be compiled separately for use
168 with and without threads: */
170 PyThreadState *
171 PyEval_SaveThread()
173 PyThreadState *tstate = PyThreadState_Swap(NULL);
174 if (tstate == NULL)
175 Py_FatalError("PyEval_SaveThread: NULL tstate");
176 #ifdef WITH_THREAD
177 if (interpreter_lock)
178 PyThread_release_lock(interpreter_lock);
179 #endif
180 return tstate;
183 void
184 PyEval_RestoreThread(tstate)
185 PyThreadState *tstate;
187 if (tstate == NULL)
188 Py_FatalError("PyEval_RestoreThread: NULL tstate");
189 #ifdef WITH_THREAD
190 if (interpreter_lock) {
191 int err = errno;
192 PyThread_acquire_lock(interpreter_lock, 1);
193 errno = err;
195 #endif
196 PyThreadState_Swap(tstate);
200 /* Mechanism whereby asynchronously executing callbacks (e.g. UNIX
201 signal handlers or Mac I/O completion routines) can schedule calls
202 to a function to be called synchronously.
203 The synchronous function is called with one void* argument.
204 It should return 0 for success or -1 for failure -- failure should
205 be accompanied by an exception.
207 If registry succeeds, the registry function returns 0; if it fails
208 (e.g. due to too many pending calls) it returns -1 (without setting
209 an exception condition).
211 Note that because registry may occur from within signal handlers,
212 or other asynchronous events, calling malloc() is unsafe!
214 #ifdef WITH_THREAD
215 Any thread can schedule pending calls, but only the main thread
216 will execute them.
217 #endif
219 XXX WARNING! ASYNCHRONOUSLY EXECUTING CODE!
220 There are two possible race conditions:
221 (1) nested asynchronous registry calls;
222 (2) registry calls made while pending calls are being processed.
223 While (1) is very unlikely, (2) is a real possibility.
224 The current code is safe against (2), but not against (1).
225 The safety against (2) is derived from the fact that only one
226 thread (the main thread) ever takes things out of the queue.
228 XXX Darn! With the advent of thread state, we should have an array
229 of pending calls per thread in the thread state! Later...
232 #define NPENDINGCALLS 32
233 static struct {
234 int (*func) Py_PROTO((ANY *));
235 ANY *arg;
236 } pendingcalls[NPENDINGCALLS];
237 static volatile int pendingfirst = 0;
238 static volatile int pendinglast = 0;
239 static volatile int things_to_do = 0;
242 Py_AddPendingCall(func, arg)
243 int (*func) Py_PROTO((ANY *));
244 ANY *arg;
246 static int busy = 0;
247 int i, j;
248 /* XXX Begin critical section */
249 /* XXX If you want this to be safe against nested
250 XXX asynchronous calls, you'll have to work harder! */
251 if (busy)
252 return -1;
253 busy = 1;
254 i = pendinglast;
255 j = (i + 1) % NPENDINGCALLS;
256 if (j == pendingfirst)
257 return -1; /* Queue full */
258 pendingcalls[i].func = func;
259 pendingcalls[i].arg = arg;
260 pendinglast = j;
261 things_to_do = 1; /* Signal main loop */
262 busy = 0;
263 /* XXX End critical section */
264 return 0;
268 Py_MakePendingCalls()
270 static int busy = 0;
271 #ifdef WITH_THREAD
272 if (main_thread && PyThread_get_thread_ident() != main_thread)
273 return 0;
274 #endif
275 if (busy)
276 return 0;
277 busy = 1;
278 things_to_do = 0;
279 for (;;) {
280 int i;
281 int (*func) Py_PROTO((ANY *));
282 ANY *arg;
283 i = pendingfirst;
284 if (i == pendinglast)
285 break; /* Queue empty */
286 func = pendingcalls[i].func;
287 arg = pendingcalls[i].arg;
288 pendingfirst = (i + 1) % NPENDINGCALLS;
289 if (func(arg) < 0) {
290 busy = 0;
291 things_to_do = 1; /* We're not done yet */
292 return -1;
295 busy = 0;
296 return 0;
300 /* Status code for main loop (reason for stack unwind) */
302 enum why_code {
303 WHY_NOT, /* No error */
304 WHY_EXCEPTION, /* Exception occurred */
305 WHY_RERAISE, /* Exception re-raised by 'finally' */
306 WHY_RETURN, /* 'return' statement */
307 WHY_BREAK /* 'break' statement */
310 static enum why_code do_raise Py_PROTO((PyObject *, PyObject *, PyObject *));
311 static int unpack_sequence Py_PROTO((PyObject *, int, PyObject **));
314 /* Backward compatible interface */
316 PyObject *
317 PyEval_EvalCode(co, globals, locals)
318 PyCodeObject *co;
319 PyObject *globals;
320 PyObject *locals;
322 return eval_code2(co,
323 globals, locals,
324 (PyObject **)NULL, 0,
325 (PyObject **)NULL, 0,
326 (PyObject **)NULL, 0,
327 (PyObject *)NULL);
331 /* Interpreter main loop */
333 #ifndef MAX_RECURSION_DEPTH
334 #define MAX_RECURSION_DEPTH 10000
335 #endif
337 static PyObject *
338 eval_code2(co, globals, locals,
339 args, argcount, kws, kwcount, defs, defcount, owner)
340 PyCodeObject *co;
341 PyObject *globals;
342 PyObject *locals;
343 PyObject **args;
344 int argcount;
345 PyObject **kws; /* length: 2*kwcount */
346 int kwcount;
347 PyObject **defs;
348 int defcount;
349 PyObject *owner;
351 #ifdef DXPAIRS
352 int lastopcode = 0;
353 #endif
354 register unsigned char *next_instr;
355 register int opcode; /* Current opcode */
356 register int oparg; /* Current opcode argument, if any */
357 register PyObject **stack_pointer;
358 register enum why_code why; /* Reason for block stack unwind */
359 register int err; /* Error status -- nonzero if error */
360 register PyObject *x; /* Result object -- NULL if error */
361 register PyObject *v; /* Temporary objects popped off stack */
362 register PyObject *w;
363 register PyObject *u;
364 register PyObject *t;
365 register PyFrameObject *f; /* Current frame */
366 register PyObject **fastlocals;
367 PyObject *retval = NULL; /* Return value */
368 PyThreadState *tstate = PyThreadState_GET();
369 unsigned char *first_instr;
370 #ifdef LLTRACE
371 int lltrace;
372 #endif
373 #if defined(Py_DEBUG) || defined(LLTRACE)
374 /* Make it easier to find out where we are with a debugger */
375 char *filename = PyString_AsString(co->co_filename);
376 #endif
378 /* Code access macros */
380 #define GETCONST(i) Getconst(f, i)
381 #define GETNAME(i) Getname(f, i)
382 #define GETNAMEV(i) Getnamev(f, i)
383 #define INSTR_OFFSET() (next_instr - first_instr)
384 #define NEXTOP() (*next_instr++)
385 #define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
386 #define JUMPTO(x) (next_instr = first_instr + (x))
387 #define JUMPBY(x) (next_instr += (x))
389 /* Stack manipulation macros */
391 #define STACK_LEVEL() (stack_pointer - f->f_valuestack)
392 #define EMPTY() (STACK_LEVEL() == 0)
393 #define TOP() (stack_pointer[-1])
394 #define BASIC_PUSH(v) (*stack_pointer++ = (v))
395 #define BASIC_POP() (*--stack_pointer)
397 #ifdef LLTRACE
398 #define PUSH(v) (BASIC_PUSH(v), lltrace && prtrace(TOP(), "push"))
399 #define POP() (lltrace && prtrace(TOP(), "pop"), BASIC_POP())
400 #else
401 #define PUSH(v) BASIC_PUSH(v)
402 #define POP() BASIC_POP()
403 #endif
405 /* Local variable macros */
407 #define GETLOCAL(i) (fastlocals[i])
408 #define SETLOCAL(i, value) do { Py_XDECREF(GETLOCAL(i)); \
409 GETLOCAL(i) = value; } while (0)
411 /* Start of code */
413 #ifdef USE_STACKCHECK
414 if (tstate->recursion_depth%10 == 0 && PyOS_CheckStack()) {
415 PyErr_SetString(PyExc_MemoryError, "Stack overflow");
416 return NULL;
418 #endif
420 if (globals == NULL) {
421 PyErr_SetString(PyExc_SystemError, "eval_code2: NULL globals");
422 return NULL;
425 #ifdef LLTRACE
426 lltrace = PyDict_GetItemString(globals, "__lltrace__") != NULL;
427 #endif
429 f = PyFrame_New(
430 tstate, /*back*/
431 co, /*code*/
432 globals, /*globals*/
433 locals); /*locals*/
434 if (f == NULL)
435 return NULL;
437 tstate->frame = f;
438 fastlocals = f->f_localsplus;
440 if (co->co_argcount > 0 ||
441 co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
442 int i;
443 int n = argcount;
444 PyObject *kwdict = NULL;
445 if (co->co_flags & CO_VARKEYWORDS) {
446 kwdict = PyDict_New();
447 if (kwdict == NULL)
448 goto fail;
449 i = co->co_argcount;
450 if (co->co_flags & CO_VARARGS)
451 i++;
452 SETLOCAL(i, kwdict);
454 if (argcount > co->co_argcount) {
455 if (!(co->co_flags & CO_VARARGS)) {
456 PyErr_Format(PyExc_TypeError,
457 "too many arguments; expected %d, got %d",
458 co->co_argcount, argcount);
459 goto fail;
461 n = co->co_argcount;
463 for (i = 0; i < n; i++) {
464 x = args[i];
465 Py_INCREF(x);
466 SETLOCAL(i, x);
468 if (co->co_flags & CO_VARARGS) {
469 u = PyTuple_New(argcount - n);
470 if (u == NULL)
471 goto fail;
472 SETLOCAL(co->co_argcount, u);
473 for (i = n; i < argcount; i++) {
474 x = args[i];
475 Py_INCREF(x);
476 PyTuple_SET_ITEM(u, i-n, x);
479 for (i = 0; i < kwcount; i++) {
480 PyObject *keyword = kws[2*i];
481 PyObject *value = kws[2*i + 1];
482 int j;
483 /* XXX slow -- speed up using dictionary? */
484 for (j = 0; j < co->co_argcount; j++) {
485 PyObject *nm = PyTuple_GET_ITEM(
486 co->co_varnames, j);
487 if (PyObject_Compare(keyword, nm) == 0)
488 break;
490 /* Check errors from Compare */
491 if (PyErr_Occurred())
492 goto fail;
493 if (j >= co->co_argcount) {
494 if (kwdict == NULL) {
495 PyErr_Format(PyExc_TypeError,
496 "unexpected keyword argument: %.400s",
497 PyString_AsString(keyword));
498 goto fail;
500 PyDict_SetItem(kwdict, keyword, value);
502 else {
503 if (GETLOCAL(j) != NULL) {
504 PyErr_SetString(PyExc_TypeError,
505 "keyword parameter redefined");
506 goto fail;
508 Py_INCREF(value);
509 SETLOCAL(j, value);
512 if (argcount < co->co_argcount) {
513 int m = co->co_argcount - defcount;
514 for (i = argcount; i < m; i++) {
515 if (GETLOCAL(i) == NULL) {
516 PyErr_Format(PyExc_TypeError,
517 "not enough arguments; expected %d, got %d",
518 m, i);
519 goto fail;
522 if (n > m)
523 i = n - m;
524 else
525 i = 0;
526 for (; i < defcount; i++) {
527 if (GETLOCAL(m+i) == NULL) {
528 PyObject *def = defs[i];
529 Py_INCREF(def);
530 SETLOCAL(m+i, def);
535 else {
536 if (argcount > 0 || kwcount > 0) {
537 PyErr_SetString(PyExc_TypeError,
538 "no arguments expected");
539 goto fail;
543 if (tstate->sys_tracefunc != NULL) {
544 /* tstate->sys_tracefunc, if defined, is a function that
545 will be called on *every* entry to a code block.
546 Its return value, if not None, is a function that
547 will be called at the start of each executed line
548 of code. (Actually, the function must return
549 itself in order to continue tracing.)
550 The trace functions are called with three arguments:
551 a pointer to the current frame, a string indicating
552 why the function is called, and an argument which
553 depends on the situation. The global trace function
554 (sys.trace) is also called whenever an exception
555 is detected. */
556 if (call_trace(&tstate->sys_tracefunc,
557 &f->f_trace, f, "call",
558 Py_None/*XXX how to compute arguments now?*/)) {
559 /* Trace function raised an error */
560 goto fail;
564 if (tstate->sys_profilefunc != NULL) {
565 /* Similar for sys_profilefunc, except it needn't return
566 itself and isn't called for "line" events */
567 if (call_trace(&tstate->sys_profilefunc,
568 (PyObject**)0, f, "call",
569 Py_None/*XXX*/)) {
570 goto fail;
574 if (++tstate->recursion_depth > MAX_RECURSION_DEPTH) {
575 --tstate->recursion_depth;
576 PyErr_SetString(PyExc_RuntimeError,
577 "Maximum recursion depth exceeded");
578 tstate->frame = f->f_back;
579 Py_DECREF(f);
580 return NULL;
583 _PyCode_GETCODEPTR(co, &first_instr);
584 next_instr = first_instr;
585 stack_pointer = f->f_valuestack;
587 why = WHY_NOT;
588 err = 0;
589 x = Py_None; /* Not a reference, just anything non-NULL */
591 for (;;) {
592 /* Do periodic things. Doing this every time through
593 the loop would add too much overhead, so we do it
594 only every Nth instruction. We also do it if
595 ``things_to_do'' is set, i.e. when an asynchronous
596 event needs attention (e.g. a signal handler or
597 async I/O handler); see Py_AddPendingCall() and
598 Py_MakePendingCalls() above. */
600 if (things_to_do || --tstate->ticker < 0) {
601 tstate->ticker = tstate->interp->checkinterval;
602 if (things_to_do) {
603 if (Py_MakePendingCalls() < 0) {
604 why = WHY_EXCEPTION;
605 goto on_error;
608 #if !defined(HAVE_SIGNAL_H) || defined(macintosh)
609 /* If we have true signals, the signal handler
610 will call Py_AddPendingCall() so we don't
611 have to call sigcheck(). On the Mac and
612 DOS, alas, we have to call it. */
613 if (PyErr_CheckSignals()) {
614 why = WHY_EXCEPTION;
615 goto on_error;
617 #endif
619 #ifdef WITH_THREAD
620 if (interpreter_lock) {
621 /* Give another thread a chance */
623 if (PyThreadState_Swap(NULL) != tstate)
624 Py_FatalError("ceval: tstate mix-up");
625 PyThread_release_lock(interpreter_lock);
627 /* Other threads may run now */
629 PyThread_acquire_lock(interpreter_lock, 1);
630 if (PyThreadState_Swap(tstate) != NULL)
631 Py_FatalError("ceval: orphan tstate");
633 #endif
636 /* Extract opcode and argument */
638 #if defined(Py_DEBUG) || defined(LLTRACE)
639 f->f_lasti = INSTR_OFFSET();
640 #endif
642 opcode = NEXTOP();
643 if (HAS_ARG(opcode))
644 oparg = NEXTARG();
645 #ifdef DYNAMIC_EXECUTION_PROFILE
646 #ifdef DXPAIRS
647 dxpairs[lastopcode][opcode]++;
648 lastopcode = opcode;
649 #endif
650 dxp[opcode]++;
651 #endif
653 #ifdef LLTRACE
654 /* Instruction tracing */
656 if (lltrace) {
657 if (HAS_ARG(opcode)) {
658 printf("%d: %d, %d\n",
659 (int) (INSTR_OFFSET() - 3),
660 opcode, oparg);
662 else {
663 printf("%d: %d\n",
664 (int) (INSTR_OFFSET() - 1), opcode);
667 #endif
669 /* Main switch on opcode */
671 switch (opcode) {
673 /* BEWARE!
674 It is essential that any operation that fails sets either
675 x to NULL, err to nonzero, or why to anything but WHY_NOT,
676 and that no operation that succeeds does this! */
678 /* case STOP_CODE: this is an error! */
680 case POP_TOP:
681 v = POP();
682 Py_DECREF(v);
683 continue;
685 case ROT_TWO:
686 v = POP();
687 w = POP();
688 PUSH(v);
689 PUSH(w);
690 continue;
692 case ROT_THREE:
693 v = POP();
694 w = POP();
695 x = POP();
696 PUSH(v);
697 PUSH(x);
698 PUSH(w);
699 continue;
701 case DUP_TOP:
702 v = TOP();
703 Py_INCREF(v);
704 PUSH(v);
705 continue;
707 case UNARY_POSITIVE:
708 v = POP();
709 x = PyNumber_Positive(v);
710 Py_DECREF(v);
711 PUSH(x);
712 if (x != NULL) continue;
713 break;
715 case UNARY_NEGATIVE:
716 v = POP();
717 x = PyNumber_Negative(v);
718 Py_DECREF(v);
719 PUSH(x);
720 if (x != NULL) continue;
721 break;
723 case UNARY_NOT:
724 v = POP();
725 err = PyObject_IsTrue(v);
726 Py_DECREF(v);
727 if (err == 0) {
728 Py_INCREF(Py_True);
729 PUSH(Py_True);
730 continue;
732 else if (err > 0) {
733 Py_INCREF(Py_False);
734 PUSH(Py_False);
735 err = 0;
736 continue;
738 break;
740 case UNARY_CONVERT:
741 v = POP();
742 x = PyObject_Repr(v);
743 Py_DECREF(v);
744 PUSH(x);
745 if (x != NULL) continue;
746 break;
748 case UNARY_INVERT:
749 v = POP();
750 x = PyNumber_Invert(v);
751 Py_DECREF(v);
752 PUSH(x);
753 if (x != NULL) continue;
754 break;
756 case BINARY_POWER:
757 w = POP();
758 v = POP();
759 x = PyNumber_Power(v, w, Py_None);
760 Py_DECREF(v);
761 Py_DECREF(w);
762 PUSH(x);
763 if (x != NULL) continue;
764 break;
766 case BINARY_MULTIPLY:
767 w = POP();
768 v = POP();
769 x = PyNumber_Multiply(v, w);
770 Py_DECREF(v);
771 Py_DECREF(w);
772 PUSH(x);
773 if (x != NULL) continue;
774 break;
776 case BINARY_DIVIDE:
777 w = POP();
778 v = POP();
779 x = PyNumber_Divide(v, w);
780 Py_DECREF(v);
781 Py_DECREF(w);
782 PUSH(x);
783 if (x != NULL) continue;
784 break;
786 case BINARY_MODULO:
787 w = POP();
788 v = POP();
789 x = PyNumber_Remainder(v, w);
790 Py_DECREF(v);
791 Py_DECREF(w);
792 PUSH(x);
793 if (x != NULL) continue;
794 break;
796 case BINARY_ADD:
797 w = POP();
798 v = POP();
799 if (PyInt_Check(v) && PyInt_Check(w)) {
800 /* INLINE: int + int */
801 register long a, b, i;
802 a = PyInt_AS_LONG(v);
803 b = PyInt_AS_LONG(w);
804 i = a + b;
805 if ((i^a) < 0 && (i^b) < 0) {
806 PyErr_SetString(PyExc_OverflowError,
807 "integer addition");
808 x = NULL;
810 else
811 x = PyInt_FromLong(i);
813 else
814 x = PyNumber_Add(v, w);
815 Py_DECREF(v);
816 Py_DECREF(w);
817 PUSH(x);
818 if (x != NULL) continue;
819 break;
821 case BINARY_SUBTRACT:
822 w = POP();
823 v = POP();
824 if (PyInt_Check(v) && PyInt_Check(w)) {
825 /* INLINE: int - int */
826 register long a, b, i;
827 a = PyInt_AS_LONG(v);
828 b = PyInt_AS_LONG(w);
829 i = a - b;
830 if ((i^a) < 0 && (i^~b) < 0) {
831 PyErr_SetString(PyExc_OverflowError,
832 "integer subtraction");
833 x = NULL;
835 else
836 x = PyInt_FromLong(i);
838 else
839 x = PyNumber_Subtract(v, w);
840 Py_DECREF(v);
841 Py_DECREF(w);
842 PUSH(x);
843 if (x != NULL) continue;
844 break;
846 case BINARY_SUBSCR:
847 w = POP();
848 v = POP();
849 if (PyList_Check(v) && PyInt_Check(w)) {
850 /* INLINE: list[int] */
851 long i = PyInt_AsLong(w);
852 if (i < 0)
853 i += PyList_GET_SIZE(v);
854 if (i < 0 ||
855 i >= PyList_GET_SIZE(v)) {
856 PyErr_SetString(PyExc_IndexError,
857 "list index out of range");
858 x = NULL;
860 else {
861 x = PyList_GET_ITEM(v, i);
862 Py_INCREF(x);
865 else
866 x = PyObject_GetItem(v, w);
867 Py_DECREF(v);
868 Py_DECREF(w);
869 PUSH(x);
870 if (x != NULL) continue;
871 break;
873 case BINARY_LSHIFT:
874 w = POP();
875 v = POP();
876 x = PyNumber_Lshift(v, w);
877 Py_DECREF(v);
878 Py_DECREF(w);
879 PUSH(x);
880 if (x != NULL) continue;
881 break;
883 case BINARY_RSHIFT:
884 w = POP();
885 v = POP();
886 x = PyNumber_Rshift(v, w);
887 Py_DECREF(v);
888 Py_DECREF(w);
889 PUSH(x);
890 if (x != NULL) continue;
891 break;
893 case BINARY_AND:
894 w = POP();
895 v = POP();
896 x = PyNumber_And(v, w);
897 Py_DECREF(v);
898 Py_DECREF(w);
899 PUSH(x);
900 if (x != NULL) continue;
901 break;
903 case BINARY_XOR:
904 w = POP();
905 v = POP();
906 x = PyNumber_Xor(v, w);
907 Py_DECREF(v);
908 Py_DECREF(w);
909 PUSH(x);
910 if (x != NULL) continue;
911 break;
913 case BINARY_OR:
914 w = POP();
915 v = POP();
916 x = PyNumber_Or(v, w);
917 Py_DECREF(v);
918 Py_DECREF(w);
919 PUSH(x);
920 if (x != NULL) continue;
921 break;
923 case SLICE+0:
924 case SLICE+1:
925 case SLICE+2:
926 case SLICE+3:
927 if ((opcode-SLICE) & 2)
928 w = POP();
929 else
930 w = NULL;
931 if ((opcode-SLICE) & 1)
932 v = POP();
933 else
934 v = NULL;
935 u = POP();
936 x = apply_slice(u, v, w);
937 Py_DECREF(u);
938 Py_XDECREF(v);
939 Py_XDECREF(w);
940 PUSH(x);
941 if (x != NULL) continue;
942 break;
944 case STORE_SLICE+0:
945 case STORE_SLICE+1:
946 case STORE_SLICE+2:
947 case STORE_SLICE+3:
948 if ((opcode-STORE_SLICE) & 2)
949 w = POP();
950 else
951 w = NULL;
952 if ((opcode-STORE_SLICE) & 1)
953 v = POP();
954 else
955 v = NULL;
956 u = POP();
957 t = POP();
958 err = assign_slice(u, v, w, t); /* u[v:w] = t */
959 Py_DECREF(t);
960 Py_DECREF(u);
961 Py_XDECREF(v);
962 Py_XDECREF(w);
963 if (err == 0) continue;
964 break;
966 case DELETE_SLICE+0:
967 case DELETE_SLICE+1:
968 case DELETE_SLICE+2:
969 case DELETE_SLICE+3:
970 if ((opcode-DELETE_SLICE) & 2)
971 w = POP();
972 else
973 w = NULL;
974 if ((opcode-DELETE_SLICE) & 1)
975 v = POP();
976 else
977 v = NULL;
978 u = POP();
979 err = assign_slice(u, v, w, (PyObject *)NULL);
980 /* del u[v:w] */
981 Py_DECREF(u);
982 Py_XDECREF(v);
983 Py_XDECREF(w);
984 if (err == 0) continue;
985 break;
987 case STORE_SUBSCR:
988 w = POP();
989 v = POP();
990 u = POP();
991 /* v[w] = u */
992 err = PyObject_SetItem(v, w, u);
993 Py_DECREF(u);
994 Py_DECREF(v);
995 Py_DECREF(w);
996 if (err == 0) continue;
997 break;
999 case DELETE_SUBSCR:
1000 w = POP();
1001 v = POP();
1002 /* del v[w] */
1003 err = PyObject_DelItem(v, w);
1004 Py_DECREF(v);
1005 Py_DECREF(w);
1006 if (err == 0) continue;
1007 break;
1009 case PRINT_EXPR:
1010 v = POP();
1011 /* Print value except if None */
1012 /* After printing, also assign to '_' */
1013 /* Before, set '_' to None to avoid recursion */
1014 if (v != Py_None &&
1015 (err = PyDict_SetItemString(
1016 f->f_builtins, "_", Py_None)) == 0) {
1017 err = Py_FlushLine();
1018 if (err == 0) {
1019 x = PySys_GetObject("stdout");
1020 if (x == NULL) {
1021 PyErr_SetString(
1022 PyExc_RuntimeError,
1023 "lost sys.stdout");
1024 err = -1;
1027 if (err == 0)
1028 err = PyFile_WriteObject(v, x, 0);
1029 if (err == 0) {
1030 PyFile_SoftSpace(x, 1);
1031 err = Py_FlushLine();
1033 if (err == 0) {
1034 err = PyDict_SetItemString(
1035 f->f_builtins, "_", v);
1038 Py_DECREF(v);
1039 break;
1041 case PRINT_ITEM:
1042 v = POP();
1043 w = PySys_GetObject("stdout");
1044 if (w == NULL) {
1045 PyErr_SetString(PyExc_RuntimeError,
1046 "lost sys.stdout");
1047 err = -1;
1049 else if (PyFile_SoftSpace(w, 1))
1050 err = PyFile_WriteString(" ", w);
1051 if (err == 0)
1052 err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
1053 if (err == 0 && PyString_Check(v)) {
1054 /* XXX move into writeobject() ? */
1055 char *s = PyString_AsString(v);
1056 int len = PyString_Size(v);
1057 if (len > 0 &&
1058 isspace(Py_CHARMASK(s[len-1])) &&
1059 s[len-1] != ' ')
1060 PyFile_SoftSpace(w, 0);
1062 Py_DECREF(v);
1063 if (err == 0) continue;
1064 break;
1066 case PRINT_NEWLINE:
1067 x = PySys_GetObject("stdout");
1068 if (x == NULL)
1069 PyErr_SetString(PyExc_RuntimeError,
1070 "lost sys.stdout");
1071 else {
1072 err = PyFile_WriteString("\n", x);
1073 if (err == 0)
1074 PyFile_SoftSpace(x, 0);
1076 break;
1078 case BREAK_LOOP:
1079 why = WHY_BREAK;
1080 break;
1082 case RAISE_VARARGS:
1083 u = v = w = NULL;
1084 switch (oparg) {
1085 case 3:
1086 u = POP(); /* traceback */
1087 /* Fallthrough */
1088 case 2:
1089 v = POP(); /* value */
1090 /* Fallthrough */
1091 case 1:
1092 w = POP(); /* exc */
1093 case 0: /* Fallthrough */
1094 why = do_raise(w, v, u);
1095 break;
1096 default:
1097 PyErr_SetString(PyExc_SystemError,
1098 "bad RAISE_VARARGS oparg");
1099 why = WHY_EXCEPTION;
1100 break;
1102 break;
1104 case LOAD_LOCALS:
1105 if ((x = f->f_locals) == NULL) {
1106 PyErr_SetString(PyExc_SystemError,
1107 "no locals");
1108 break;
1110 Py_INCREF(x);
1111 PUSH(x);
1112 break;
1114 case RETURN_VALUE:
1115 retval = POP();
1116 why = WHY_RETURN;
1117 break;
1119 case EXEC_STMT:
1120 w = POP();
1121 v = POP();
1122 u = POP();
1123 err = exec_statement(f, u, v, w);
1124 Py_DECREF(u);
1125 Py_DECREF(v);
1126 Py_DECREF(w);
1127 break;
1129 case POP_BLOCK:
1131 PyTryBlock *b = PyFrame_BlockPop(f);
1132 while (STACK_LEVEL() > b->b_level) {
1133 v = POP();
1134 Py_DECREF(v);
1137 break;
1139 case END_FINALLY:
1140 v = POP();
1141 if (PyInt_Check(v)) {
1142 why = (enum why_code) PyInt_AsLong(v);
1143 if (why == WHY_RETURN)
1144 retval = POP();
1146 else if (PyString_Check(v) || PyClass_Check(v)) {
1147 w = POP();
1148 u = POP();
1149 PyErr_Restore(v, w, u);
1150 why = WHY_RERAISE;
1151 break;
1153 else if (v != Py_None) {
1154 PyErr_SetString(PyExc_SystemError,
1155 "'finally' pops bad exception");
1156 why = WHY_EXCEPTION;
1158 Py_DECREF(v);
1159 break;
1161 case BUILD_CLASS:
1162 u = POP();
1163 v = POP();
1164 w = POP();
1165 x = build_class(u, v, w);
1166 PUSH(x);
1167 Py_DECREF(u);
1168 Py_DECREF(v);
1169 Py_DECREF(w);
1170 break;
1172 case STORE_NAME:
1173 w = GETNAMEV(oparg);
1174 v = POP();
1175 if ((x = f->f_locals) == NULL) {
1176 PyErr_SetString(PyExc_SystemError,
1177 "no locals");
1178 break;
1180 err = PyDict_SetItem(x, w, v);
1181 Py_DECREF(v);
1182 break;
1184 case DELETE_NAME:
1185 w = GETNAMEV(oparg);
1186 if ((x = f->f_locals) == NULL) {
1187 PyErr_SetString(PyExc_SystemError,
1188 "no locals");
1189 break;
1191 if ((err = PyDict_DelItem(x, w)) != 0)
1192 PyErr_SetObject(PyExc_NameError, w);
1193 break;
1195 #ifdef CASE_TOO_BIG
1196 default: switch (opcode) {
1197 #endif
1199 case UNPACK_TUPLE:
1200 case UNPACK_LIST:
1201 v = POP();
1202 if (PyTuple_Check(v)) {
1203 if (PyTuple_Size(v) != oparg) {
1204 PyErr_SetString(PyExc_ValueError,
1205 "unpack tuple of wrong size");
1206 why = WHY_EXCEPTION;
1208 else {
1209 for (; --oparg >= 0; ) {
1210 w = PyTuple_GET_ITEM(v, oparg);
1211 Py_INCREF(w);
1212 PUSH(w);
1216 else if (PyList_Check(v)) {
1217 if (PyList_Size(v) != oparg) {
1218 PyErr_SetString(PyExc_ValueError,
1219 "unpack list of wrong size");
1220 why = WHY_EXCEPTION;
1222 else {
1223 for (; --oparg >= 0; ) {
1224 w = PyList_GET_ITEM(v, oparg);
1225 Py_INCREF(w);
1226 PUSH(w);
1230 else if (PySequence_Check(v)) {
1231 if (unpack_sequence(v, oparg,
1232 stack_pointer + oparg))
1233 stack_pointer += oparg;
1234 else
1235 why = WHY_EXCEPTION;
1237 else {
1238 PyErr_SetString(PyExc_TypeError,
1239 "unpack non-sequence");
1240 why = WHY_EXCEPTION;
1242 Py_DECREF(v);
1243 break;
1245 case STORE_ATTR:
1246 w = GETNAMEV(oparg);
1247 v = POP();
1248 u = POP();
1249 err = PyObject_SetAttr(v, w, u); /* v.w = u */
1250 Py_DECREF(v);
1251 Py_DECREF(u);
1252 break;
1254 case DELETE_ATTR:
1255 w = GETNAMEV(oparg);
1256 v = POP();
1257 err = PyObject_SetAttr(v, w, (PyObject *)NULL);
1258 /* del v.w */
1259 Py_DECREF(v);
1260 break;
1262 case STORE_GLOBAL:
1263 w = GETNAMEV(oparg);
1264 v = POP();
1265 err = PyDict_SetItem(f->f_globals, w, v);
1266 Py_DECREF(v);
1267 break;
1269 case DELETE_GLOBAL:
1270 w = GETNAMEV(oparg);
1271 if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
1272 PyErr_SetObject(PyExc_NameError, w);
1273 break;
1275 case LOAD_CONST:
1276 x = GETCONST(oparg);
1277 Py_INCREF(x);
1278 PUSH(x);
1279 break;
1281 case LOAD_NAME:
1282 w = GETNAMEV(oparg);
1283 if ((x = f->f_locals) == NULL) {
1284 PyErr_SetString(PyExc_SystemError,
1285 "no locals");
1286 break;
1288 x = PyDict_GetItem(x, w);
1289 if (x == NULL) {
1290 x = PyDict_GetItem(f->f_globals, w);
1291 if (x == NULL) {
1292 x = PyDict_GetItem(f->f_builtins, w);
1293 if (x == NULL) {
1294 PyErr_SetObject(
1295 PyExc_NameError, w);
1296 break;
1300 Py_INCREF(x);
1301 PUSH(x);
1302 break;
1304 case LOAD_GLOBAL:
1305 w = GETNAMEV(oparg);
1306 x = PyDict_GetItem(f->f_globals, w);
1307 if (x == NULL) {
1308 x = PyDict_GetItem(f->f_builtins, w);
1309 if (x == NULL) {
1310 PyErr_SetObject(PyExc_NameError, w);
1311 break;
1314 Py_INCREF(x);
1315 PUSH(x);
1316 break;
1318 case LOAD_FAST:
1319 x = GETLOCAL(oparg);
1320 if (x == NULL) {
1321 PyErr_SetObject(PyExc_NameError,
1322 PyTuple_GetItem(co->co_varnames,
1323 oparg));
1324 break;
1326 Py_INCREF(x);
1327 PUSH(x);
1328 if (x != NULL) continue;
1329 break;
1331 case STORE_FAST:
1332 v = POP();
1333 SETLOCAL(oparg, v);
1334 continue;
1336 case DELETE_FAST:
1337 x = GETLOCAL(oparg);
1338 if (x == NULL) {
1339 PyErr_SetObject(PyExc_NameError,
1340 PyTuple_GetItem(co->co_varnames,
1341 oparg));
1342 break;
1344 SETLOCAL(oparg, NULL);
1345 continue;
1347 case BUILD_TUPLE:
1348 x = PyTuple_New(oparg);
1349 if (x != NULL) {
1350 for (; --oparg >= 0;) {
1351 w = POP();
1352 PyTuple_SET_ITEM(x, oparg, w);
1354 PUSH(x);
1355 continue;
1357 break;
1359 case BUILD_LIST:
1360 x = PyList_New(oparg);
1361 if (x != NULL) {
1362 for (; --oparg >= 0;) {
1363 w = POP();
1364 PyList_SET_ITEM(x, oparg, w);
1366 PUSH(x);
1367 continue;
1369 break;
1371 case BUILD_MAP:
1372 x = PyDict_New();
1373 PUSH(x);
1374 if (x != NULL) continue;
1375 break;
1377 case LOAD_ATTR:
1378 w = GETNAMEV(oparg);
1379 v = POP();
1380 x = PyObject_GetAttr(v, w);
1381 Py_DECREF(v);
1382 PUSH(x);
1383 if (x != NULL) continue;
1384 break;
1386 case COMPARE_OP:
1387 w = POP();
1388 v = POP();
1389 if (PyInt_Check(v) && PyInt_Check(w)) {
1390 /* INLINE: cmp(int, int) */
1391 register long a, b;
1392 register int res;
1393 a = PyInt_AS_LONG(v);
1394 b = PyInt_AS_LONG(w);
1395 switch (oparg) {
1396 case LT: res = a < b; break;
1397 case LE: res = a <= b; break;
1398 case EQ: res = a == b; break;
1399 case NE: res = a != b; break;
1400 case GT: res = a > b; break;
1401 case GE: res = a >= b; break;
1402 case IS: res = v == w; break;
1403 case IS_NOT: res = v != w; break;
1404 default: goto slow_compare;
1406 x = res ? Py_True : Py_False;
1407 Py_INCREF(x);
1409 else {
1410 slow_compare:
1411 x = cmp_outcome(oparg, v, w);
1413 Py_DECREF(v);
1414 Py_DECREF(w);
1415 PUSH(x);
1416 if (x != NULL) continue;
1417 break;
1419 case IMPORT_NAME:
1420 w = GETNAMEV(oparg);
1421 x = PyDict_GetItemString(f->f_builtins, "__import__");
1422 if (x == NULL) {
1423 PyErr_SetString(PyExc_ImportError,
1424 "__import__ not found");
1425 break;
1427 u = find_from_args(f, INSTR_OFFSET());
1428 if (u == NULL) {
1429 x = u;
1430 break;
1432 w = Py_BuildValue("(OOOO)",
1434 f->f_globals,
1435 f->f_locals == NULL ?
1436 Py_None : f->f_locals,
1438 Py_DECREF(u);
1439 if (w == NULL) {
1440 x = NULL;
1441 break;
1443 x = PyEval_CallObject(x, w);
1444 Py_DECREF(w);
1445 PUSH(x);
1446 if (x != NULL) continue;
1447 break;
1449 case IMPORT_FROM:
1450 w = GETNAMEV(oparg);
1451 v = TOP();
1452 PyFrame_FastToLocals(f);
1453 if ((x = f->f_locals) == NULL) {
1454 PyErr_SetString(PyExc_SystemError,
1455 "no locals");
1456 break;
1458 err = import_from(x, v, w);
1459 PyFrame_LocalsToFast(f, 0);
1460 if (err == 0) continue;
1461 break;
1463 case JUMP_FORWARD:
1464 JUMPBY(oparg);
1465 continue;
1467 case JUMP_IF_FALSE:
1468 err = PyObject_IsTrue(TOP());
1469 if (err > 0)
1470 err = 0;
1471 else if (err == 0)
1472 JUMPBY(oparg);
1473 else
1474 break;
1475 continue;
1477 case JUMP_IF_TRUE:
1478 err = PyObject_IsTrue(TOP());
1479 if (err > 0) {
1480 err = 0;
1481 JUMPBY(oparg);
1483 else if (err == 0)
1485 else
1486 break;
1487 continue;
1489 case JUMP_ABSOLUTE:
1490 JUMPTO(oparg);
1491 continue;
1493 case FOR_LOOP:
1494 /* for v in s: ...
1495 On entry: stack contains s, i.
1496 On exit: stack contains s, i+1, s[i];
1497 but if loop exhausted:
1498 s, i are popped, and we jump */
1499 w = POP(); /* Loop index */
1500 v = POP(); /* Sequence object */
1501 u = loop_subscript(v, w);
1502 if (u != NULL) {
1503 PUSH(v);
1504 x = PyInt_FromLong(PyInt_AsLong(w)+1);
1505 PUSH(x);
1506 Py_DECREF(w);
1507 PUSH(u);
1508 if (x != NULL) continue;
1510 else {
1511 Py_DECREF(v);
1512 Py_DECREF(w);
1513 /* A NULL can mean "s exhausted"
1514 but also an error: */
1515 if (PyErr_Occurred())
1516 why = WHY_EXCEPTION;
1517 else {
1518 JUMPBY(oparg);
1519 continue;
1522 break;
1524 case SETUP_LOOP:
1525 case SETUP_EXCEPT:
1526 case SETUP_FINALLY:
1527 PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
1528 STACK_LEVEL());
1529 continue;
1531 case SET_LINENO:
1532 #ifdef LLTRACE
1533 if (lltrace)
1534 printf("--- %s:%d \n", filename, oparg);
1535 #endif
1536 f->f_lineno = oparg;
1537 if (f->f_trace == NULL)
1538 continue;
1539 /* Trace each line of code reached */
1540 f->f_lasti = INSTR_OFFSET();
1541 err = call_trace(&f->f_trace, &f->f_trace,
1542 f, "line", Py_None);
1543 break;
1545 case CALL_FUNCTION:
1547 int na = oparg & 0xff;
1548 int nk = (oparg>>8) & 0xff;
1549 int n = na + 2*nk;
1550 PyObject **pfunc = stack_pointer - n - 1;
1551 PyObject *func = *pfunc;
1552 PyObject *self = NULL;
1553 PyObject *class = NULL;
1554 f->f_lasti = INSTR_OFFSET() - 3; /* For tracing */
1555 if (PyMethod_Check(func)) {
1556 self = PyMethod_Self(func);
1557 class = PyMethod_Class(func);
1558 func = PyMethod_Function(func);
1559 Py_INCREF(func);
1560 if (self != NULL) {
1561 Py_INCREF(self);
1562 Py_DECREF(*pfunc);
1563 *pfunc = self;
1564 na++;
1565 n++;
1567 else {
1568 /* Unbound methods must be
1569 called with an instance of
1570 the class (or a derived
1571 class) as first argument */
1572 if (na > 0 &&
1573 (self = stack_pointer[-n])
1574 != NULL &&
1575 PyInstance_Check(self) &&
1576 PyClass_IsSubclass(
1577 (PyObject *)
1578 (((PyInstanceObject *)self)
1579 ->in_class),
1580 class))
1581 /* Handy-dandy */ ;
1582 else {
1583 PyErr_SetString(
1584 PyExc_TypeError,
1585 "unbound method must be called with class instance 1st argument");
1586 x = NULL;
1587 break;
1591 else
1592 Py_INCREF(func);
1593 if (PyFunction_Check(func)) {
1594 PyObject *co = PyFunction_GetCode(func);
1595 PyObject *globals =
1596 PyFunction_GetGlobals(func);
1597 PyObject *argdefs =
1598 PyFunction_GetDefaults(func);
1599 PyObject **d;
1600 int nd;
1601 if (argdefs != NULL) {
1602 d = &PyTuple_GET_ITEM(argdefs, 0);
1603 nd = ((PyTupleObject *)argdefs) ->
1604 ob_size;
1606 else {
1607 d = NULL;
1608 nd = 0;
1610 x = eval_code2(
1611 (PyCodeObject *)co,
1612 globals, (PyObject *)NULL,
1613 stack_pointer-n, na,
1614 stack_pointer-2*nk, nk,
1615 d, nd,
1616 class);
1618 else {
1619 PyObject *args = PyTuple_New(na);
1620 PyObject *kwdict = NULL;
1621 if (args == NULL) {
1622 x = NULL;
1623 break;
1625 if (nk > 0) {
1626 kwdict = PyDict_New();
1627 if (kwdict == NULL) {
1628 x = NULL;
1629 break;
1631 err = 0;
1632 while (--nk >= 0) {
1633 PyObject *value = POP();
1634 PyObject *key = POP();
1635 err = PyDict_SetItem(
1636 kwdict, key, value);
1637 Py_DECREF(key);
1638 Py_DECREF(value);
1639 if (err)
1640 break;
1642 if (err) {
1643 Py_DECREF(args);
1644 Py_DECREF(kwdict);
1645 break;
1648 while (--na >= 0) {
1649 w = POP();
1650 PyTuple_SET_ITEM(args, na, w);
1652 x = PyEval_CallObjectWithKeywords(
1653 func, args, kwdict);
1654 Py_DECREF(args);
1655 Py_XDECREF(kwdict);
1657 Py_DECREF(func);
1658 while (stack_pointer > pfunc) {
1659 w = POP();
1660 Py_DECREF(w);
1662 PUSH(x);
1663 if (x != NULL) continue;
1664 break;
1667 case MAKE_FUNCTION:
1668 v = POP(); /* code object */
1669 x = PyFunction_New(v, f->f_globals);
1670 Py_DECREF(v);
1671 /* XXX Maybe this should be a separate opcode? */
1672 if (x != NULL && oparg > 0) {
1673 v = PyTuple_New(oparg);
1674 if (v == NULL) {
1675 Py_DECREF(x);
1676 x = NULL;
1677 break;
1679 while (--oparg >= 0) {
1680 w = POP();
1681 PyTuple_SET_ITEM(v, oparg, w);
1683 err = PyFunction_SetDefaults(x, v);
1684 Py_DECREF(v);
1686 PUSH(x);
1687 break;
1689 case BUILD_SLICE:
1690 if (oparg == 3)
1691 w = POP();
1692 else
1693 w = NULL;
1694 v = POP();
1695 u = POP();
1696 x = PySlice_New(u, v, w);
1697 Py_DECREF(u);
1698 Py_DECREF(v);
1699 Py_XDECREF(w);
1700 PUSH(x);
1701 if (x != NULL) continue;
1702 break;
1705 default:
1706 fprintf(stderr,
1707 "XXX lineno: %d, opcode: %d\n",
1708 f->f_lineno, opcode);
1709 PyErr_SetString(PyExc_SystemError, "unknown opcode");
1710 why = WHY_EXCEPTION;
1711 break;
1713 #ifdef CASE_TOO_BIG
1715 #endif
1717 } /* switch */
1719 on_error:
1721 /* Quickly continue if no error occurred */
1723 if (why == WHY_NOT) {
1724 if (err == 0 && x != NULL) {
1725 #ifdef CHECKEXC
1726 if (PyErr_Occurred())
1727 fprintf(stderr,
1728 "XXX undetected error\n");
1729 else
1730 #endif
1731 continue; /* Normal, fast path */
1733 why = WHY_EXCEPTION;
1734 x = Py_None;
1735 err = 0;
1738 #ifdef CHECKEXC
1739 /* Double-check exception status */
1741 if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
1742 if (!PyErr_Occurred()) {
1743 fprintf(stderr, "XXX ghost error\n");
1744 PyErr_SetString(PyExc_SystemError,
1745 "ghost error");
1746 why = WHY_EXCEPTION;
1749 else {
1750 if (PyErr_Occurred()) {
1751 fprintf(stderr,
1752 "XXX undetected error (why=%d)\n",
1753 why);
1754 why = WHY_EXCEPTION;
1757 #endif
1759 /* Log traceback info if this is a real exception */
1761 if (why == WHY_EXCEPTION) {
1762 f->f_lasti = INSTR_OFFSET() - 1;
1763 if (HAS_ARG(opcode))
1764 f->f_lasti -= 2;
1765 PyTraceBack_Here(f);
1767 if (f->f_trace)
1768 call_exc_trace(&f->f_trace, &f->f_trace, f);
1769 if (tstate->sys_profilefunc)
1770 call_exc_trace(&tstate->sys_profilefunc,
1771 (PyObject**)0, f);
1774 /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
1776 if (why == WHY_RERAISE)
1777 why = WHY_EXCEPTION;
1779 /* Unwind stacks if a (pseudo) exception occurred */
1781 while (why != WHY_NOT && f->f_iblock > 0) {
1782 PyTryBlock *b = PyFrame_BlockPop(f);
1783 while (STACK_LEVEL() > b->b_level) {
1784 v = POP();
1785 Py_XDECREF(v);
1787 if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
1788 why = WHY_NOT;
1789 JUMPTO(b->b_handler);
1790 break;
1792 if (b->b_type == SETUP_FINALLY ||
1793 (b->b_type == SETUP_EXCEPT &&
1794 why == WHY_EXCEPTION)) {
1795 if (why == WHY_EXCEPTION) {
1796 PyObject *exc, *val, *tb;
1797 PyErr_Fetch(&exc, &val, &tb);
1798 if (val == NULL) {
1799 val = Py_None;
1800 Py_INCREF(val);
1802 /* Make the raw exception data
1803 available to the handler,
1804 so a program can emulate the
1805 Python main loop. Don't do
1806 this for 'finally'. */
1807 if (b->b_type == SETUP_EXCEPT) {
1808 PyErr_NormalizeException(
1809 &exc, &val, &tb);
1810 set_exc_info(tstate,
1811 exc, val, tb);
1813 PUSH(tb);
1814 PUSH(val);
1815 PUSH(exc);
1817 else {
1818 if (why == WHY_RETURN)
1819 PUSH(retval);
1820 v = PyInt_FromLong((long)why);
1821 PUSH(v);
1823 why = WHY_NOT;
1824 JUMPTO(b->b_handler);
1825 break;
1827 } /* unwind stack */
1829 /* End the loop if we still have an error (or return) */
1831 if (why != WHY_NOT)
1832 break;
1834 } /* main loop */
1836 /* Pop remaining stack entries */
1838 while (!EMPTY()) {
1839 v = POP();
1840 Py_XDECREF(v);
1843 if (why != WHY_RETURN)
1844 retval = NULL;
1846 if (f->f_trace) {
1847 if (why == WHY_RETURN) {
1848 if (call_trace(&f->f_trace, &f->f_trace, f,
1849 "return", retval)) {
1850 Py_XDECREF(retval);
1851 retval = NULL;
1852 why = WHY_EXCEPTION;
1857 if (tstate->sys_profilefunc && why == WHY_RETURN) {
1858 if (call_trace(&tstate->sys_profilefunc, (PyObject**)0,
1859 f, "return", retval)) {
1860 Py_XDECREF(retval);
1861 retval = NULL;
1862 why = WHY_EXCEPTION;
1866 reset_exc_info(tstate);
1868 --tstate->recursion_depth;
1870 fail: /* Jump here from prelude on failure */
1872 /* Restore previous frame and release the current one */
1874 tstate->frame = f->f_back;
1875 Py_DECREF(f);
1877 return retval;
1880 static void
1881 set_exc_info(tstate, type, value, tb)
1882 PyThreadState *tstate;
1883 PyObject *type;
1884 PyObject *value;
1885 PyObject *tb;
1887 PyFrameObject *frame;
1888 PyObject *tmp_type, *tmp_value, *tmp_tb;
1890 frame = tstate->frame;
1891 if (frame->f_exc_type == NULL) {
1892 /* This frame didn't catch an exception before */
1893 /* Save previous exception of this thread in this frame */
1894 if (tstate->exc_type == NULL) {
1895 Py_INCREF(Py_None);
1896 tstate->exc_type = Py_None;
1898 tmp_type = frame->f_exc_type;
1899 tmp_value = frame->f_exc_value;
1900 tmp_tb = frame->f_exc_traceback;
1901 Py_XINCREF(tstate->exc_type);
1902 Py_XINCREF(tstate->exc_value);
1903 Py_XINCREF(tstate->exc_traceback);
1904 frame->f_exc_type = tstate->exc_type;
1905 frame->f_exc_value = tstate->exc_value;
1906 frame->f_exc_traceback = tstate->exc_traceback;
1907 Py_XDECREF(tmp_type);
1908 Py_XDECREF(tmp_value);
1909 Py_XDECREF(tmp_tb);
1911 /* Set new exception for this thread */
1912 tmp_type = tstate->exc_type;
1913 tmp_value = tstate->exc_value;
1914 tmp_tb = tstate->exc_traceback;
1915 Py_XINCREF(type);
1916 Py_XINCREF(value);
1917 Py_XINCREF(tb);
1918 tstate->exc_type = type;
1919 tstate->exc_value = value;
1920 tstate->exc_traceback = tb;
1921 Py_XDECREF(tmp_type);
1922 Py_XDECREF(tmp_value);
1923 Py_XDECREF(tmp_tb);
1924 /* For b/w compatibility */
1925 PySys_SetObject("exc_type", type);
1926 PySys_SetObject("exc_value", value);
1927 PySys_SetObject("exc_traceback", tb);
1930 static void
1931 reset_exc_info(tstate)
1932 PyThreadState *tstate;
1934 PyFrameObject *frame;
1935 PyObject *tmp_type, *tmp_value, *tmp_tb;
1936 frame = tstate->frame;
1937 if (frame->f_exc_type != NULL) {
1938 /* This frame caught an exception */
1939 tmp_type = tstate->exc_type;
1940 tmp_value = tstate->exc_value;
1941 tmp_tb = tstate->exc_traceback;
1942 Py_XINCREF(frame->f_exc_type);
1943 Py_XINCREF(frame->f_exc_value);
1944 Py_XINCREF(frame->f_exc_traceback);
1945 tstate->exc_type = frame->f_exc_type;
1946 tstate->exc_value = frame->f_exc_value;
1947 tstate->exc_traceback = frame->f_exc_traceback;
1948 Py_XDECREF(tmp_type);
1949 Py_XDECREF(tmp_value);
1950 Py_XDECREF(tmp_tb);
1951 /* For b/w compatibility */
1952 PySys_SetObject("exc_type", frame->f_exc_type);
1953 PySys_SetObject("exc_value", frame->f_exc_value);
1954 PySys_SetObject("exc_traceback", frame->f_exc_traceback);
1956 tmp_type = frame->f_exc_type;
1957 tmp_value = frame->f_exc_value;
1958 tmp_tb = frame->f_exc_traceback;
1959 frame->f_exc_type = NULL;
1960 frame->f_exc_value = NULL;
1961 frame->f_exc_traceback = NULL;
1962 Py_XDECREF(tmp_type);
1963 Py_XDECREF(tmp_value);
1964 Py_XDECREF(tmp_tb);
1967 /* Logic for the raise statement (too complicated for inlining).
1968 This *consumes* a reference count to each of its arguments. */
1969 static enum why_code
1970 do_raise(type, value, tb)
1971 PyObject *type, *value, *tb;
1973 if (type == NULL) {
1974 /* Reraise */
1975 PyThreadState *tstate = PyThreadState_Get();
1976 type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
1977 value = tstate->exc_value;
1978 tb = tstate->exc_traceback;
1979 Py_XINCREF(type);
1980 Py_XINCREF(value);
1981 Py_XINCREF(tb);
1984 /* We support the following forms of raise:
1985 raise <class>, <classinstance>
1986 raise <class>, <argument tuple>
1987 raise <class>, None
1988 raise <class>, <argument>
1989 raise <classinstance>, None
1990 raise <string>, <object>
1991 raise <string>, None
1993 An omitted second argument is the same as None.
1995 In addition, raise <tuple>, <anything> is the same as
1996 raising the tuple's first item (and it better have one!);
1997 this rule is applied recursively.
1999 Finally, an optional third argument can be supplied, which
2000 gives the traceback to be substituted (useful when
2001 re-raising an exception after examining it). */
2003 /* First, check the traceback argument, replacing None with
2004 NULL. */
2005 if (tb == Py_None) {
2006 Py_DECREF(tb);
2007 tb = NULL;
2009 else if (tb != NULL && !PyTraceBack_Check(tb)) {
2010 PyErr_SetString(PyExc_TypeError,
2011 "raise 3rd arg must be traceback or None");
2012 goto raise_error;
2015 /* Next, replace a missing value with None */
2016 if (value == NULL) {
2017 value = Py_None;
2018 Py_INCREF(value);
2021 /* Next, repeatedly, replace a tuple exception with its first item */
2022 while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
2023 PyObject *tmp = type;
2024 type = PyTuple_GET_ITEM(type, 0);
2025 Py_INCREF(type);
2026 Py_DECREF(tmp);
2029 if (PyString_Check(type))
2032 else if (PyClass_Check(type))
2033 PyErr_NormalizeException(&type, &value, &tb);
2035 else if (PyInstance_Check(type)) {
2036 /* Raising an instance. The value should be a dummy. */
2037 if (value != Py_None) {
2038 PyErr_SetString(PyExc_TypeError,
2039 "instance exception may not have a separate value");
2040 goto raise_error;
2042 else {
2043 /* Normalize to raise <class>, <instance> */
2044 Py_DECREF(value);
2045 value = type;
2046 type = (PyObject*) ((PyInstanceObject*)type)->in_class;
2047 Py_INCREF(type);
2050 else {
2051 /* Not something you can raise. You get an exception
2052 anyway, just not what you specified :-) */
2053 PyErr_SetString(PyExc_TypeError,
2054 "exceptions must be strings, classes, or instances");
2055 goto raise_error;
2057 PyErr_Restore(type, value, tb);
2058 if (tb == NULL)
2059 return WHY_EXCEPTION;
2060 else
2061 return WHY_RERAISE;
2062 raise_error:
2063 Py_XDECREF(value);
2064 Py_XDECREF(type);
2065 Py_XDECREF(tb);
2066 return WHY_EXCEPTION;
2069 static int
2070 unpack_sequence(v, argcnt, sp)
2071 PyObject *v;
2072 int argcnt;
2073 PyObject **sp;
2075 int i;
2076 PyObject *w;
2078 for (i = 0; i < argcnt; i++) {
2079 if (! (w = PySequence_GetItem(v, i))) {
2080 if (PyErr_ExceptionMatches(PyExc_IndexError))
2081 PyErr_SetString(PyExc_ValueError,
2082 "unpack sequence of wrong size");
2083 goto finally;
2085 *--sp = w;
2087 /* we better get an IndexError now */
2088 if (PySequence_GetItem(v, i) == NULL) {
2089 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2090 PyErr_Clear();
2091 return 1;
2093 /* some other exception occurred. fall through to finally */
2095 else
2096 PyErr_SetString(PyExc_ValueError,
2097 "unpack sequence of wrong size");
2098 /* fall through */
2099 finally:
2100 for (; i > 0; i--, sp++)
2101 Py_DECREF(*sp);
2103 return 0;
2107 #ifdef LLTRACE
2108 static int
2109 prtrace(v, str)
2110 PyObject *v;
2111 char *str;
2113 printf("%s ", str);
2114 if (PyObject_Print(v, stdout, 0) != 0)
2115 PyErr_Clear(); /* Don't know what else to do */
2116 printf("\n");
2118 #endif
2120 static void
2121 call_exc_trace(p_trace, p_newtrace, f)
2122 PyObject **p_trace, **p_newtrace;
2123 PyFrameObject *f;
2125 PyObject *type, *value, *traceback, *arg;
2126 int err;
2127 PyErr_Fetch(&type, &value, &traceback);
2128 if (value == NULL) {
2129 value = Py_None;
2130 Py_INCREF(value);
2132 arg = Py_BuildValue("(OOO)", type, value, traceback);
2133 if (arg == NULL) {
2134 PyErr_Restore(type, value, traceback);
2135 return;
2137 err = call_trace(p_trace, p_newtrace, f, "exception", arg);
2138 Py_DECREF(arg);
2139 if (err == 0)
2140 PyErr_Restore(type, value, traceback);
2141 else {
2142 Py_XDECREF(type);
2143 Py_XDECREF(value);
2144 Py_XDECREF(traceback);
2148 static int
2149 call_trace(p_trace, p_newtrace, f, msg, arg)
2150 PyObject **p_trace; /* in/out; may not be NULL;
2151 may not point to NULL variable initially */
2152 PyObject **p_newtrace; /* in/out; may be NULL;
2153 may point to NULL variable;
2154 may be same variable as p_newtrace */
2155 PyFrameObject *f;
2156 char *msg;
2157 PyObject *arg;
2159 PyThreadState *tstate = f->f_tstate;
2160 PyObject *args, *what;
2161 PyObject *res = NULL;
2163 if (tstate->tracing) {
2164 /* Don't do recursive traces */
2165 if (p_newtrace) {
2166 Py_XDECREF(*p_newtrace);
2167 *p_newtrace = NULL;
2169 return 0;
2172 args = PyTuple_New(3);
2173 if (args == NULL)
2174 goto cleanup;
2175 what = PyString_FromString(msg);
2176 if (what == NULL)
2177 goto cleanup;
2178 Py_INCREF(f);
2179 PyTuple_SET_ITEM(args, 0, (PyObject *)f);
2180 PyTuple_SET_ITEM(args, 1, what);
2181 if (arg == NULL)
2182 arg = Py_None;
2183 Py_INCREF(arg);
2184 PyTuple_SET_ITEM(args, 2, arg);
2185 tstate->tracing++;
2186 PyFrame_FastToLocals(f);
2187 res = PyEval_CallObject(*p_trace, args); /* May clear *p_trace! */
2188 PyFrame_LocalsToFast(f, 1);
2189 tstate->tracing--;
2190 cleanup:
2191 Py_XDECREF(args);
2192 if (res == NULL) {
2193 /* The trace proc raised an exception */
2194 PyTraceBack_Here(f);
2195 Py_XDECREF(*p_trace);
2196 *p_trace = NULL;
2197 if (p_newtrace) {
2198 Py_XDECREF(*p_newtrace);
2199 *p_newtrace = NULL;
2201 return -1;
2203 else {
2204 if (p_newtrace) {
2205 Py_XDECREF(*p_newtrace);
2206 if (res == Py_None)
2207 *p_newtrace = NULL;
2208 else {
2209 Py_INCREF(res);
2210 *p_newtrace = res;
2213 Py_DECREF(res);
2214 return 0;
2218 PyObject *
2219 PyEval_GetBuiltins()
2221 PyThreadState *tstate = PyThreadState_Get();
2222 PyFrameObject *current_frame = tstate->frame;
2223 if (current_frame == NULL)
2224 return tstate->interp->builtins;
2225 else
2226 return current_frame->f_builtins;
2229 PyObject *
2230 PyEval_GetLocals()
2232 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2233 if (current_frame == NULL)
2234 return NULL;
2235 PyFrame_FastToLocals(current_frame);
2236 return current_frame->f_locals;
2239 PyObject *
2240 PyEval_GetGlobals()
2242 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2243 if (current_frame == NULL)
2244 return NULL;
2245 else
2246 return current_frame->f_globals;
2249 PyObject *
2250 PyEval_GetFrame()
2252 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2253 return (PyObject *)current_frame;
2257 PyEval_GetRestricted()
2259 PyFrameObject *current_frame = PyThreadState_Get()->frame;
2260 return current_frame == NULL ? 0 : current_frame->f_restricted;
2264 Py_FlushLine()
2266 PyObject *f = PySys_GetObject("stdout");
2267 if (f == NULL)
2268 return 0;
2269 if (!PyFile_SoftSpace(f, 0))
2270 return 0;
2271 return PyFile_WriteString("\n", f);
2275 /* External interface to call any callable object.
2276 The arg must be a tuple or NULL. */
2278 #undef PyEval_CallObject
2279 /* for backward compatibility: export this interface */
2281 PyObject *
2282 PyEval_CallObject(func, arg)
2283 PyObject *func;
2284 PyObject *arg;
2286 return PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL);
2288 #define PyEval_CallObject(func,arg) \
2289 PyEval_CallObjectWithKeywords(func, arg, (PyObject *)NULL)
2291 PyObject *
2292 PyEval_CallObjectWithKeywords(func, arg, kw)
2293 PyObject *func;
2294 PyObject *arg;
2295 PyObject *kw;
2297 ternaryfunc call;
2298 PyObject *result;
2300 if (arg == NULL)
2301 arg = PyTuple_New(0);
2302 else if (!PyTuple_Check(arg)) {
2303 PyErr_SetString(PyExc_TypeError,
2304 "argument list must be a tuple");
2305 return NULL;
2307 else
2308 Py_INCREF(arg);
2310 if (kw != NULL && !PyDict_Check(kw)) {
2311 PyErr_SetString(PyExc_TypeError,
2312 "keyword list must be a dictionary");
2313 return NULL;
2316 if ((call = func->ob_type->tp_call) != NULL)
2317 result = (*call)(func, arg, kw);
2318 else if (PyMethod_Check(func) || PyFunction_Check(func))
2319 result = call_function(func, arg, kw);
2320 else
2321 result = call_builtin(func, arg, kw);
2323 Py_DECREF(arg);
2325 if (result == NULL && !PyErr_Occurred())
2326 PyErr_SetString(PyExc_SystemError,
2327 "NULL result without error in call_object");
2329 return result;
2332 static PyObject *
2333 call_builtin(func, arg, kw)
2334 PyObject *func;
2335 PyObject *arg;
2336 PyObject *kw;
2338 if (PyCFunction_Check(func)) {
2339 PyCFunction meth = PyCFunction_GetFunction(func);
2340 PyObject *self = PyCFunction_GetSelf(func);
2341 int flags = PyCFunction_GetFlags(func);
2342 if (!(flags & METH_VARARGS)) {
2343 int size = PyTuple_Size(arg);
2344 if (size == 1)
2345 arg = PyTuple_GET_ITEM(arg, 0);
2346 else if (size == 0)
2347 arg = NULL;
2349 if (flags & METH_KEYWORDS)
2350 return (*(PyCFunctionWithKeywords)meth)(self, arg, kw);
2351 if (kw != NULL && PyDict_Size(kw) != 0) {
2352 PyErr_SetString(PyExc_TypeError,
2353 "this function takes no keyword arguments");
2354 return NULL;
2356 return (*meth)(self, arg);
2358 if (PyClass_Check(func)) {
2359 return PyInstance_New(func, arg, kw);
2361 if (PyInstance_Check(func)) {
2362 PyObject *res, *call = PyObject_GetAttrString(func,"__call__");
2363 if (call == NULL) {
2364 PyErr_Clear();
2365 PyErr_SetString(PyExc_AttributeError,
2366 "no __call__ method defined");
2367 return NULL;
2369 res = PyEval_CallObjectWithKeywords(call, arg, kw);
2370 Py_DECREF(call);
2371 return res;
2373 PyErr_Format(PyExc_TypeError, "call of non-function (type %s)",
2374 func->ob_type->tp_name);
2375 return NULL;
2378 static PyObject *
2379 call_function(func, arg, kw)
2380 PyObject *func;
2381 PyObject *arg;
2382 PyObject *kw;
2384 PyObject *class = NULL; /* == owner */
2385 PyObject *argdefs;
2386 PyObject **d, **k;
2387 int nk, nd;
2388 PyObject *result;
2390 if (kw != NULL && !PyDict_Check(kw)) {
2391 PyErr_BadInternalCall();
2392 return NULL;
2395 if (PyMethod_Check(func)) {
2396 PyObject *self = PyMethod_Self(func);
2397 class = PyMethod_Class(func);
2398 func = PyMethod_Function(func);
2399 if (self == NULL) {
2400 /* Unbound methods must be called with an instance of
2401 the class (or a derived class) as first argument */
2402 if (PyTuple_Size(arg) >= 1) {
2403 self = PyTuple_GET_ITEM(arg, 0);
2404 if (self != NULL &&
2405 PyInstance_Check(self) &&
2406 PyClass_IsSubclass((PyObject *)
2407 (((PyInstanceObject *)self)->in_class),
2408 class))
2409 /* Handy-dandy */ ;
2410 else
2411 self = NULL;
2413 if (self == NULL) {
2414 PyErr_SetString(PyExc_TypeError,
2415 "unbound method must be called with class instance 1st argument");
2416 return NULL;
2418 Py_INCREF(arg);
2420 else {
2421 int argcount = PyTuple_Size(arg);
2422 PyObject *newarg = PyTuple_New(argcount + 1);
2423 int i;
2424 if (newarg == NULL)
2425 return NULL;
2426 Py_INCREF(self);
2427 PyTuple_SET_ITEM(newarg, 0, self);
2428 for (i = 0; i < argcount; i++) {
2429 PyObject *v = PyTuple_GET_ITEM(arg, i);
2430 Py_XINCREF(v);
2431 PyTuple_SET_ITEM(newarg, i+1, v);
2433 arg = newarg;
2435 if (!PyFunction_Check(func)) {
2436 result = PyEval_CallObjectWithKeywords(func, arg, kw);
2437 Py_DECREF(arg);
2438 return result;
2441 else {
2442 if (!PyFunction_Check(func)) {
2443 PyErr_Format(PyExc_TypeError,
2444 "call of non-function (type %s)",
2445 func->ob_type->tp_name);
2446 return NULL;
2448 Py_INCREF(arg);
2451 argdefs = PyFunction_GetDefaults(func);
2452 if (argdefs != NULL && PyTuple_Check(argdefs)) {
2453 d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
2454 nd = PyTuple_Size(argdefs);
2456 else {
2457 d = NULL;
2458 nd = 0;
2461 if (kw != NULL) {
2462 int pos, i;
2463 nk = PyDict_Size(kw);
2464 k = PyMem_NEW(PyObject *, 2*nk);
2465 if (k == NULL) {
2466 PyErr_NoMemory();
2467 Py_DECREF(arg);
2468 return NULL;
2470 pos = i = 0;
2471 while (PyDict_Next(kw, &pos, &k[i], &k[i+1]))
2472 i += 2;
2473 nk = i/2;
2474 /* XXX This is broken if the caller deletes dict items! */
2476 else {
2477 k = NULL;
2478 nk = 0;
2481 result = eval_code2(
2482 (PyCodeObject *)PyFunction_GetCode(func),
2483 PyFunction_GetGlobals(func), (PyObject *)NULL,
2484 &PyTuple_GET_ITEM(arg, 0), PyTuple_Size(arg),
2485 k, nk,
2486 d, nd,
2487 class);
2489 Py_DECREF(arg);
2490 PyMem_XDEL(k);
2492 return result;
2495 #define SLICE_ERROR_MSG \
2496 "standard sequence type does not support step size other than one"
2498 static PyObject *
2499 loop_subscript(v, w)
2500 PyObject *v, *w;
2502 PySequenceMethods *sq = v->ob_type->tp_as_sequence;
2503 int i;
2504 if (sq == NULL || sq->sq_item == NULL) {
2505 PyErr_SetString(PyExc_TypeError, "loop over non-sequence");
2506 return NULL;
2508 i = PyInt_AsLong(w);
2509 v = (*sq->sq_item)(v, i);
2510 if (v)
2511 return v;
2512 if (PyErr_ExceptionMatches(PyExc_IndexError))
2513 PyErr_Clear();
2514 return NULL;
2517 static int
2518 slice_index(v, pi)
2519 PyObject *v;
2520 int *pi;
2522 if (v != NULL) {
2523 long x;
2524 if (!PyInt_Check(v)) {
2525 PyErr_SetString(PyExc_TypeError,
2526 "slice index must be int");
2527 return -1;
2529 x = PyInt_AsLong(v);
2530 /* Truncate -- very long indices are truncated anyway */
2531 if (x > INT_MAX)
2532 x = INT_MAX;
2533 else if (x < -INT_MAX)
2534 x = 0;
2535 *pi = x;
2537 return 0;
2540 static PyObject *
2541 apply_slice(u, v, w) /* return u[v:w] */
2542 PyObject *u, *v, *w;
2544 int ilow = 0, ihigh = INT_MAX;
2545 if (slice_index(v, &ilow) != 0)
2546 return NULL;
2547 if (slice_index(w, &ihigh) != 0)
2548 return NULL;
2549 return PySequence_GetSlice(u, ilow, ihigh);
2552 static int
2553 assign_slice(u, v, w, x) /* u[v:w] = x */
2554 PyObject *u, *v, *w, *x;
2556 int ilow = 0, ihigh = INT_MAX;
2557 if (slice_index(v, &ilow) != 0)
2558 return -1;
2559 if (slice_index(w, &ihigh) != 0)
2560 return -1;
2561 if (x == NULL)
2562 return PySequence_DelSlice(u, ilow, ihigh);
2563 else
2564 return PySequence_SetSlice(u, ilow, ihigh, x);
2567 static PyObject *
2568 cmp_outcome(op, v, w)
2569 int op;
2570 register PyObject *v;
2571 register PyObject *w;
2573 register int cmp;
2574 register int res = 0;
2575 switch (op) {
2576 case IS:
2577 case IS_NOT:
2578 res = (v == w);
2579 if (op == (int) IS_NOT)
2580 res = !res;
2581 break;
2582 case IN:
2583 case NOT_IN:
2584 res = PySequence_Contains(w, v);
2585 if (res < 0)
2586 return NULL;
2587 if (op == (int) NOT_IN)
2588 res = !res;
2589 break;
2590 case EXC_MATCH:
2591 res = PyErr_GivenExceptionMatches(v, w);
2592 break;
2593 default:
2594 cmp = PyObject_Compare(v, w);
2595 if (cmp && PyErr_Occurred())
2596 return NULL;
2597 switch (op) {
2598 case LT: res = cmp < 0; break;
2599 case LE: res = cmp <= 0; break;
2600 case EQ: res = cmp == 0; break;
2601 case NE: res = cmp != 0; break;
2602 case GT: res = cmp > 0; break;
2603 case GE: res = cmp >= 0; break;
2604 /* XXX no default? (res is initialized to 0 though) */
2607 v = res ? Py_True : Py_False;
2608 Py_INCREF(v);
2609 return v;
2612 static int
2613 import_from(locals, v, name)
2614 PyObject *locals;
2615 PyObject *v;
2616 PyObject *name;
2618 PyObject *w, *x;
2619 if (!PyModule_Check(v)) {
2620 PyErr_SetString(PyExc_TypeError,
2621 "import-from requires module object");
2622 return -1;
2624 w = PyModule_GetDict(v);
2625 if (PyString_AsString(name)[0] == '*') {
2626 int pos, err;
2627 PyObject *name, *value;
2628 pos = 0;
2629 while (PyDict_Next(w, &pos, &name, &value)) {
2630 if (!PyString_Check(name) ||
2631 PyString_AsString(name)[0] == '_')
2632 continue;
2633 Py_INCREF(value);
2634 err = PyDict_SetItem(locals, name, value);
2635 Py_DECREF(value);
2636 if (err != 0)
2637 return -1;
2639 return 0;
2641 else {
2642 x = PyDict_GetItem(w, name);
2643 if (x == NULL) {
2644 char buf[250];
2645 sprintf(buf, "cannot import name %.230s",
2646 PyString_AsString(name));
2647 PyErr_SetString(PyExc_ImportError, buf);
2648 return -1;
2650 else
2651 return PyDict_SetItem(locals, name, x);
2655 static PyObject *
2656 build_class(methods, bases, name)
2657 PyObject *methods; /* dictionary */
2658 PyObject *bases; /* tuple containing classes */
2659 PyObject *name; /* string */
2661 int i, n;
2662 if (!PyTuple_Check(bases)) {
2663 PyErr_SetString(PyExc_SystemError,
2664 "build_class with non-tuple bases");
2665 return NULL;
2667 if (!PyDict_Check(methods)) {
2668 PyErr_SetString(PyExc_SystemError,
2669 "build_class with non-dictionary");
2670 return NULL;
2672 if (!PyString_Check(name)) {
2673 PyErr_SetString(PyExc_SystemError,
2674 "build_class witn non-string name");
2675 return NULL;
2677 n = PyTuple_Size(bases);
2678 for (i = 0; i < n; i++) {
2679 PyObject *base = PyTuple_GET_ITEM(bases, i);
2680 if (!PyClass_Check(base)) {
2681 /* Call the base's *type*, if it is callable.
2682 This code is a hook for Donald Beaudry's
2683 and Jim Fulton's type extensions. In
2684 unexended Python it will never be triggered
2685 since its types are not callable.
2686 Ditto: call the bases's *class*, if it has
2687 one. This makes the same thing possible
2688 without writing C code. A true meta-object
2689 protocol! */
2690 PyObject *basetype = (PyObject *)base->ob_type;
2691 PyObject *callable = NULL;
2692 if (PyCallable_Check(basetype))
2693 callable = basetype;
2694 else
2695 callable = PyObject_GetAttrString(
2696 base, "__class__");
2697 if (callable) {
2698 PyObject *args;
2699 PyObject *newclass = NULL;
2700 args = Py_BuildValue(
2701 "(OOO)", name, bases, methods);
2702 if (args != NULL) {
2703 newclass = PyEval_CallObject(
2704 callable, args);
2705 Py_DECREF(args);
2707 if (callable != basetype) {
2708 Py_DECREF(callable);
2710 return newclass;
2712 PyErr_SetString(PyExc_TypeError,
2713 "base is not a class object");
2714 return NULL;
2717 return PyClass_New(bases, methods, name);
2720 static int
2721 exec_statement(f, prog, globals, locals)
2722 PyFrameObject *f;
2723 PyObject *prog;
2724 PyObject *globals;
2725 PyObject *locals;
2727 char *s;
2728 int n;
2729 PyObject *v;
2730 int plain = 0;
2732 if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
2733 ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
2734 /* Backward compatibility hack */
2735 globals = PyTuple_GetItem(prog, 1);
2736 if (n == 3)
2737 locals = PyTuple_GetItem(prog, 2);
2738 prog = PyTuple_GetItem(prog, 0);
2740 if (globals == Py_None) {
2741 globals = PyEval_GetGlobals();
2742 if (locals == Py_None) {
2743 locals = PyEval_GetLocals();
2744 plain = 1;
2747 else if (locals == Py_None)
2748 locals = globals;
2749 if (!PyString_Check(prog) &&
2750 !PyCode_Check(prog) &&
2751 !PyFile_Check(prog)) {
2752 PyErr_SetString(PyExc_TypeError,
2753 "exec 1st arg must be string, code or file object");
2754 return -1;
2756 if (!PyDict_Check(globals) || !PyDict_Check(locals)) {
2757 PyErr_SetString(PyExc_TypeError,
2758 "exec 2nd/3rd args must be dict or None");
2759 return -1;
2761 if (PyDict_GetItemString(globals, "__builtins__") == NULL)
2762 PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
2763 if (PyCode_Check(prog)) {
2764 v = PyEval_EvalCode((PyCodeObject *) prog,
2765 globals, locals);
2766 if (v == NULL)
2767 return -1;
2768 Py_DECREF(v);
2769 return 0;
2771 if (PyFile_Check(prog)) {
2772 FILE *fp = PyFile_AsFile(prog);
2773 char *name = PyString_AsString(PyFile_Name(prog));
2774 if (PyRun_File(fp, name, Py_file_input,
2775 globals, locals) == NULL)
2776 return -1;
2777 return 0;
2779 s = PyString_AsString(prog);
2780 if ((int)strlen(s) != PyString_Size(prog)) {
2781 PyErr_SetString(PyExc_ValueError,
2782 "embedded '\\0' in exec string");
2783 return -1;
2785 v = PyRun_String(s, Py_file_input, globals, locals);
2786 if (v == NULL)
2787 return -1;
2788 Py_DECREF(v);
2789 if (plain)
2790 PyFrame_LocalsToFast(f, 0);
2791 return 0;
2794 /* Hack for ni.py */
2795 static PyObject *
2796 find_from_args(f, nexti)
2797 PyFrameObject *f;
2798 int nexti;
2800 int opcode;
2801 int oparg;
2802 PyObject *list, *name;
2803 unsigned char *next_instr;
2805 _PyCode_GETCODEPTR(f->f_code, &next_instr);
2806 next_instr += nexti;
2808 opcode = (*next_instr++);
2809 if (opcode != IMPORT_FROM) {
2810 Py_INCREF(Py_None);
2811 return Py_None;
2814 list = PyList_New(0);
2815 if (list == NULL)
2816 return NULL;
2818 do {
2819 oparg = (next_instr[1]<<8) + next_instr[0];
2820 next_instr += 2;
2821 name = Getnamev(f, oparg);
2822 if (PyList_Append(list, name) < 0) {
2823 Py_DECREF(list);
2824 break;
2826 opcode = (*next_instr++);
2827 } while (opcode == IMPORT_FROM);
2829 return list;
2833 #ifdef DYNAMIC_EXECUTION_PROFILE
2835 PyObject *
2836 getarray(a)
2837 long a[256];
2839 int i;
2840 PyObject *l = PyList_New(256);
2841 if (l == NULL) return NULL;
2842 for (i = 0; i < 256; i++) {
2843 PyObject *x = PyInt_FromLong(a[i]);
2844 if (x == NULL) {
2845 Py_DECREF(l);
2846 return NULL;
2848 PyList_SetItem(l, i, x);
2850 for (i = 0; i < 256; i++)
2851 a[i] = 0;
2852 return l;
2855 PyObject *
2856 _Py_GetDXProfile(self, args)
2857 PyObject *self, *args;
2859 #ifndef DXPAIRS
2860 return getarray(dxp);
2861 #else
2862 int i;
2863 PyObject *l = PyList_New(257);
2864 if (l == NULL) return NULL;
2865 for (i = 0; i < 257; i++) {
2866 PyObject *x = getarray(dxpairs[i]);
2867 if (x == NULL) {
2868 Py_DECREF(l);
2869 return NULL;
2871 PyList_SetItem(l, i, x);
2873 return l;
2874 #endif
2877 #endif