2 /* Execute compiled code */
5 XXX how to pass arguments to call_trace?
6 XXX speed up searching for keywords by using a dictionary
13 #include "frameobject.h"
23 /* Turn this on if your compiler chokes on the big switch: */
24 /* #define CASE_TOO_BIG 1 */
27 /* For debugging the interpreter: */
28 #define LLTRACE 1 /* Low-level trace feature */
29 #define CHECKEXC 1 /* Double-check exception checking */
33 /* Forward declarations */
35 static PyObject
*eval_code2(PyCodeObject
*,
36 PyObject
*, PyObject
*,
42 static int prtrace(PyObject
*, char *);
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
71 static long dxpairs
[257][256];
72 #define dxp dxpairs[256]
81 #ifndef DONT_HAVE_ERRNO_H
86 extern int _PyThread_Started
; /* Flag for Py_Exit */
88 static PyThread_type_lock interpreter_lock
= 0;
89 static long main_thread
= 0;
92 PyEval_InitThreads(void)
96 _PyThread_Started
= 1;
97 interpreter_lock
= PyThread_allocate_lock();
98 PyThread_acquire_lock(interpreter_lock
, 1);
99 main_thread
= PyThread_get_thread_ident();
103 PyEval_AcquireLock(void)
105 PyThread_acquire_lock(interpreter_lock
, 1);
109 PyEval_ReleaseLock(void)
111 PyThread_release_lock(interpreter_lock
);
115 PyEval_AcquireThread(PyThreadState
*tstate
)
118 Py_FatalError("PyEval_AcquireThread: NULL new thread state");
119 PyThread_acquire_lock(interpreter_lock
, 1);
120 if (PyThreadState_Swap(tstate
) != NULL
)
122 "PyEval_AcquireThread: non-NULL old thread state");
126 PyEval_ReleaseThread(PyThreadState
*tstate
)
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.) */
141 PyEval_ReInitThreads(void)
143 if (!interpreter_lock
)
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();
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: */
160 PyEval_SaveThread(void)
162 PyThreadState
*tstate
= PyThreadState_Swap(NULL
);
164 Py_FatalError("PyEval_SaveThread: NULL tstate");
166 if (interpreter_lock
)
167 PyThread_release_lock(interpreter_lock
);
173 PyEval_RestoreThread(PyThreadState
*tstate
)
176 Py_FatalError("PyEval_RestoreThread: NULL tstate");
178 if (interpreter_lock
) {
180 PyThread_acquire_lock(interpreter_lock
, 1);
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!
203 Any thread can schedule pending calls, but only the main thread
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
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
)
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! */
241 j
= (i
+ 1) % NPENDINGCALLS
;
242 if (j
== pendingfirst
)
243 return -1; /* Queue full */
244 pendingcalls
[i
].func
= func
;
245 pendingcalls
[i
].arg
= arg
;
247 things_to_do
= 1; /* Signal main loop */
249 /* XXX End critical section */
254 Py_MakePendingCalls(void)
258 if (main_thread
&& PyThread_get_thread_ident() != main_thread
)
270 if (i
== pendinglast
)
271 break; /* Queue empty */
272 func
= pendingcalls
[i
].func
;
273 arg
= pendingcalls
[i
].arg
;
274 pendingfirst
= (i
+ 1) % NPENDINGCALLS
;
277 things_to_do
= 1; /* We're not done yet */
286 /* The interpreter's recursion limit */
288 static int recursion_limit
= 1000;
291 Py_GetRecursionLimit(void)
293 return recursion_limit
;
297 Py_SetRecursionLimit(int new_limit
)
299 recursion_limit
= new_limit
;
302 /* Status code for main loop (reason for stack unwind) */
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
**);
317 PyEval_EvalCode(PyCodeObject
*co
, PyObject
*globals
, PyObject
*locals
)
319 return eval_code2(co
,
321 (PyObject
**)NULL
, 0,
322 (PyObject
**)NULL
, 0,
323 (PyObject
**)NULL
, 0,
328 /* Interpreter main loop */
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
)
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
;
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
);
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)
383 #define PUSH(v) (BASIC_PUSH(v), lltrace && prtrace(TOP(), "push"))
384 #define POP() (lltrace && prtrace(TOP(), "pop"), BASIC_POP())
386 #define PUSH(v) BASIC_PUSH(v)
387 #define POP() BASIC_POP()
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)
398 #ifdef USE_STACKCHECK
399 if (tstate
->recursion_depth
%10 == 0 && PyOS_CheckStack()) {
400 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
405 if (globals
== NULL
) {
406 PyErr_SetString(PyExc_SystemError
, "eval_code2: NULL globals");
411 lltrace
= PyDict_GetItemString(globals
, "__lltrace__") != NULL
;
423 fastlocals
= f
->f_localsplus
;
425 if (co
->co_argcount
> 0 ||
426 co
->co_flags
& (CO_VARARGS
| CO_VARKEYWORDS
)) {
429 PyObject
*kwdict
= NULL
;
430 if (co
->co_flags
& CO_VARKEYWORDS
) {
431 kwdict
= PyDict_New();
435 if (co
->co_flags
& CO_VARARGS
)
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
);
448 for (i
= 0; i
< n
; i
++) {
453 if (co
->co_flags
& CO_VARARGS
) {
454 u
= PyTuple_New(argcount
- n
);
457 SETLOCAL(co
->co_argcount
, u
);
458 for (i
= n
; i
< argcount
; i
++) {
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];
468 if (keyword
== NULL
|| !PyString_Check(keyword
)) {
469 PyErr_SetString(PyExc_TypeError
,
470 "keywords must be strings");
473 /* XXX slow -- speed up using dictionary? */
474 for (j
= 0; j
< co
->co_argcount
; j
++) {
475 PyObject
*nm
= PyTuple_GET_ITEM(
477 if (PyObject_Compare(keyword
, nm
) == 0)
480 /* Check errors from Compare */
481 if (PyErr_Occurred())
483 if (j
>= co
->co_argcount
) {
484 if (kwdict
== NULL
) {
485 PyErr_Format(PyExc_TypeError
,
486 "unexpected keyword argument: %.400s",
487 PyString_AsString(keyword
));
490 PyDict_SetItem(kwdict
, keyword
, value
);
493 if (GETLOCAL(j
) != NULL
) {
494 PyErr_Format(PyExc_TypeError
,
495 "keyword parameter redefined: %.400s",
496 PyString_AsString(keyword
));
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",
517 for (; i
< defcount
; i
++) {
518 if (GETLOCAL(m
+i
) == NULL
) {
519 PyObject
*def
= defs
[i
];
527 if (argcount
> 0 || kwcount
> 0) {
528 PyErr_SetString(PyExc_TypeError
,
529 "no arguments expected");
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
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 */
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",
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
;
574 _PyCode_GETCODEPTR(co
, &first_instr
);
575 next_instr
= first_instr
;
576 stack_pointer
= f
->f_valuestack
;
580 x
= Py_None
; /* Not a reference, just anything non-NULL */
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
;
595 if (Py_MakePendingCalls() < 0) {
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()) {
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");
628 /* Extract opcode and argument */
630 #if defined(Py_DEBUG) || defined(LLTRACE)
631 f
->f_lasti
= INSTR_OFFSET();
638 #ifdef DYNAMIC_EXECUTION_PROFILE
640 dxpairs
[lastopcode
][opcode
]++;
647 /* Instruction tracing */
650 if (HAS_ARG(opcode
)) {
651 printf("%d: %d, %d\n",
652 (int) (INSTR_OFFSET() - 3),
657 (int) (INSTR_OFFSET() - 1), opcode
);
661 /* Main switch on opcode */
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! */
778 Py_FatalError("invalid argument to DUP_TOPX"
779 " (bytecode corruption?)");
785 x
= PyNumber_Positive(v
);
788 if (x
!= NULL
) continue;
793 x
= PyNumber_Negative(v
);
796 if (x
!= NULL
) continue;
801 err
= PyObject_IsTrue(v
);
818 x
= PyObject_Repr(v
);
821 if (x
!= NULL
) continue;
826 x
= PyNumber_Invert(v
);
829 if (x
!= NULL
) continue;
835 x
= PyNumber_Power(v
, w
, Py_None
);
839 if (x
!= NULL
) continue;
842 case BINARY_MULTIPLY
:
845 x
= PyNumber_Multiply(v
, w
);
849 if (x
!= NULL
) continue;
855 x
= PyNumber_Divide(v
, w
);
859 if (x
!= NULL
) continue;
865 x
= PyNumber_Remainder(v
, w
);
869 if (x
!= NULL
) continue;
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
);
881 if ((i
^a
) < 0 && (i
^b
) < 0) {
882 PyErr_SetString(PyExc_OverflowError
,
887 x
= PyInt_FromLong(i
);
890 x
= PyNumber_Add(v
, w
);
894 if (x
!= NULL
) continue;
897 case BINARY_SUBTRACT
:
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
);
906 if ((i
^a
) < 0 && (i
^~b
) < 0) {
907 PyErr_SetString(PyExc_OverflowError
,
908 "integer subtraction");
912 x
= PyInt_FromLong(i
);
915 x
= PyNumber_Subtract(v
, w
);
919 if (x
!= NULL
) continue;
925 if (PyList_Check(v
) && PyInt_Check(w
)) {
926 /* INLINE: list[int] */
927 long i
= PyInt_AsLong(w
);
929 i
+= PyList_GET_SIZE(v
);
931 i
>= PyList_GET_SIZE(v
)) {
932 PyErr_SetString(PyExc_IndexError
,
933 "list index out of range");
937 x
= PyList_GET_ITEM(v
, i
);
942 x
= PyObject_GetItem(v
, w
);
946 if (x
!= NULL
) continue;
952 x
= PyNumber_Lshift(v
, w
);
956 if (x
!= NULL
) continue;
962 x
= PyNumber_Rshift(v
, w
);
966 if (x
!= NULL
) continue;
972 x
= PyNumber_And(v
, w
);
976 if (x
!= NULL
) continue;
982 x
= PyNumber_Xor(v
, w
);
986 if (x
!= NULL
) continue;
992 x
= PyNumber_Or(v
, w
);
996 if (x
!= NULL
) continue;
1002 x
= PyNumber_InPlacePower(v
, w
, Py_None
);
1006 if (x
!= NULL
) continue;
1009 case INPLACE_MULTIPLY
:
1012 x
= PyNumber_InPlaceMultiply(v
, w
);
1016 if (x
!= NULL
) continue;
1019 case INPLACE_DIVIDE
:
1022 x
= PyNumber_InPlaceDivide(v
, w
);
1026 if (x
!= NULL
) continue;
1029 case INPLACE_MODULO
:
1032 x
= PyNumber_InPlaceRemainder(v
, w
);
1036 if (x
!= NULL
) continue;
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
);
1048 if ((i
^a
) < 0 && (i
^b
) < 0) {
1049 PyErr_SetString(PyExc_OverflowError
,
1050 "integer addition");
1054 x
= PyInt_FromLong(i
);
1057 x
= PyNumber_InPlaceAdd(v
, w
);
1061 if (x
!= NULL
) continue;
1064 case INPLACE_SUBTRACT
:
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
);
1073 if ((i
^a
) < 0 && (i
^~b
) < 0) {
1074 PyErr_SetString(PyExc_OverflowError
,
1075 "integer subtraction");
1079 x
= PyInt_FromLong(i
);
1082 x
= PyNumber_InPlaceSubtract(v
, w
);
1086 if (x
!= NULL
) continue;
1089 case INPLACE_LSHIFT
:
1092 x
= PyNumber_InPlaceLshift(v
, w
);
1096 if (x
!= NULL
) continue;
1099 case INPLACE_RSHIFT
:
1102 x
= PyNumber_InPlaceRshift(v
, w
);
1106 if (x
!= NULL
) continue;
1112 x
= PyNumber_InPlaceAnd(v
, w
);
1116 if (x
!= NULL
) continue;
1122 x
= PyNumber_InPlaceXor(v
, w
);
1126 if (x
!= NULL
) continue;
1132 x
= PyNumber_InPlaceOr(v
, w
);
1136 if (x
!= NULL
) continue;
1143 if ((opcode
-SLICE
) & 2)
1147 if ((opcode
-SLICE
) & 1)
1152 x
= apply_slice(u
, v
, w
);
1157 if (x
!= NULL
) continue;
1164 if ((opcode
-STORE_SLICE
) & 2)
1168 if ((opcode
-STORE_SLICE
) & 1)
1174 err
= assign_slice(u
, v
, w
, t
); /* u[v:w] = t */
1179 if (err
== 0) continue;
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)
1190 if ((opcode
-DELETE_SLICE
) & 1)
1195 err
= assign_slice(u
, v
, w
, (PyObject
*)NULL
);
1200 if (err
== 0) continue;
1208 err
= PyObject_SetItem(v
, w
, u
);
1212 if (err
== 0) continue;
1219 err
= PyObject_DelItem(v
, w
);
1222 if (err
== 0) continue;
1227 /* Print value except if None */
1228 /* After printing, also assign to '_' */
1229 /* Before, set '_' to None to avoid recursion */
1231 (err
= PyDict_SetItemString(
1232 f
->f_builtins
, "_", Py_None
)) == 0) {
1233 err
= Py_FlushLine();
1235 x
= PySys_GetObject("stdout");
1244 err
= PyFile_WriteObject(v
, x
, 0);
1246 PyFile_SoftSpace(x
, 1);
1247 err
= Py_FlushLine();
1250 err
= PyDict_SetItemString(
1251 f
->f_builtins
, "_", v
);
1259 /* fall through to PRINT_ITEM */
1263 if (stream
== NULL
|| stream
== Py_None
) {
1264 w
= PySys_GetObject("stdout");
1266 PyErr_SetString(PyExc_RuntimeError
,
1271 if (w
!= NULL
&& PyFile_SoftSpace(w
, 1))
1272 err
= PyFile_WriteString(" ", w
);
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
);
1280 isspace(Py_CHARMASK(s
[len
-1])) &&
1282 PyFile_SoftSpace(w
, 0);
1291 case PRINT_NEWLINE_TO
:
1293 /* fall through to PRINT_NEWLINE */
1296 if (stream
== NULL
|| stream
== Py_None
) {
1297 w
= PySys_GetObject("stdout");
1299 PyErr_SetString(PyExc_RuntimeError
,
1303 err
= PyFile_WriteString("\n", w
);
1305 PyFile_SoftSpace(w
, 0);
1313 default: switch (opcode
) {
1323 u
= POP(); /* traceback */
1326 v
= POP(); /* value */
1329 w
= POP(); /* exc */
1330 case 0: /* Fallthrough */
1331 why
= do_raise(w
, v
, u
);
1334 PyErr_SetString(PyExc_SystemError
,
1335 "bad RAISE_VARARGS oparg");
1336 why
= WHY_EXCEPTION
;
1342 if ((x
= f
->f_locals
) == NULL
) {
1343 PyErr_SetString(PyExc_SystemError
,
1360 err
= exec_statement(f
, u
, v
, w
);
1368 PyTryBlock
*b
= PyFrame_BlockPop(f
);
1369 while (STACK_LEVEL() > b
->b_level
) {
1378 if (PyInt_Check(v
)) {
1379 why
= (enum why_code
) PyInt_AsLong(v
);
1380 if (why
== WHY_RETURN
)
1383 else if (PyString_Check(v
) || PyClass_Check(v
)) {
1386 PyErr_Restore(v
, w
, u
);
1390 else if (v
!= Py_None
) {
1391 PyErr_SetString(PyExc_SystemError
,
1392 "'finally' pops bad exception");
1393 why
= WHY_EXCEPTION
;
1402 x
= build_class(u
, v
, w
);
1410 w
= GETNAMEV(oparg
);
1412 if ((x
= f
->f_locals
) == NULL
) {
1413 PyErr_SetString(PyExc_SystemError
,
1417 err
= PyDict_SetItem(x
, w
, v
);
1422 w
= GETNAMEV(oparg
);
1423 if ((x
= f
->f_locals
) == NULL
) {
1424 PyErr_SetString(PyExc_SystemError
,
1428 if ((err
= PyDict_DelItem(x
, w
)) != 0)
1429 format_exc_check_arg(PyExc_NameError
,
1433 case UNPACK_SEQUENCE
:
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
;
1442 for (; --oparg
>= 0; ) {
1443 w
= PyTuple_GET_ITEM(v
, oparg
);
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
;
1456 for (; --oparg
>= 0; ) {
1457 w
= PyList_GET_ITEM(v
, oparg
);
1463 else if (PySequence_Check(v
)) {
1464 if (unpack_sequence(v
, oparg
,
1465 stack_pointer
+ oparg
))
1466 stack_pointer
+= oparg
;
1468 why
= WHY_EXCEPTION
;
1471 PyErr_SetString(PyExc_TypeError
,
1472 "unpack non-sequence");
1473 why
= WHY_EXCEPTION
;
1479 w
= GETNAMEV(oparg
);
1482 err
= PyObject_SetAttr(v
, w
, u
); /* v.w = u */
1488 w
= GETNAMEV(oparg
);
1490 err
= PyObject_SetAttr(v
, w
, (PyObject
*)NULL
);
1496 w
= GETNAMEV(oparg
);
1498 err
= PyDict_SetItem(f
->f_globals
, w
, v
);
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
);
1510 x
= GETCONST(oparg
);
1516 w
= GETNAMEV(oparg
);
1517 if ((x
= f
->f_locals
) == NULL
) {
1518 PyErr_SetString(PyExc_SystemError
,
1522 x
= PyDict_GetItem(x
, w
);
1524 x
= PyDict_GetItem(f
->f_globals
, w
);
1526 x
= PyDict_GetItem(f
->f_builtins
, w
);
1528 format_exc_check_arg(
1540 w
= GETNAMEV(oparg
);
1541 x
= PyDict_GetItem(f
->f_globals
, w
);
1543 x
= PyDict_GetItem(f
->f_builtins
, w
);
1545 format_exc_check_arg(
1556 x
= GETLOCAL(oparg
);
1558 format_exc_check_arg(
1559 PyExc_UnboundLocalError
,
1560 UNBOUNDLOCAL_ERROR_MSG
,
1561 PyTuple_GetItem(co
->co_varnames
, oparg
)
1567 if (x
!= NULL
) continue;
1576 x
= GETLOCAL(oparg
);
1578 format_exc_check_arg(
1579 PyExc_UnboundLocalError
,
1580 UNBOUNDLOCAL_ERROR_MSG
,
1581 PyTuple_GetItem(co
->co_varnames
, oparg
)
1585 SETLOCAL(oparg
, NULL
);
1589 x
= PyTuple_New(oparg
);
1591 for (; --oparg
>= 0;) {
1593 PyTuple_SET_ITEM(x
, oparg
, w
);
1601 x
= PyList_New(oparg
);
1603 for (; --oparg
>= 0;) {
1605 PyList_SET_ITEM(x
, oparg
, w
);
1615 if (x
!= NULL
) continue;
1619 w
= GETNAMEV(oparg
);
1621 x
= PyObject_GetAttr(v
, w
);
1624 if (x
!= NULL
) continue;
1630 if (PyInt_Check(v
) && PyInt_Check(w
)) {
1631 /* INLINE: cmp(int, int) */
1634 a
= PyInt_AS_LONG(v
);
1635 b
= PyInt_AS_LONG(w
);
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
;
1652 x
= cmp_outcome(oparg
, v
, w
);
1657 if (x
!= NULL
) continue;
1661 w
= GETNAMEV(oparg
);
1662 x
= PyDict_GetItemString(f
->f_builtins
, "__import__");
1664 PyErr_SetString(PyExc_ImportError
,
1665 "__import__ not found");
1669 w
= Py_BuildValue("(OOOO)",
1672 f
->f_locals
== NULL
?
1673 Py_None
: f
->f_locals
,
1680 x
= PyEval_CallObject(x
, w
);
1683 if (x
!= NULL
) continue;
1688 PyFrame_FastToLocals(f
);
1689 if ((x
= f
->f_locals
) == NULL
) {
1690 PyErr_SetString(PyExc_SystemError
,
1694 err
= import_all_from(x
, v
);
1695 PyFrame_LocalsToFast(f
, 0);
1697 if (err
== 0) continue;
1701 w
= GETNAMEV(oparg
);
1703 x
= import_from(v
, w
);
1705 if (x
!= NULL
) continue;
1713 err
= PyObject_IsTrue(TOP());
1723 err
= PyObject_IsTrue(TOP());
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
);
1749 x
= PyInt_FromLong(PyInt_AsLong(w
)+1);
1753 if (x
!= NULL
) continue;
1758 /* A NULL can mean "s exhausted"
1759 but also an error: */
1760 if (PyErr_Occurred())
1761 why
= WHY_EXCEPTION
;
1772 PyFrame_BlockSetup(f
, opcode
, INSTR_OFFSET() + oparg
,
1779 printf("--- %s:%d \n", filename
, oparg
);
1781 f
->f_lineno
= oparg
;
1782 if (f
->f_trace
== NULL
)
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
);
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
);
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
),
1827 PyErr_SetString(PyExc_TypeError
,
1828 "unbound method must be called with class instance 1st argument");
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
);
1842 if (argdefs
!= NULL
) {
1843 d
= &PyTuple_GET_ITEM(argdefs
, 0);
1844 nd
= ((PyTupleObject
*)argdefs
)->ob_size
;
1850 x
= eval_code2((PyCodeObject
*)co
, globals
,
1851 (PyObject
*)NULL
, stack_pointer
-n
, na
,
1852 stack_pointer
-2*nk
, nk
, d
, nd
,
1858 PyObject
*stararg
= 0;
1859 PyObject
*kwdict
= NULL
;
1862 if (!PyDict_Check(kwdict
)) {
1863 PyErr_SetString(PyExc_TypeError
,
1864 "** argument must be a dictionary");
1870 if (!PySequence_Check(stararg
)) {
1871 PyErr_SetString(PyExc_TypeError
,
1872 "* argument must be a sequence");
1875 /* Convert abstract sequence to concrete tuple */
1876 if (!PyTuple_Check(stararg
)) {
1878 t
= PySequence_Tuple(stararg
);
1885 nstar
= PyTuple_GET_SIZE(stararg
);
1891 if (kwdict
== NULL
) {
1892 kwdict
= PyDict_New();
1893 if (kwdict
== NULL
) {
1898 PyObject
*d
= PyDict_Copy(kwdict
);
1907 PyObject
*value
= POP();
1908 PyObject
*key
= POP();
1909 if (PyDict_GetItem(kwdict
, key
) != NULL
) {
1911 PyErr_Format(PyExc_TypeError
,
1912 "keyword parameter redefined: %.400s",
1913 PyString_AsString(key
));
1918 err
= PyDict_SetItem(kwdict
, key
, value
);
1927 Py_XDECREF(stararg
);
1933 callargs
= PyTuple_New(na
+ nstar
);
1934 if (callargs
== NULL
) {
1940 for (i
= 0; i
< nstar
; i
++) {
1941 PyObject
*a
= PyTuple_GET_ITEM(stararg
, i
);
1943 PyTuple_SET_ITEM(callargs
, na
+ i
, a
);
1949 PyTuple_SET_ITEM(callargs
, na
, w
);
1951 x
= PyEval_CallObjectWithKeywords(func
,
1954 Py_DECREF(callargs
);
1958 while (stack_pointer
> pfunc
) {
1963 if (x
!= NULL
) continue;
1968 v
= POP(); /* code object */
1969 x
= PyFunction_New(v
, f
->f_globals
);
1971 /* XXX Maybe this should be a separate opcode? */
1972 if (x
!= NULL
&& oparg
> 0) {
1973 v
= PyTuple_New(oparg
);
1979 while (--oparg
>= 0) {
1981 PyTuple_SET_ITEM(v
, oparg
, w
);
1983 err
= PyFunction_SetDefaults(x
, v
);
1996 x
= PySlice_New(u
, v
, w
);
2001 if (x
!= NULL
) continue;
2006 oparg
= oparg
<<16 | NEXTARG();
2007 goto dispatch_opcode
;
2012 "XXX lineno: %d, opcode: %d\n",
2013 f
->f_lineno
, opcode
);
2014 PyErr_SetString(PyExc_SystemError
, "unknown opcode");
2015 why
= WHY_EXCEPTION
;
2026 /* Quickly continue if no error occurred */
2028 if (why
== WHY_NOT
) {
2029 if (err
== 0 && x
!= NULL
) {
2031 /* This check is expensive! */
2032 if (PyErr_Occurred())
2034 "XXX undetected error\n");
2037 continue; /* Normal, fast path */
2039 why
= WHY_EXCEPTION
;
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
;
2055 /* This check is expensive! */
2056 if (PyErr_Occurred()) {
2058 "XXX undetected error (why=%d)\n",
2060 why
= WHY_EXCEPTION
;
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
))
2071 PyTraceBack_Here(f
);
2074 call_exc_trace(&f
->f_trace
, &f
->f_trace
, f
);
2075 if (tstate
->sys_profilefunc
)
2076 call_exc_trace(&tstate
->sys_profilefunc
,
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
) {
2093 if (b
->b_type
== SETUP_LOOP
&& why
== WHY_BREAK
) {
2095 JUMPTO(b
->b_handler
);
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
);
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(
2116 set_exc_info(tstate
,
2124 if (why
== WHY_RETURN
)
2126 v
= PyInt_FromLong((long)why
);
2130 JUMPTO(b
->b_handler
);
2133 } /* unwind stack */
2135 /* End the loop if we still have an error (or return) */
2142 /* Pop remaining stack entries */
2149 if (why
!= WHY_RETURN
)
2153 if (why
== WHY_RETURN
) {
2154 if (call_trace(&f
->f_trace
, &f
->f_trace
, f
,
2155 "return", retval
)) {
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
)) {
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
;
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
) {
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
);
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
;
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
);
2226 /* For b/w compatibility */
2227 PySys_SetObject("exc_type", type
);
2228 PySys_SetObject("exc_value", value
);
2229 PySys_SetObject("exc_traceback", tb
);
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
);
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
);
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
)
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
;
2284 /* We support the following forms of raise:
2285 raise <class>, <classinstance>
2286 raise <class>, <argument tuple>
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
2305 if (tb
== Py_None
) {
2309 else if (tb
!= NULL
&& !PyTraceBack_Check(tb
)) {
2310 PyErr_SetString(PyExc_TypeError
,
2311 "raise 3rd arg must be traceback or None");
2315 /* Next, replace a missing value with None */
2316 if (value
== NULL
) {
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);
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");
2343 /* Normalize to raise <class>, <instance> */
2346 type
= (PyObject
*) ((PyInstanceObject
*)type
)->in_class
;
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");
2357 PyErr_Restore(type
, value
, tb
);
2359 return WHY_EXCEPTION
;
2366 return WHY_EXCEPTION
;
2370 unpack_sequence(PyObject
*v
, int argcnt
, PyObject
**sp
)
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");
2384 /* we better get an IndexError now */
2385 if (PySequence_GetItem(v
, i
) == NULL
) {
2386 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2390 /* some other exception occurred. fall through to finally */
2393 PyErr_SetString(PyExc_ValueError
,
2394 "unpack sequence of wrong size");
2397 for (; i
> 0; i
--, sp
++)
2406 prtrace(PyObject
*v
, char *str
)
2409 if (PyObject_Print(v
, stdout
, 0) != 0)
2410 PyErr_Clear(); /* Don't know what else to do */
2417 call_exc_trace(PyObject
**p_trace
, PyObject
**p_newtrace
, PyFrameObject
*f
)
2419 PyObject
*type
, *value
, *traceback
, *arg
;
2421 PyErr_Fetch(&type
, &value
, &traceback
);
2422 if (value
== NULL
) {
2426 arg
= Py_BuildValue("(OOO)", type
, value
, traceback
);
2428 PyErr_Restore(type
, value
, traceback
);
2431 err
= call_trace(p_trace
, p_newtrace
, f
, "exception", arg
);
2434 PyErr_Restore(type
, value
, traceback
);
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 */
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 */
2459 Py_XDECREF(*p_newtrace
);
2465 args
= PyTuple_New(3);
2468 what
= PyString_FromString(msg
);
2472 PyTuple_SET_ITEM(args
, 0, (PyObject
*)f
);
2473 PyTuple_SET_ITEM(args
, 1, what
);
2477 PyTuple_SET_ITEM(args
, 2, arg
);
2479 PyFrame_FastToLocals(f
);
2480 res
= PyEval_CallObject(*p_trace
, args
); /* May clear *p_trace! */
2481 PyFrame_LocalsToFast(f
, 1);
2486 /* The trace proc raised an exception */
2487 PyTraceBack_Here(f
);
2488 Py_XDECREF(*p_trace
);
2491 Py_XDECREF(*p_newtrace
);
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
;
2506 Py_XDECREF(*p_newtrace
);
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
;
2527 return current_frame
->f_builtins
;
2531 PyEval_GetLocals(void)
2533 PyFrameObject
*current_frame
= PyThreadState_Get()->frame
;
2534 if (current_frame
== NULL
)
2536 PyFrame_FastToLocals(current_frame
);
2537 return current_frame
->f_locals
;
2541 PyEval_GetGlobals(void)
2543 PyFrameObject
*current_frame
= PyThreadState_Get()->frame
;
2544 if (current_frame
== NULL
)
2547 return current_frame
->f_globals
;
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
;
2567 PyObject
*f
= PySys_GetObject("stdout");
2570 if (!PyFile_SoftSpace(f
, 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 */
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)
2591 PyEval_CallObjectWithKeywords(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2597 arg
= PyTuple_New(0);
2598 else if (!PyTuple_Check(arg
)) {
2599 PyErr_SetString(PyExc_TypeError
,
2600 "argument list must be a tuple");
2606 if (kw
!= NULL
&& !PyDict_Check(kw
)) {
2607 PyErr_SetString(PyExc_TypeError
,
2608 "keyword list must be a dictionary");
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
);
2618 result
= call_builtin(func
, arg
, kw
);
2622 if (result
== NULL
&& !PyErr_Occurred())
2623 PyErr_SetString(PyExc_SystemError
,
2624 "NULL result without error in call_object");
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
);
2639 arg
= PyTuple_GET_ITEM(arg
, 0);
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");
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__");
2659 PyErr_SetString(PyExc_AttributeError
,
2660 "no __call__ method defined");
2663 res
= PyEval_CallObjectWithKeywords(call
, arg
, kw
);
2667 PyErr_Format(PyExc_TypeError
, "call of non-function (type %.400s)",
2668 func
->ob_type
->tp_name
);
2673 call_function(PyObject
*func
, PyObject
*arg
, PyObject
*kw
)
2675 PyObject
*class = NULL
; /* == owner */
2681 if (kw
!= NULL
&& !PyDict_Check(kw
)) {
2682 PyErr_BadInternalCall();
2686 if (PyMethod_Check(func
)) {
2687 PyObject
*self
= PyMethod_Self(func
);
2688 class = PyMethod_Class(func
);
2689 func
= PyMethod_Function(func
);
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);
2696 PyInstance_Check(self
) &&
2697 PyClass_IsSubclass((PyObject
*)
2698 (((PyInstanceObject
*)self
)->in_class
),
2705 PyErr_SetString(PyExc_TypeError
,
2706 "unbound method must be called with class instance 1st argument");
2712 int argcount
= PyTuple_Size(arg
);
2713 PyObject
*newarg
= PyTuple_New(argcount
+ 1);
2718 PyTuple_SET_ITEM(newarg
, 0, self
);
2719 for (i
= 0; i
< argcount
; i
++) {
2720 PyObject
*v
= PyTuple_GET_ITEM(arg
, i
);
2722 PyTuple_SET_ITEM(newarg
, i
+1, v
);
2726 if (!PyFunction_Check(func
)) {
2727 result
= PyEval_CallObjectWithKeywords(func
, arg
, kw
);
2733 if (!PyFunction_Check(func
)) {
2734 PyErr_Format(PyExc_TypeError
,
2735 "call of non-function (type %.200s)",
2736 func
->ob_type
->tp_name
);
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
);
2754 nk
= PyDict_Size(kw
);
2755 k
= PyMem_NEW(PyObject
*, 2*nk
);
2762 while (PyDict_Next(kw
, &pos
, &k
[i
], &k
[i
+1]))
2765 /* XXX This is broken if the caller deletes dict items! */
2772 result
= eval_code2(
2773 (PyCodeObject
*)PyFunction_GetCode(func
),
2774 PyFunction_GetGlobals(func
), (PyObject
*)NULL
,
2775 &PyTuple_GET_ITEM(arg
, 0), PyTuple_Size(arg
),
2787 #define SLICE_ERROR_MSG \
2788 "standard sequence type does not support step size other than one"
2791 loop_subscript(PyObject
*v
, PyObject
*w
)
2793 PySequenceMethods
*sq
= v
->ob_type
->tp_as_sequence
;
2795 if (sq
== NULL
|| sq
->sq_item
== NULL
) {
2796 PyErr_SetString(PyExc_TypeError
, "loop over non-sequence");
2799 i
= PyInt_AsLong(w
);
2800 v
= (*sq
->sq_item
)(v
, i
);
2803 if (PyErr_ExceptionMatches(PyExc_IndexError
))
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
)
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
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
2835 /* Create a long integer with a value of 0 */
2836 long_zero
= PyLong_FromLong( 0L );
2837 if (long_zero
== NULL
) return 0;
2840 if (PyObject_Compare(long_zero
, v
) < 0)
2845 /* Free the long integer we created, and clear the
2847 Py_DECREF(long_zero
);
2851 PyErr_SetString(PyExc_TypeError
,
2852 "slice index must be int");
2855 /* Truncate -- very long indices are truncated anyway */
2858 else if (x
< -INT_MAX
)
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
))
2871 if (!_PyEval_SliceIndex(w
, &ihigh
))
2873 return PySequence_GetSlice(u
, ilow
, ihigh
);
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
))
2882 if (!_PyEval_SliceIndex(w
, &ihigh
))
2885 return PySequence_DelSlice(u
, ilow
, ihigh
);
2887 return PySequence_SetSlice(u
, ilow
, ihigh
, x
);
2891 cmp_outcome(int op
, register PyObject
*v
, register PyObject
*w
)
2894 register int res
= 0;
2899 if (op
== (int) IS_NOT
)
2904 res
= PySequence_Contains(w
, v
);
2907 if (op
== (int) NOT_IN
)
2911 res
= PyErr_GivenExceptionMatches(v
, w
);
2914 cmp
= PyObject_Compare(v
, w
);
2915 if (cmp
&& PyErr_Occurred())
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
;
2933 import_from(PyObject
*v
, PyObject
*name
)
2936 if (!PyModule_Check(v
)) {
2937 PyErr_SetString(PyExc_TypeError
,
2938 "import-from requires module object");
2941 w
= PyModule_GetDict(v
); /* TDB: can this not fail ? */
2942 x
= PyDict_GetItem(w
, name
);
2944 PyErr_Format(PyExc_ImportError
,
2945 "cannot import name %.230s",
2946 PyString_AsString(name
));
2953 import_all_from(PyObject
*locals
, PyObject
*v
)
2956 PyObject
*name
, *value
;
2959 if (!PyModule_Check(v
)) {
2960 PyErr_SetString(PyExc_TypeError
,
2961 "import-from requires module object");
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] == '_')
2971 err
= PyDict_SetItem(locals
, name
, value
);
2980 build_class(PyObject
*methods
, PyObject
*bases
, PyObject
*name
)
2983 if (!PyTuple_Check(bases
)) {
2984 PyErr_SetString(PyExc_SystemError
,
2985 "build_class with non-tuple bases");
2988 if (!PyDict_Check(methods
)) {
2989 PyErr_SetString(PyExc_SystemError
,
2990 "build_class with non-dictionary");
2993 if (!PyString_Check(name
)) {
2994 PyErr_SetString(PyExc_SystemError
,
2995 "build_class with non-string name");
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
3011 PyObject
*basetype
= (PyObject
*)base
->ob_type
;
3012 PyObject
*callable
= NULL
;
3013 if (PyCallable_Check(basetype
))
3014 callable
= basetype
;
3016 callable
= PyObject_GetAttrString(
3020 PyObject
*newclass
= NULL
;
3021 args
= Py_BuildValue(
3022 "(OOO)", name
, bases
, methods
);
3024 newclass
= PyEval_CallObject(
3028 if (callable
!= basetype
) {
3029 Py_DECREF(callable
);
3033 PyErr_SetString(PyExc_TypeError
,
3034 "base is not a class object");
3038 return PyClass_New(bases
, methods
, name
);
3042 exec_statement(PyFrameObject
*f
, PyObject
*prog
, PyObject
*globals
,
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);
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();
3064 else if (locals
== Py_None
)
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");
3074 if (!PyDict_Check(globals
) || !PyDict_Check(locals
)) {
3075 PyErr_SetString(PyExc_TypeError
,
3076 "exec 2nd/3rd args must be dict or None");
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
);
3091 if (PyString_AsStringAndSize(prog
, &str
, NULL
))
3093 v
= PyRun_String(str
, Py_file_input
, globals
, locals
);
3096 PyFrame_LocalsToFast(f
, 0);
3104 format_exc_check_arg(PyObject
*exc
, char *format_str
, PyObject
*obj
)
3111 obj_str
= PyString_AsString(obj
);
3115 PyErr_Format(exc
, format_str
, obj_str
);
3118 #ifdef DYNAMIC_EXECUTION_PROFILE
3121 getarray(long a
[256])
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
]);
3132 PyList_SetItem(l
, i
, x
);
3134 for (i
= 0; i
< 256; i
++)
3140 _Py_GetDXProfile(PyObject
*self
, PyObject
*args
)
3143 return getarray(dxp
);
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
]);
3154 PyList_SetItem(l
, i
, x
);