diff options
Diffstat (limited to 'Python')
-rw-r--r-- | Python/ast.c | 12 | ||||
-rw-r--r-- | Python/bltinmodule.c | 18 | ||||
-rw-r--r-- | Python/ceval.c | 172 | ||||
-rw-r--r-- | Python/codecs.c | 4 | ||||
-rw-r--r-- | Python/compile.c | 19 | ||||
-rw-r--r-- | Python/dynload_hpux.c | 4 | ||||
-rw-r--r-- | Python/errors.c | 51 | ||||
-rw-r--r-- | Python/exceptions.c | 1943 | ||||
-rw-r--r-- | Python/getcwd.c | 4 | ||||
-rw-r--r-- | Python/graminit.c | 35 | ||||
-rw-r--r-- | Python/import.c | 75 | ||||
-rw-r--r-- | Python/mystrtoul.c | 238 | ||||
-rw-r--r-- | Python/pystrtod.c | 4 | ||||
-rw-r--r-- | Python/pythonrun.c | 12 | ||||
-rw-r--r-- | Python/structmember.c | 11 | ||||
-rw-r--r-- | Python/thread_nt.h | 4 |
16 files changed, 407 insertions, 2199 deletions
diff --git a/Python/ast.c b/Python/ast.c index 0b3b485465..f3e611b8e3 100644 --- a/Python/ast.c +++ b/Python/ast.c @@ -107,7 +107,7 @@ ast_error_finish(const char *filename) Py_DECREF(errstr); return; } - value = Py_BuildValue("(OO)", errstr, tmp); + value = PyTuple_Pack(2, errstr, tmp); Py_DECREF(errstr); Py_DECREF(tmp); if (!value) @@ -401,6 +401,9 @@ set_context(expr_ty e, expr_context_ty ctx, const node *n) case Repr_kind: expr_name = "repr"; break; + case IfExp_kind: + expr_name = "conditional expression"; + break; default: PyErr_Format(PyExc_SystemError, "unexpected expression in assignment %d (line %d)", @@ -1747,6 +1750,11 @@ ast_for_call(struct compiling *c, const node *n, expr_ty func) if (TYPE(ch) == argument) { expr_ty e; if (NCH(ch) == 1) { + if (nkeywords) { + ast_error(CHILD(ch, 0), + "non-keyword arg after keyword arg"); + return NULL; + } e = ast_for_expr(c, CHILD(ch, 0)); if (!e) return NULL; @@ -3034,7 +3042,7 @@ decode_unicode(const char *s, size_t len, int rawmode, const char *encoding) if (*s & 0x80) { /* XXX inefficient */ PyObject *w; char *r; - int rn, i; + Py_ssize_t rn, i; w = decode_utf8(&s, end, "utf-16-be"); if (w == NULL) { Py_DECREF(u); diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 54e8fe832d..8f1f464a75 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -1260,6 +1260,18 @@ Return the octal representation of an integer or long integer."); static PyObject * +builtin_open(PyObject *self, PyObject *args, PyObject *kwds) +{ + return PyObject_Call((PyObject*)&PyFile_Type, args, kwds); +} + +PyDoc_STRVAR(open_doc, +"open(name[, mode[, buffering]]) -> file object\n\ +\n\ +Open a file using the file() type, returns a file object."); + + +static PyObject * builtin_ord(PyObject *self, PyObject* obj) { long ord; @@ -2080,6 +2092,7 @@ static PyMethodDef builtin_methods[] = { {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc}, {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc}, {"oct", builtin_oct, METH_O, oct_doc}, + {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc}, {"ord", builtin_ord, METH_O, ord_doc}, {"pow", builtin_pow, METH_VARARGS, pow_doc}, {"range", builtin_range, METH_VARARGS, range_doc}, @@ -2146,6 +2159,7 @@ _PyBuiltin_Init(void) #endif SETBUILTIN("dict", &PyDict_Type); SETBUILTIN("enumerate", &PyEnum_Type); + SETBUILTIN("file", &PyFile_Type); SETBUILTIN("float", &PyFloat_Type); SETBUILTIN("frozenset", &PyFrozenSet_Type); SETBUILTIN("property", &PyProperty_Type); @@ -2162,10 +2176,6 @@ _PyBuiltin_Init(void) SETBUILTIN("tuple", &PyTuple_Type); SETBUILTIN("type", &PyType_Type); SETBUILTIN("xrange", &PyRange_Type); - - /* Note that open() is just an alias of file(). */ - SETBUILTIN("open", &PyFile_Type); - SETBUILTIN("file", &PyFile_Type); #ifdef Py_USING_UNICODE SETBUILTIN("unicode", &PyUnicode_Type); #endif diff --git a/Python/ceval.c b/Python/ceval.c index 6c8afba1c5..80adc30ed4 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -6,6 +6,9 @@ XXX document it! */ +/* enable more aggressive intra-module optimizations, where available */ +#define PY_LOCAL_AGGRESSIVE + #include "Python.h" #include "code.h" @@ -16,7 +19,7 @@ #include <ctype.h> -#ifndef WITH_TSC +#ifndef WITH_TSC #define READ_TIMESTAMP(var) @@ -41,7 +44,7 @@ ppc_getcounter(uint64 *v) asm volatile ("mftbu %0" : "=r" (tbu2)); if (__builtin_expect(tbu != tbu2, 0)) goto loop; - /* The slightly peculiar way of writing the next lines is + /* The slightly peculiar way of writing the next lines is compiled better by GCC than any other way I tried. */ ((long*)(v))[0] = tbu; ((long*)(v))[1] = tb; @@ -54,7 +57,7 @@ ppc_getcounter(uint64 *v) #endif -void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, +void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1, uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1) { uint64 intr, inst, loop; @@ -83,16 +86,16 @@ typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *); /* Forward declarations */ #ifdef WITH_TSC -static PyObject *call_function(PyObject ***, int, uint64*, uint64*); +static PyObject * call_function(PyObject ***, int, uint64*, uint64*); #else -static PyObject *call_function(PyObject ***, int); +static PyObject * call_function(PyObject ***, int); #endif -static PyObject *fast_function(PyObject *, PyObject ***, int, int, int); -static PyObject *do_call(PyObject *, PyObject ***, int, int); -static PyObject *ext_do_call(PyObject *, PyObject ***, int, int, int); -static PyObject *update_keyword_args(PyObject *, int, PyObject ***,PyObject *); -static PyObject *update_star_args(int, int, PyObject *, PyObject ***); -static PyObject *load_args(PyObject ***, int); +static PyObject * fast_function(PyObject *, PyObject ***, int, int, int); +static PyObject * do_call(PyObject *, PyObject ***, int, int); +static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int); +static PyObject * update_keyword_args(PyObject *, int, PyObject ***,PyObject *); +static PyObject * update_star_args(int, int, PyObject *, PyObject ***); +static PyObject * load_args(PyObject ***, int); #define CALL_FLAG_VAR 1 #define CALL_FLAG_KW 2 @@ -108,19 +111,19 @@ static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *); static int maybe_call_line_trace(Py_tracefunc, PyObject *, PyFrameObject *, int *, int *, int *); -static PyObject *apply_slice(PyObject *, PyObject *, PyObject *); +static PyObject * apply_slice(PyObject *, PyObject *, PyObject *); static int assign_slice(PyObject *, PyObject *, PyObject *, PyObject *); -static PyObject *cmp_outcome(int, PyObject *, PyObject *); -static PyObject *import_from(PyObject *, PyObject *); +static PyObject * cmp_outcome(int, PyObject *, PyObject *); +static PyObject * import_from(PyObject *, PyObject *); static int import_all_from(PyObject *, PyObject *); -static PyObject *build_class(PyObject *, PyObject *, PyObject *); +static PyObject * build_class(PyObject *, PyObject *, PyObject *); static int exec_statement(PyFrameObject *, PyObject *, PyObject *, PyObject *); static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *); static void reset_exc_info(PyThreadState *); static void format_exc_check_arg(PyObject *, char *, PyObject *); -static PyObject *string_concatenate(PyObject *, PyObject *, +static PyObject * string_concatenate(PyObject *, PyObject *, PyFrameObject *, unsigned char *); #define NAME_ERROR_MSG \ @@ -559,7 +562,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) inst0 -- beginning of switch statement for opcode dispatch inst1 -- end of switch statement (may be skipped) loop0 -- the top of the mainloop - loop1 -- place where control returns again to top of mainloop + loop1 -- place where control returns again to top of mainloop (may be skipped) intr1 -- beginning of long interruption intr2 -- end of long interruption @@ -654,11 +657,11 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) #ifdef LLTRACE #define PUSH(v) { (void)(BASIC_PUSH(v), \ lltrace && prtrace(TOP(), "push")); \ - assert(STACK_LEVEL() <= f->f_stacksize); } + assert(STACK_LEVEL() <= co->co_stacksize); } #define POP() ((void)(lltrace && prtrace(TOP(), "pop")), BASIC_POP()) #define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \ lltrace && prtrace(TOP(), "stackadj")); \ - assert(STACK_LEVEL() <= f->f_stacksize); } + assert(STACK_LEVEL() <= co->co_stacksize); } #define EXT_POP(STACK_POINTER) (lltrace && prtrace(*(STACK_POINTER), "ext_pop"), *--(STACK_POINTER)) #else #define PUSH(v) BASIC_PUSH(v) @@ -729,7 +732,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) names = co->co_names; consts = co->co_consts; fastlocals = f->f_localsplus; - freevars = f->f_localsplus + f->f_nlocals; + freevars = f->f_localsplus + co->co_nlocals; first_instr = (unsigned char*) PyString_AS_STRING(co->co_code); /* An explanation is in order for the next line. @@ -760,7 +763,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) why = WHY_EXCEPTION; goto on_error; } - + for (;;) { #ifdef WITH_TSC if (inst1 == 0) { @@ -780,7 +783,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) READ_TIMESTAMP(loop0); #endif assert(stack_pointer >= f->f_valuestack); /* else underflow */ - assert(STACK_LEVEL() <= f->f_stacksize); /* else overflow */ + assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */ /* Do periodic things. Doing this every time through the loop would add too much overhead, so we do it @@ -1534,7 +1537,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) /* XXX move into writeobject() ? */ if (PyString_Check(v)) { char *s = PyString_AS_STRING(v); - int len = PyString_GET_SIZE(v); + Py_ssize_t len = PyString_GET_SIZE(v); if (len == 0 || !isspace(Py_CHARMASK(s[len-1])) || s[len-1] == ' ') @@ -1543,7 +1546,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) #ifdef Py_USING_UNICODE else if (PyUnicode_Check(v)) { Py_UNICODE *s = PyUnicode_AS_UNICODE(v); - int len = PyUnicode_GET_SIZE(v); + Py_ssize_t len = PyUnicode_GET_SIZE(v); if (len == 0 || !Py_UNICODE_ISSPACE(s[len-1]) || s[len-1] == ' ') @@ -1890,17 +1893,17 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) /* Don't stomp existing exception */ if (PyErr_Occurred()) break; - if (oparg < f->f_ncells) { - v = PyTuple_GetItem(co->co_cellvars, + if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) { + v = PyTuple_GET_ITEM(co->co_cellvars, oparg); format_exc_check_arg( PyExc_UnboundLocalError, UNBOUNDLOCAL_ERROR_MSG, v); } else { - v = PyTuple_GetItem( + v = PyTuple_GET_ITEM( co->co_freevars, - oparg - f->f_ncells); + oparg - PyTuple_GET_SIZE(co->co_cellvars)); format_exc_check_arg( PyExc_NameError, UNBOUNDFREE_ERROR_MSG, @@ -2147,6 +2150,10 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) case CONTINUE_LOOP: retval = PyInt_FromLong(oparg); + if (!retval) { + x = NULL; + break; + } why = WHY_CONTINUE; goto fast_block_end; @@ -2180,7 +2187,7 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag) re-raising the exception. (But non-local gotos should still be resumed.) */ - + x = TOP(); u = SECOND(); if (PyInt_Check(u) || u == Py_None) { @@ -2543,7 +2550,12 @@ fast_yield: } } - reset_exc_info(tstate); + if (tstate->frame->f_exc_type != NULL) + reset_exc_info(tstate); + else { + assert(tstate->frame->f_exc_value == NULL); + assert(tstate->frame->f_exc_traceback == NULL); + } /* pop frame */ exit_eval_frame: @@ -2580,7 +2592,7 @@ PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, return NULL; fastlocals = f->f_localsplus; - freevars = f->f_localsplus + f->f_nlocals; + freevars = f->f_localsplus + co->co_nlocals; if (co->co_argcount > 0 || co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) { @@ -2716,7 +2728,7 @@ PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, } /* Allocate and initialize storage for cell vars, and copy free vars into frame. This isn't too efficient right now. */ - if (f->f_ncells) { + if (PyTuple_GET_SIZE(co->co_cellvars)) { int i = 0, j = 0, nargs, found; char *cellname, *argname; PyObject *c; @@ -2734,7 +2746,7 @@ PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, that are arguments at the beginning of the cellvars list so that we can march over it more efficiently? */ - for (i = 0; i < f->f_ncells; ++i) { + for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) { cellname = PyString_AS_STRING( PyTuple_GET_ITEM(co->co_cellvars, i)); found = 0; @@ -2745,7 +2757,7 @@ PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, c = PyCell_New(GETLOCAL(j)); if (c == NULL) goto fail; - GETLOCAL(f->f_nlocals + i) = c; + GETLOCAL(co->co_nlocals + i) = c; found = 1; break; } @@ -2754,16 +2766,16 @@ PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, c = PyCell_New(NULL); if (c == NULL) goto fail; - SETLOCAL(f->f_nlocals + i, c); + SETLOCAL(co->co_nlocals + i, c); } } } - if (f->f_nfreevars) { + if (PyTuple_GET_SIZE(co->co_freevars)) { int i; - for (i = 0; i < f->f_nfreevars; ++i) { + for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) { PyObject *o = PyTuple_GET_ITEM(closure, i); Py_INCREF(o); - freevars[f->f_ncells + i] = o; + freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o; } } @@ -2808,6 +2820,7 @@ PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, - Once an exception is caught by an except clause, it is transferred from tstate->curexc_ZZZ to tstate->exc_ZZZ, from which sys.exc_info() can pick it up. This is the primary task of set_exc_info(). + XXX That can't be right: set_exc_info() doesn't look at tstate->curexc_ZZZ. - Now let me explain the complicated dance with frame->f_exc_ZZZ. @@ -2862,35 +2875,33 @@ static void set_exc_info(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { - PyFrameObject *frame; + PyFrameObject *frame = tstate->frame; PyObject *tmp_type, *tmp_value, *tmp_tb; - frame = tstate->frame; + assert(type != NULL); + assert(frame != NULL); if (frame->f_exc_type == NULL) { - /* This frame didn't catch an exception before */ - /* Save previous exception of this thread in this frame */ + assert(frame->f_exc_value == NULL); + assert(frame->f_exc_traceback == NULL); + /* This frame didn't catch an exception before. */ + /* Save previous exception of this thread in this frame. */ if (tstate->exc_type == NULL) { + /* XXX Why is this set to Py_None? */ Py_INCREF(Py_None); tstate->exc_type = Py_None; } - tmp_type = frame->f_exc_type; - tmp_value = frame->f_exc_value; - tmp_tb = frame->f_exc_traceback; - Py_XINCREF(tstate->exc_type); + Py_INCREF(tstate->exc_type); Py_XINCREF(tstate->exc_value); Py_XINCREF(tstate->exc_traceback); frame->f_exc_type = tstate->exc_type; frame->f_exc_value = tstate->exc_value; frame->f_exc_traceback = tstate->exc_traceback; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); } - /* Set new exception for this thread */ + /* Set new exception for this thread. */ tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; - Py_XINCREF(type); + Py_INCREF(type); Py_XINCREF(value); Py_XINCREF(tb); tstate->exc_type = type; @@ -2910,33 +2921,42 @@ reset_exc_info(PyThreadState *tstate) { PyFrameObject *frame; PyObject *tmp_type, *tmp_value, *tmp_tb; + + /* It's a precondition that the thread state's frame caught an + * exception -- verify in a debug build. + */ + assert(tstate != NULL); frame = tstate->frame; - if (frame->f_exc_type != NULL) { - /* This frame caught an exception */ - tmp_type = tstate->exc_type; - tmp_value = tstate->exc_value; - tmp_tb = tstate->exc_traceback; - Py_XINCREF(frame->f_exc_type); - Py_XINCREF(frame->f_exc_value); - Py_XINCREF(frame->f_exc_traceback); - tstate->exc_type = frame->f_exc_type; - tstate->exc_value = frame->f_exc_value; - tstate->exc_traceback = frame->f_exc_traceback; - Py_XDECREF(tmp_type); - Py_XDECREF(tmp_value); - Py_XDECREF(tmp_tb); - /* For b/w compatibility */ - PySys_SetObject("exc_type", frame->f_exc_type); - PySys_SetObject("exc_value", frame->f_exc_value); - PySys_SetObject("exc_traceback", frame->f_exc_traceback); - } + assert(frame != NULL); + assert(frame->f_exc_type != NULL); + + /* Copy the frame's exception info back to the thread state. */ + tmp_type = tstate->exc_type; + tmp_value = tstate->exc_value; + tmp_tb = tstate->exc_traceback; + Py_INCREF(frame->f_exc_type); + Py_XINCREF(frame->f_exc_value); + Py_XINCREF(frame->f_exc_traceback); + tstate->exc_type = frame->f_exc_type; + tstate->exc_value = frame->f_exc_value; + tstate->exc_traceback = frame->f_exc_traceback; + Py_XDECREF(tmp_type); + Py_XDECREF(tmp_value); + Py_XDECREF(tmp_tb); + + /* For b/w compatibility */ + PySys_SetObject("exc_type", frame->f_exc_type); + PySys_SetObject("exc_value", frame->f_exc_value); + PySys_SetObject("exc_traceback", frame->f_exc_traceback); + + /* Clear the frame's exception info. */ tmp_type = frame->f_exc_type; tmp_value = frame->f_exc_value; tmp_tb = frame->f_exc_traceback; frame->f_exc_type = NULL; frame->f_exc_value = NULL; frame->f_exc_traceback = NULL; - Py_XDECREF(tmp_type); + Py_DECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } @@ -3800,7 +3820,7 @@ _PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi) Py_ssize_t x; if (PyInt_Check(v)) { x = PyInt_AsSsize_t(v); - } + } else if (v->ob_type->tp_as_number && PyType_HasFeature(v->ob_type, Py_TPFLAGS_HAVE_INDEX) && v->ob_type->tp_as_number->nb_index) { @@ -4015,10 +4035,10 @@ build_class(PyObject *methods, PyObject *bases, PyObject *name) metaclass = (PyObject *) &PyType_Type; Py_INCREF(metaclass); } - result = PyObject_CallFunction(metaclass, "OOO", name, bases, methods); + result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, NULL); Py_DECREF(metaclass); if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) { - /* A type error here likely means that the user passed + /* A type error here likely means that the user passed in a base that was not a class (such the random module instead of the random.random type). Help them out with by augmenting the error message with more information.*/ @@ -4158,7 +4178,7 @@ string_concatenate(PyObject *v, PyObject *w, { /* This function implements 'variable += expr' when both arguments are strings. */ - + if (v->ob_refcnt == 2) { /* In the common case, there are 2 references to the value * stored in 'variable' when the += is performed: one on the @@ -4176,7 +4196,7 @@ string_concatenate(PyObject *v, PyObject *w, } case STORE_DEREF: { - PyObject **freevars = f->f_localsplus + f->f_nlocals; + PyObject **freevars = f->f_localsplus + f->f_code->co_nlocals; PyObject *c = freevars[PEEKARG()]; if (PyCell_GET(c) == v) PyCell_Set(c, NULL); diff --git a/Python/codecs.c b/Python/codecs.c index 2124824f6c..046abe3507 100644 --- a/Python/codecs.c +++ b/Python/codecs.c @@ -70,7 +70,7 @@ PyObject *normalizestring(const char *string) if (ch == ' ') ch = '-'; else - ch = tolower(ch); + ch = tolower(Py_CHARMASK(ch)); p[i] = ch; } return v; @@ -95,7 +95,7 @@ PyObject *_PyCodec_Lookup(const char *encoding) { PyInterpreterState *interp; PyObject *result, *args = NULL, *v; - int i, len; + Py_ssize_t i, len; if (encoding == NULL) { PyErr_BadArgument(); diff --git a/Python/compile.c b/Python/compile.c index 12b190a764..199cac5ac5 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -334,7 +334,7 @@ list2dict(PyObject *list) return NULL; } k = PyList_GET_ITEM(list, i); - k = Py_BuildValue("(OO)", k, k->ob_type); + k = PyTuple_Pack(2, k, k->ob_type); if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { Py_XDECREF(k); Py_DECREF(v); @@ -377,7 +377,7 @@ dictbytype(PyObject *src, int scope_type, int flag, int offset) return NULL; } i++; - tuple = Py_BuildValue("(OO)", k, k->ob_type); + tuple = PyTuple_Pack(2, k, k->ob_type); if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { Py_DECREF(item); Py_DECREF(dest); @@ -1834,7 +1834,7 @@ static int compiler_lookup_arg(PyObject *dict, PyObject *name) { PyObject *k, *v; - k = Py_BuildValue("(OO)", name, name->ob_type); + k = PyTuple_Pack(2, name, name->ob_type); if (k == NULL) return -1; v = PyDict_GetItem(dict, k); @@ -3349,7 +3349,7 @@ expr_constant(expr_ty e) It is implemented roughly as: - context = (EXPR).__context__() + context = EXPR exit = context.__exit__ # not calling it value = context.__enter__() try: @@ -3365,17 +3365,12 @@ expr_constant(expr_ty e) static int compiler_with(struct compiler *c, stmt_ty s) { - static identifier context_attr, enter_attr, exit_attr; + static identifier enter_attr, exit_attr; basicblock *block, *finally; identifier tmpexit, tmpvalue = NULL; assert(s->kind == With_kind); - if (!context_attr) { - context_attr = PyString_InternFromString("__context__"); - if (!context_attr) - return 0; - } if (!enter_attr) { enter_attr = PyString_InternFromString("__enter__"); if (!enter_attr) @@ -3414,10 +3409,8 @@ compiler_with(struct compiler *c, stmt_ty s) PyArena_AddPyObject(c->c_arena, tmpvalue); } - /* Evaluate (EXPR).__context__() */ + /* Evaluate EXPR */ VISIT(c, expr, s->v.With.context_expr); - ADDOP_O(c, LOAD_ATTR, context_attr, names); - ADDOP_I(c, CALL_FUNCTION, 0); /* Squirrel away context.__exit__ */ ADDOP(c, DUP_TOP); diff --git a/Python/dynload_hpux.c b/Python/dynload_hpux.c index b4de08146c..fec0826ca6 100644 --- a/Python/dynload_hpux.c +++ b/Python/dynload_hpux.c @@ -14,8 +14,8 @@ #endif const struct filedescr _PyImport_DynLoadFiletab[] = { - {".sl", "rb", C_EXTENSION}, - {"module.sl", "rb", C_EXTENSION}, + {SHLIB_EXT, "rb", C_EXTENSION}, + {"module"SHLIB_EXT, "rb", C_EXTENSION}, {0, 0} }; diff --git a/Python/errors.c b/Python/errors.c index 2ae062fde4..c391d3389a 100644 --- a/Python/errors.c +++ b/Python/errors.c @@ -536,6 +536,7 @@ PyErr_Format(PyObject *exception, const char *format, ...) } + PyObject * PyErr_NewException(char *name, PyObject *base, PyObject *dict) { @@ -565,14 +566,18 @@ PyErr_NewException(char *name, PyObject *base, PyObject *dict) if (PyDict_SetItemString(dict, "__module__", modulename) != 0) goto failure; } - classname = PyString_FromString(dot+1); - if (classname == NULL) - goto failure; - bases = PyTuple_Pack(1, base); - if (bases == NULL) - goto failure; - result = PyObject_CallFunction((PyObject *) (base->ob_type), - "OOO", classname, bases, dict); + if (PyTuple_Check(base)) { + bases = base; + /* INCREF as we create a new ref in the else branch */ + Py_INCREF(bases); + } else { + bases = PyTuple_Pack(1, base); + if (bases == NULL) + goto failure; + } + /* Create a real new-style class. */ + result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO", + dot+1, bases, dict); failure: Py_XDECREF(bases); Py_XDECREF(mydict); @@ -593,8 +598,11 @@ PyErr_WriteUnraisable(PyObject *obj) PyFile_WriteString("Exception ", f); if (t) { char* className = PyExceptionClass_Name(t); - PyObject* moduleName = - PyObject_GetAttrString(t, "__module__"); + PyObject* moduleName; + char *dot = strrchr(className, '.'); + if (dot != NULL) + className = dot+1; + moduleName = PyObject_GetAttrString(t, "__module__"); if (moduleName == NULL) PyFile_WriteString("<unknown>", f); @@ -644,15 +652,11 @@ PyErr_Warn(PyObject *category, char *message) return 0; } else { - PyObject *args, *res; + PyObject *res; if (category == NULL) category = PyExc_RuntimeWarning; - args = Py_BuildValue("(sO)", message, category); - if (args == NULL) - return -1; - res = PyEval_CallObject(func, args); - Py_DECREF(args); + res = PyObject_CallFunction(func, "sO", message, category); if (res == NULL) return -1; Py_DECREF(res); @@ -680,18 +684,14 @@ PyErr_WarnExplicit(PyObject *category, const char *message, return 0; } else { - PyObject *args, *res; + PyObject *res; if (category == NULL) category = PyExc_RuntimeWarning; if (registry == NULL) registry = Py_None; - args = Py_BuildValue("(sOsizO)", message, category, - filename, lineno, module, registry); - if (args == NULL) - return -1; - res = PyEval_CallObject(func, args); - Py_DECREF(args); + res = PyObject_CallFunction(func, "sOsizO", message, category, + filename, lineno, module, registry); if (res == NULL) return -1; Py_DECREF(res); @@ -712,7 +712,8 @@ PyErr_SyntaxLocation(const char *filename, int lineno) /* add attributes for the line number and filename for the error */ PyErr_Fetch(&exc, &v, &tb); PyErr_NormalizeException(&exc, &v, &tb); - /* XXX check that it is, indeed, a syntax error */ + /* XXX check that it is, indeed, a syntax error. It might not + * be, though. */ tmp = PyInt_FromLong(lineno); if (tmp == NULL) PyErr_Clear(); @@ -788,7 +789,7 @@ PyErr_ProgramText(const char *filename, int lineno) break; /* fgets read *something*; if it didn't get as far as pLastChar, it must have found a newline - or hit the end of the file; if pLastChar is \n, + or hit the end of the file; if pLastChar is \n, it obviously found a newline; else we haven't yet seen a newline, so must continue */ } while (*pLastChar != '\0' && *pLastChar != '\n'); diff --git a/Python/exceptions.c b/Python/exceptions.c deleted file mode 100644 index 5c824e650c..0000000000 --- a/Python/exceptions.c +++ /dev/null @@ -1,1943 +0,0 @@ -/* This module provides the suite of standard class-based exceptions for - * Python's builtin module. This is a complete C implementation of what, - * in Python 1.5.2, was contained in the exceptions.py module. The problem - * there was that if exceptions.py could not be imported for some reason, - * the entire interpreter would abort. - * - * By moving the exceptions into C and statically linking, we can guarantee - * that the standard exceptions will always be available. - * - * - * written by Fredrik Lundh - * modifications, additions, cleanups, and proofreading by Barry Warsaw - * - * Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved. - */ - -#define PY_SSIZE_T_CLEAN -#include "Python.h" -#include "osdefs.h" - -/* Caution: MS Visual C++ 6 errors if a single string literal exceeds - * 2Kb. So the module docstring has been broken roughly in half, using - * compile-time literal concatenation. - */ - -/* NOTE: If the exception class hierarchy changes, don't forget to update - * Doc/lib/libexcs.tex! - */ - -PyDoc_STRVAR(module__doc__, -"Python's standard exception class hierarchy.\n\ -\n\ -Exceptions found here are defined both in the exceptions module and the \n\ -built-in namespace. It is recommended that user-defined exceptions inherit \n\ -from Exception. See the documentation for the exception inheritance hierarchy.\n\ -" - - /* keep string pieces "small" */ -/* XXX(bcannon): exception hierarchy in Lib/test/exception_hierarchy.txt */ -); - - -/* Helper function for populating a dictionary with method wrappers. */ -static int -populate_methods(PyObject *klass, PyMethodDef *methods) -{ - PyObject *module; - int status = -1; - - if (!methods) - return 0; - - module = PyString_FromString("exceptions"); - if (!module) - return 0; - while (methods->ml_name) { - /* get a wrapper for the built-in function */ - PyObject *func = PyCFunction_NewEx(methods, NULL, module); - PyObject *meth; - - if (!func) - goto status; - - /* turn the function into an unbound method */ - if (!(meth = PyMethod_New(func, NULL, klass))) { - Py_DECREF(func); - goto status; - } - - /* add method to dictionary */ - status = PyObject_SetAttrString(klass, methods->ml_name, meth); - Py_DECREF(meth); - Py_DECREF(func); - - /* stop now if an error occurred, otherwise do the next method */ - if (status) - goto status; - - methods++; - } - status = 0; - status: - Py_DECREF(module); - return status; -} - - - -/* This function is used to create all subsequent exception classes. */ -static int -make_class(PyObject **klass, PyObject *base, - char *name, PyMethodDef *methods, - char *docstr) -{ - PyObject *dict = PyDict_New(); - PyObject *str = NULL; - int status = -1; - - if (!dict) - return -1; - - /* If an error occurs from here on, goto finally instead of explicitly - * returning NULL. - */ - - if (docstr) { - if (!(str = PyString_FromString(docstr))) - goto finally; - if (PyDict_SetItemString(dict, "__doc__", str)) - goto finally; - } - - if (!(*klass = PyErr_NewException(name, base, dict))) - goto finally; - - if (populate_methods(*klass, methods)) { - Py_DECREF(*klass); - *klass = NULL; - goto finally; - } - - status = 0; - - finally: - Py_XDECREF(dict); - Py_XDECREF(str); - return status; -} - - -/* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */ -static PyObject * -get_self(PyObject *args) -{ - PyObject *self = PyTuple_GetItem(args, 0); - if (!self) { - /* Watch out for being called to early in the bootstrapping process */ - if (PyExc_TypeError) { - PyErr_SetString(PyExc_TypeError, - "unbound method must be called with instance as first argument"); - } - return NULL; - } - return self; -} - - - -/* Notes on bootstrapping the exception classes. - * - * First thing we create is the base class for all exceptions, called - * appropriately BaseException. Creation of this class makes no - * assumptions about the existence of any other exception class -- except - * for TypeError, which can conditionally exist. - * - * Next, Exception is created since it is the common subclass for the rest of - * the needed exceptions for this bootstrapping to work. StandardError is - * created (which is quite simple) followed by - * TypeError, because the instantiation of other exceptions can potentially - * throw a TypeError. Once these exceptions are created, all the others - * can be created in any order. See the static exctable below for the - * explicit bootstrap order. - * - * All classes after BaseException can be created using PyErr_NewException(). - */ - -PyDoc_STRVAR(BaseException__doc__, "Common base class for all exceptions"); - -/* - Set args and message attributes. - - Assumes self and args have already been set properly with set_self, etc. -*/ -static int -set_args_and_message(PyObject *self, PyObject *args) -{ - PyObject *message_val; - Py_ssize_t args_len = PySequence_Length(args); - - if (args_len < 0) - return 0; - - /* set args */ - if (PyObject_SetAttrString(self, "args", args) < 0) - return 0; - - /* set message */ - if (args_len == 1) - message_val = PySequence_GetItem(args, 0); - else - message_val = PyString_FromString(""); - if (!message_val) - return 0; - - if (PyObject_SetAttrString(self, "message", message_val) < 0) { - Py_DECREF(message_val); - return 0; - } - - Py_DECREF(message_val); - return 1; -} - -static PyObject * -BaseException__init__(PyObject *self, PyObject *args) -{ - if (!(self = get_self(args))) - return NULL; - - /* set args and message attribute */ - args = PySequence_GetSlice(args, 1, PySequence_Length(args)); - if (!args) - return NULL; - - if (!set_args_and_message(self, args)) { - Py_DECREF(args); - return NULL; - } - - Py_DECREF(args); - Py_RETURN_NONE; -} - - -static PyObject * -BaseException__str__(PyObject *self, PyObject *args) -{ - PyObject *out; - - if (!PyArg_ParseTuple(args, "O:__str__", &self)) - return NULL; - - args = PyObject_GetAttrString(self, "args"); - if (!args) - return NULL; - - switch (PySequence_Size(args)) { - case 0: - out = PyString_FromString(""); - break; - case 1: - { - PyObject *tmp = PySequence_GetItem(args, 0); - if (tmp) { - out = PyObject_Str(tmp); - Py_DECREF(tmp); - } - else - out = NULL; - break; - } - case -1: - PyErr_Clear(); - /* Fall through */ - default: - out = PyObject_Str(args); - break; - } - - Py_DECREF(args); - return out; -} - -#ifdef Py_USING_UNICODE -static PyObject * -BaseException__unicode__(PyObject *self, PyObject *args) -{ - Py_ssize_t args_len; - - if (!PyArg_ParseTuple(args, "O:__unicode__", &self)) - return NULL; - - args = PyObject_GetAttrString(self, "args"); - if (!args) - return NULL; - - args_len = PySequence_Size(args); - if (args_len < 0) { - Py_DECREF(args); - return NULL; - } - - if (args_len == 0) { - Py_DECREF(args); - return PyUnicode_FromUnicode(NULL, 0); - } - else if (args_len == 1) { - PyObject *temp = PySequence_GetItem(args, 0); - PyObject *unicode_obj; - - if (!temp) { - Py_DECREF(args); - return NULL; - } - Py_DECREF(args); - unicode_obj = PyObject_Unicode(temp); - Py_DECREF(temp); - return unicode_obj; - } - else { - PyObject *unicode_obj = PyObject_Unicode(args); - - Py_DECREF(args); - return unicode_obj; - } -} -#endif /* Py_USING_UNICODE */ - -static PyObject * -BaseException__repr__(PyObject *self, PyObject *args) -{ - PyObject *args_attr; - Py_ssize_t args_len; - PyObject *repr_suffix; - PyObject *repr; - - if (!PyArg_ParseTuple(args, "O:__repr__", &self)) - return NULL; - - args_attr = PyObject_GetAttrString(self, "args"); - if (!args_attr) - return NULL; - - args_len = PySequence_Length(args_attr); - if (args_len < 0) { - Py_DECREF(args_attr); - return NULL; - } - - if (args_len == 0) { - Py_DECREF(args_attr); - repr_suffix = PyString_FromString("()"); - if (!repr_suffix) - return NULL; - } - else { - PyObject *args_repr = PyObject_Repr(args_attr); - Py_DECREF(args_attr); - if (!args_repr) - return NULL; - - repr_suffix = args_repr; - } - - repr = PyString_FromString(self->ob_type->tp_name); - if (!repr) { - Py_DECREF(repr_suffix); - return NULL; - } - - PyString_ConcatAndDel(&repr, repr_suffix); - return repr; -} - -static PyObject * -BaseException__getitem__(PyObject *self, PyObject *args) -{ - PyObject *out; - PyObject *index; - - if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index)) - return NULL; - - args = PyObject_GetAttrString(self, "args"); - if (!args) - return NULL; - - out = PyObject_GetItem(args, index); - Py_DECREF(args); - return out; -} - - -static PyMethodDef -BaseException_methods[] = { - /* methods for the BaseException class */ - {"__getitem__", BaseException__getitem__, METH_VARARGS}, - {"__repr__", BaseException__repr__, METH_VARARGS}, - {"__str__", BaseException__str__, METH_VARARGS}, -#ifdef Py_USING_UNICODE - {"__unicode__", BaseException__unicode__, METH_VARARGS}, -#endif /* Py_USING_UNICODE */ - {"__init__", BaseException__init__, METH_VARARGS}, - {NULL, NULL } -}; - - -static int -make_BaseException(char *modulename) -{ - PyObject *dict = PyDict_New(); - PyObject *str = NULL; - PyObject *name = NULL; - PyObject *emptytuple = NULL; - PyObject *argstuple = NULL; - int status = -1; - - if (!dict) - return -1; - - /* If an error occurs from here on, goto finally instead of explicitly - * returning NULL. - */ - - if (!(str = PyString_FromString(modulename))) - goto finally; - if (PyDict_SetItemString(dict, "__module__", str)) - goto finally; - Py_DECREF(str); - - if (!(str = PyString_FromString(BaseException__doc__))) - goto finally; - if (PyDict_SetItemString(dict, "__doc__", str)) - goto finally; - - if (!(name = PyString_FromString("BaseException"))) - goto finally; - - if (!(emptytuple = PyTuple_New(0))) - goto finally; - - if (!(argstuple = PyTuple_Pack(3, name, emptytuple, dict))) - goto finally; - - if (!(PyExc_BaseException = PyType_Type.tp_new(&PyType_Type, argstuple, - NULL))) - goto finally; - - /* Now populate the dictionary with the method suite */ - if (populate_methods(PyExc_BaseException, BaseException_methods)) - /* Don't need to reclaim PyExc_BaseException here because that'll - * happen during interpreter shutdown. - */ - goto finally; - - status = 0; - - finally: - Py_XDECREF(dict); - Py_XDECREF(str); - Py_XDECREF(name); - Py_XDECREF(emptytuple); - Py_XDECREF(argstuple); - return status; -} - - - -PyDoc_STRVAR(Exception__doc__, "Common base class for all non-exit exceptions."); - -PyDoc_STRVAR(StandardError__doc__, -"Base class for all standard Python exceptions that do not represent" -"interpreter exiting."); - -PyDoc_STRVAR(TypeError__doc__, "Inappropriate argument type."); - -PyDoc_STRVAR(StopIteration__doc__, "Signal the end from iterator.next()."); -PyDoc_STRVAR(GeneratorExit__doc__, "Request that a generator exit."); - - - -PyDoc_STRVAR(SystemExit__doc__, "Request to exit from the interpreter."); - - -static PyObject * -SystemExit__init__(PyObject *self, PyObject *args) -{ - PyObject *code; - int status; - - if (!(self = get_self(args))) - return NULL; - - if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args)))) - return NULL; - - if (!set_args_and_message(self, args)) { - Py_DECREF(args); - return NULL; - } - - /* set code attribute */ - switch (PySequence_Size(args)) { - case 0: - Py_INCREF(Py_None); - code = Py_None; - break; - case 1: - code = PySequence_GetItem(args, 0); - break; - case -1: - PyErr_Clear(); - /* Fall through */ - default: - Py_INCREF(args); - code = args; - break; - } - - status = PyObject_SetAttrString(self, "code", code); - Py_DECREF(code); - Py_DECREF(args); - if (status < 0) - return NULL; - - Py_RETURN_NONE; -} - - -static PyMethodDef SystemExit_methods[] = { - { "__init__", SystemExit__init__, METH_VARARGS}, - {NULL, NULL} -}; - - - -PyDoc_STRVAR(KeyboardInterrupt__doc__, "Program interrupted by user."); - -PyDoc_STRVAR(ImportError__doc__, -"Import can't find module, or can't find name in module."); - - - -PyDoc_STRVAR(EnvironmentError__doc__, "Base class for I/O related errors."); - - -static PyObject * -EnvironmentError__init__(PyObject *self, PyObject *args) -{ - PyObject *item0 = NULL; - PyObject *item1 = NULL; - PyObject *item2 = NULL; - PyObject *subslice = NULL; - PyObject *rtnval = NULL; - - if (!(self = get_self(args))) - return NULL; - - if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args)))) - return NULL; - - if (!set_args_and_message(self, args)) { - Py_DECREF(args); - return NULL; - } - - if (PyObject_SetAttrString(self, "errno", Py_None) || - PyObject_SetAttrString(self, "strerror", Py_None) || - PyObject_SetAttrString(self, "filename", Py_None)) - { - goto finally; - } - - switch (PySequence_Size(args)) { - case 3: - /* Where a function has a single filename, such as open() or some - * of the os module functions, PyErr_SetFromErrnoWithFilename() is - * called, giving a third argument which is the filename. But, so - * that old code using in-place unpacking doesn't break, e.g.: - * - * except IOError, (errno, strerror): - * - * we hack args so that it only contains two items. This also - * means we need our own __str__() which prints out the filename - * when it was supplied. - */ - item0 = PySequence_GetItem(args, 0); - item1 = PySequence_GetItem(args, 1); - item2 = PySequence_GetItem(args, 2); - if (!item0 || !item1 || !item2) - goto finally; - - if (PyObject_SetAttrString(self, "errno", item0) || - PyObject_SetAttrString(self, "strerror", item1) || - PyObject_SetAttrString(self, "filename", item2)) - { - goto finally; - } - - subslice = PySequence_GetSlice(args, 0, 2); - if (!subslice || PyObject_SetAttrString(self, "args", subslice)) - goto finally; - break; - - case 2: - /* Used when PyErr_SetFromErrno() is called and no filename - * argument is given. - */ - item0 = PySequence_GetItem(args, 0); - item1 = PySequence_GetItem(args, 1); - if (!item0 || !item1) - goto finally; - - if (PyObject_SetAttrString(self, "errno", item0) || - PyObject_SetAttrString(self, "strerror", item1)) - { - goto finally; - } - break; - - case -1: - PyErr_Clear(); - break; - } - - Py_INCREF(Py_None); - rtnval = Py_None; - - finally: - Py_DECREF(args); - Py_XDECREF(item0); - Py_XDECREF(item1); - Py_XDECREF(item2); - Py_XDECREF(subslice); - return rtnval; -} - - -static PyObject * -EnvironmentError__str__(PyObject *self, PyObject *args) -{ - PyObject *originalself = self; - PyObject *filename; - PyObject *serrno; - PyObject *strerror; - PyObject *rtnval = NULL; - - if (!PyArg_ParseTuple(args, "O:__str__", &self)) - return NULL; - - filename = PyObject_GetAttrString(self, "filename"); - serrno = PyObject_GetAttrString(self, "errno"); - strerror = PyObject_GetAttrString(self, "strerror"); - if (!filename || !serrno || !strerror) - goto finally; - - if (filename != Py_None) { - PyObject *fmt = PyString_FromString("[Errno %s] %s: %s"); - PyObject *repr = PyObject_Repr(filename); - PyObject *tuple = PyTuple_New(3); - - if (!fmt || !repr || !tuple) { - Py_XDECREF(fmt); - Py_XDECREF(repr); - Py_XDECREF(tuple); - goto finally; - } - - PyTuple_SET_ITEM(tuple, 0, serrno); - PyTuple_SET_ITEM(tuple, 1, strerror); - PyTuple_SET_ITEM(tuple, 2, repr); - - rtnval = PyString_Format(fmt, tuple); - - Py_DECREF(fmt); - Py_DECREF(tuple); - /* already freed because tuple owned only reference */ - serrno = NULL; - strerror = NULL; - } - else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) { - PyObject *fmt = PyString_FromString("[Errno %s] %s"); - PyObject *tuple = PyTuple_New(2); - - if (!fmt || !tuple) { - Py_XDECREF(fmt); - Py_XDECREF(tuple); - goto finally; - } - - PyTuple_SET_ITEM(tuple, 0, serrno); - PyTuple_SET_ITEM(tuple, 1, strerror); - - rtnval = PyString_Format(fmt, tuple); - - Py_DECREF(fmt); - Py_DECREF(tuple); - /* already freed because tuple owned only reference */ - serrno = NULL; - strerror = NULL; - } - else - /* The original Python code said: - * - * return StandardError.__str__(self) - * - * but there is no StandardError__str__() function; we happen to - * know that's just a pass through to BaseException__str__(). - */ - rtnval = BaseException__str__(originalself, args); - - finally: - Py_XDECREF(filename); - Py_XDECREF(serrno); - Py_XDECREF(strerror); - return rtnval; -} - - -static -PyMethodDef EnvironmentError_methods[] = { - {"__init__", EnvironmentError__init__, METH_VARARGS}, - {"__str__", EnvironmentError__str__, METH_VARARGS}, - {NULL, NULL} -}; - - - - -PyDoc_STRVAR(IOError__doc__, "I/O operation failed."); - -PyDoc_STRVAR(OSError__doc__, "OS system call failed."); - -#ifdef MS_WINDOWS -PyDoc_STRVAR(WindowsError__doc__, "MS-Windows OS system call failed."); -#endif /* MS_WINDOWS */ - -#ifdef __VMS -static char -VMSError__doc__[] = "OpenVMS OS system call failed."; -#endif - -PyDoc_STRVAR(EOFError__doc__, "Read beyond end of file."); - -PyDoc_STRVAR(RuntimeError__doc__, "Unspecified run-time error."); - -PyDoc_STRVAR(NotImplementedError__doc__, -"Method or function hasn't been implemented yet."); - -PyDoc_STRVAR(NameError__doc__, "Name not found globally."); - -PyDoc_STRVAR(UnboundLocalError__doc__, -"Local name referenced but not bound to a value."); - -PyDoc_STRVAR(AttributeError__doc__, "Attribute not found."); - - - -PyDoc_STRVAR(SyntaxError__doc__, "Invalid syntax."); - - -static int -SyntaxError__classinit__(PyObject *klass) -{ - int retval = 0; - PyObject *emptystring = PyString_FromString(""); - - /* Additional class-creation time initializations */ - if (!emptystring || - PyObject_SetAttrString(klass, "msg", emptystring) || - PyObject_SetAttrString(klass, "filename", Py_None) || - PyObject_SetAttrString(klass, "lineno", Py_None) || - PyObject_SetAttrString(klass, "offset", Py_None) || - PyObject_SetAttrString(klass, "text", Py_None) || - PyObject_SetAttrString(klass, "print_file_and_line", Py_None)) - { - retval = -1; - } - Py_XDECREF(emptystring); - return retval; -} - - -static PyObject * -SyntaxError__init__(PyObject *self, PyObject *args) -{ - PyObject *rtnval = NULL; - Py_ssize_t lenargs; - - if (!(self = get_self(args))) - return NULL; - - if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args)))) - return NULL; - - if (!set_args_and_message(self, args)) { - Py_DECREF(args); - return NULL; - } - - lenargs = PySequence_Size(args); - if (lenargs >= 1) { - PyObject *item0 = PySequence_GetItem(args, 0); - int status; - - if (!item0) - goto finally; - status = PyObject_SetAttrString(self, "msg", item0); - Py_DECREF(item0); - if (status) - goto finally; - } - if (lenargs == 2) { - PyObject *info = PySequence_GetItem(args, 1); - PyObject *filename = NULL, *lineno = NULL; - PyObject *offset = NULL, *text = NULL; - int status = 1; - - if (!info) - goto finally; - - filename = PySequence_GetItem(info, 0); - if (filename != NULL) { - lineno = PySequence_GetItem(info, 1); - if (lineno != NULL) { - offset = PySequence_GetItem(info, 2); - if (offset != NULL) { - text = PySequence_GetItem(info, 3); - if (text != NULL) { - status = - PyObject_SetAttrString(self, "filename", filename) - || PyObject_SetAttrString(self, "lineno", lineno) - || PyObject_SetAttrString(self, "offset", offset) - || PyObject_SetAttrString(self, "text", text); - Py_DECREF(text); - } - Py_DECREF(offset); - } - Py_DECREF(lineno); - } - Py_DECREF(filename); - } - Py_DECREF(info); - - if (status) - goto finally; - } - Py_INCREF(Py_None); - rtnval = Py_None; - - finally: - Py_DECREF(args); - return rtnval; -} - - -/* This is called "my_basename" instead of just "basename" to avoid name - conflicts with glibc; basename is already prototyped if _GNU_SOURCE is - defined, and Python does define that. */ -static char * -my_basename(char *name) -{ - char *cp = name; - char *result = name; - - if (name == NULL) - return "???"; - while (*cp != '\0') { - if (*cp == SEP) - result = cp + 1; - ++cp; - } - return result; -} - - -static PyObject * -SyntaxError__str__(PyObject *self, PyObject *args) -{ - PyObject *msg; - PyObject *str; - PyObject *filename, *lineno, *result; - - if (!PyArg_ParseTuple(args, "O:__str__", &self)) - return NULL; - - if (!(msg = PyObject_GetAttrString(self, "msg"))) - return NULL; - - str = PyObject_Str(msg); - Py_DECREF(msg); - result = str; - - /* XXX -- do all the additional formatting with filename and - lineno here */ - - if (str != NULL && PyString_Check(str)) { - int have_filename = 0; - int have_lineno = 0; - char *buffer = NULL; - - if ((filename = PyObject_GetAttrString(self, "filename")) != NULL) - have_filename = PyString_Check(filename); - else - PyErr_Clear(); - - if ((lineno = PyObject_GetAttrString(self, "lineno")) != NULL) - have_lineno = PyInt_Check(lineno); - else - PyErr_Clear(); - - if (have_filename || have_lineno) { - Py_ssize_t bufsize = PyString_GET_SIZE(str) + 64; - if (have_filename) - bufsize += PyString_GET_SIZE(filename); - - buffer = (char *)PyMem_MALLOC(bufsize); - if (buffer != NULL) { - if (have_filename && have_lineno) - PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)", - PyString_AS_STRING(str), - my_basename(PyString_AS_STRING(filename)), - PyInt_AsLong(lineno)); - else if (have_filename) - PyOS_snprintf(buffer, bufsize, "%s (%s)", - PyString_AS_STRING(str), - my_basename(PyString_AS_STRING(filename))); - else if (have_lineno) - PyOS_snprintf(buffer, bufsize, "%s (line %ld)", - PyString_AS_STRING(str), - PyInt_AsLong(lineno)); - - result = PyString_FromString(buffer); - PyMem_FREE(buffer); - - if (result == NULL) - result = str; - else - Py_DECREF(str); - } - } - Py_XDECREF(filename); - Py_XDECREF(lineno); - } - return result; -} - - -static PyMethodDef SyntaxError_methods[] = { - {"__init__", SyntaxError__init__, METH_VARARGS}, - {"__str__", SyntaxError__str__, METH_VARARGS}, - {NULL, NULL} -}; - - -static PyObject * -KeyError__str__(PyObject *self, PyObject *args) -{ - PyObject *argsattr; - PyObject *result; - - if (!PyArg_ParseTuple(args, "O:__str__", &self)) - return NULL; - - argsattr = PyObject_GetAttrString(self, "args"); - if (!argsattr) - return NULL; - - /* If args is a tuple of exactly one item, apply repr to args[0]. - This is done so that e.g. the exception raised by {}[''] prints - KeyError: '' - rather than the confusing - KeyError - alone. The downside is that if KeyError is raised with an explanatory - string, that string will be displayed in quotes. Too bad. - If args is anything else, use the default BaseException__str__(). - */ - if (PyTuple_Check(argsattr) && PyTuple_GET_SIZE(argsattr) == 1) { - PyObject *key = PyTuple_GET_ITEM(argsattr, 0); - result = PyObject_Repr(key); - } - else - result = BaseException__str__(self, args); - - Py_DECREF(argsattr); - return result; -} - -static PyMethodDef KeyError_methods[] = { - {"__str__", KeyError__str__, METH_VARARGS}, - {NULL, NULL} -}; - - -#ifdef Py_USING_UNICODE -static -int get_int(PyObject *exc, const char *name, Py_ssize_t *value) -{ - PyObject *attr = PyObject_GetAttrString(exc, (char *)name); - - if (!attr) - return -1; - if (PyInt_Check(attr)) { - *value = PyInt_AS_LONG(attr); - } else if (PyLong_Check(attr)) { - *value = (size_t)PyLong_AsLongLong(attr); - if (*value == -1) { - Py_DECREF(attr); - return -1; - } - } else { - PyErr_Format(PyExc_TypeError, "%.200s attribute must be int", name); - Py_DECREF(attr); - return -1; - } - Py_DECREF(attr); - return 0; -} - - -static -int set_ssize_t(PyObject *exc, const char *name, Py_ssize_t value) -{ - PyObject *obj = PyInt_FromSsize_t(value); - int result; - - if (!obj) - return -1; - result = PyObject_SetAttrString(exc, (char *)name, obj); - Py_DECREF(obj); - return result; -} - -static -PyObject *get_string(PyObject *exc, const char *name) -{ - PyObject *attr = PyObject_GetAttrString(exc, (char *)name); - - if (!attr) - return NULL; - if (!PyString_Check(attr)) { - PyErr_Format(PyExc_TypeError, "%.200s attribute must be str", name); - Py_DECREF(attr); - return NULL; - } - return attr; -} - - -static -int set_string(PyObject *exc, const char *name, const char *value) -{ - PyObject *obj = PyString_FromString(value); - int result; - - if (!obj) - return -1; - result = PyObject_SetAttrString(exc, (char *)name, obj); - Py_DECREF(obj); - return result; -} - - -static -PyObject *get_unicode(PyObject *exc, const char *name) -{ - PyObject *attr = PyObject_GetAttrString(exc, (char *)name); - - if (!attr) - return NULL; - if (!PyUnicode_Check(attr)) { - PyErr_Format(PyExc_TypeError, "%.200s attribute must be unicode", name); - Py_DECREF(attr); - return NULL; - } - return attr; -} - -PyObject * PyUnicodeEncodeError_GetEncoding(PyObject *exc) -{ - return get_string(exc, "encoding"); -} - -PyObject * PyUnicodeDecodeError_GetEncoding(PyObject *exc) -{ - return get_string(exc, "encoding"); -} - -PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc) -{ - return get_unicode(exc, "object"); -} - -PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc) -{ - return get_string(exc, "object"); -} - -PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc) -{ - return get_unicode(exc, "object"); -} - -int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start) -{ - if (!get_int(exc, "start", start)) { - PyObject *object = PyUnicodeEncodeError_GetObject(exc); - Py_ssize_t size; - if (!object) - return -1; - size = PyUnicode_GET_SIZE(object); - if (*start<0) - *start = 0; /*XXX check for values <0*/ - if (*start>=size) - *start = size-1; - Py_DECREF(object); - return 0; - } - return -1; -} - - -int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start) -{ - if (!get_int(exc, "start", start)) { - PyObject *object = PyUnicodeDecodeError_GetObject(exc); - Py_ssize_t size; - if (!object) - return -1; - size = PyString_GET_SIZE(object); - if (*start<0) - *start = 0; - if (*start>=size) - *start = size-1; - Py_DECREF(object); - return 0; - } - return -1; -} - - -int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start) -{ - return PyUnicodeEncodeError_GetStart(exc, start); -} - - -int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start) -{ - return set_ssize_t(exc, "start", start); -} - - -int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start) -{ - return set_ssize_t(exc, "start", start); -} - - -int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start) -{ - return set_ssize_t(exc, "start", start); -} - - -int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end) -{ - if (!get_int(exc, "end", end)) { - PyObject *object = PyUnicodeEncodeError_GetObject(exc); - Py_ssize_t size; - if (!object) - return -1; - size = PyUnicode_GET_SIZE(object); - if (*end<1) - *end = 1; - if (*end>size) - *end = size; - Py_DECREF(object); - return 0; - } - return -1; -} - - -int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end) -{ - if (!get_int(exc, "end", end)) { - PyObject *object = PyUnicodeDecodeError_GetObject(exc); - Py_ssize_t size; - if (!object) - return -1; - size = PyString_GET_SIZE(object); - if (*end<1) - *end = 1; - if (*end>size) - *end = size; - Py_DECREF(object); - return 0; - } - return -1; -} - - -int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start) -{ - return PyUnicodeEncodeError_GetEnd(exc, start); -} - - -int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end) -{ - return set_ssize_t(exc, "end", end); -} - - -int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end) -{ - return set_ssize_t(exc, "end", end); -} - - -int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end) -{ - return set_ssize_t(exc, "end", end); -} - - -PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc) -{ - return get_string(exc, "reason"); -} - - -PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc) -{ - return get_string(exc, "reason"); -} - - -PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc) -{ - return get_string(exc, "reason"); -} - - -int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason) -{ - return set_string(exc, "reason", reason); -} - - -int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason) -{ - return set_string(exc, "reason", reason); -} - - -int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason) -{ - return set_string(exc, "reason", reason); -} - - -static PyObject * -UnicodeError__init__(PyObject *self, PyObject *args, PyTypeObject *objecttype) -{ - PyObject *rtnval = NULL; - PyObject *encoding; - PyObject *object; - PyObject *start; - PyObject *end; - PyObject *reason; - - if (!(self = get_self(args))) - return NULL; - - if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args)))) - return NULL; - - if (!set_args_and_message(self, args)) { - Py_DECREF(args); - return NULL; - } - - if (!PyArg_ParseTuple(args, "O!O!O!O!O!", - &PyString_Type, &encoding, - objecttype, &object, - &PyInt_Type, &start, - &PyInt_Type, &end, - &PyString_Type, &reason)) - goto finally; - - if (PyObject_SetAttrString(self, "encoding", encoding)) - goto finally; - if (PyObject_SetAttrString(self, "object", object)) - goto finally; - if (PyObject_SetAttrString(self, "start", start)) - goto finally; - if (PyObject_SetAttrString(self, "end", end)) - goto finally; - if (PyObject_SetAttrString(self, "reason", reason)) - goto finally; - - Py_INCREF(Py_None); - rtnval = Py_None; - - finally: - Py_DECREF(args); - return rtnval; -} - - -static PyObject * -UnicodeEncodeError__init__(PyObject *self, PyObject *args) -{ - return UnicodeError__init__(self, args, &PyUnicode_Type); -} - -static PyObject * -UnicodeEncodeError__str__(PyObject *self, PyObject *arg) -{ - PyObject *encodingObj = NULL; - PyObject *objectObj = NULL; - Py_ssize_t start; - Py_ssize_t end; - PyObject *reasonObj = NULL; - PyObject *result = NULL; - - self = arg; - - if (!(encodingObj = PyUnicodeEncodeError_GetEncoding(self))) - goto error; - - if (!(objectObj = PyUnicodeEncodeError_GetObject(self))) - goto error; - - if (PyUnicodeEncodeError_GetStart(self, &start)) - goto error; - - if (PyUnicodeEncodeError_GetEnd(self, &end)) - goto error; - - if (!(reasonObj = PyUnicodeEncodeError_GetReason(self))) - goto error; - - if (end==start+1) { - int badchar = (int)PyUnicode_AS_UNICODE(objectObj)[start]; - char badchar_str[20]; - if (badchar <= 0xff) - PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar); - else if (badchar <= 0xffff) - PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar); - else - PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar); - result = PyString_FromFormat( - "'%.400s' codec can't encode character u'\\%s' in position %zd: %.400s", - PyString_AS_STRING(encodingObj), - badchar_str, - start, - PyString_AS_STRING(reasonObj) - ); - } - else { - result = PyString_FromFormat( - "'%.400s' codec can't encode characters in position %zd-%zd: %.400s", - PyString_AS_STRING(encodingObj), - start, - (end-1), - PyString_AS_STRING(reasonObj) - ); - } - -error: - Py_XDECREF(reasonObj); - Py_XDECREF(objectObj); - Py_XDECREF(encodingObj); - return result; -} - -static PyMethodDef UnicodeEncodeError_methods[] = { - {"__init__", UnicodeEncodeError__init__, METH_VARARGS}, - {"__str__", UnicodeEncodeError__str__, METH_O}, - {NULL, NULL} -}; - - -PyObject * PyUnicodeEncodeError_Create( - const char *encoding, const Py_UNICODE *object, Py_ssize_t length, - Py_ssize_t start, Py_ssize_t end, const char *reason) -{ - return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns", - encoding, object, length, start, end, reason); -} - - -static PyObject * -UnicodeDecodeError__init__(PyObject *self, PyObject *args) -{ - return UnicodeError__init__(self, args, &PyString_Type); -} - -static PyObject * -UnicodeDecodeError__str__(PyObject *self, PyObject *arg) -{ - PyObject *encodingObj = NULL; - PyObject *objectObj = NULL; - Py_ssize_t start; - Py_ssize_t end; - PyObject *reasonObj = NULL; - PyObject *result = NULL; - - self = arg; - - if (!(encodingObj = PyUnicodeDecodeError_GetEncoding(self))) - goto error; - - if (!(objectObj = PyUnicodeDecodeError_GetObject(self))) - goto error; - - if (PyUnicodeDecodeError_GetStart(self, &start)) - goto error; - - if (PyUnicodeDecodeError_GetEnd(self, &end)) - goto error; - - if (!(reasonObj = PyUnicodeDecodeError_GetReason(self))) - goto error; - - if (end==start+1) { - /* FromFormat does not support %02x, so format that separately */ - char byte[4]; - PyOS_snprintf(byte, sizeof(byte), "%02x", - ((int)PyString_AS_STRING(objectObj)[start])&0xff); - result = PyString_FromFormat( - "'%.400s' codec can't decode byte 0x%s in position %zd: %.400s", - PyString_AS_STRING(encodingObj), - byte, - start, - PyString_AS_STRING(reasonObj) - ); - } - else { - result = PyString_FromFormat( - "'%.400s' codec can't decode bytes in position %zd-%zd: %.400s", - PyString_AS_STRING(encodingObj), - start, - (end-1), - PyString_AS_STRING(reasonObj) - ); - } - - -error: - Py_XDECREF(reasonObj); - Py_XDECREF(objectObj); - Py_XDECREF(encodingObj); - return result; -} - -static PyMethodDef UnicodeDecodeError_methods[] = { - {"__init__", UnicodeDecodeError__init__, METH_VARARGS}, - {"__str__", UnicodeDecodeError__str__, METH_O}, - {NULL, NULL} -}; - - -PyObject * PyUnicodeDecodeError_Create( - const char *encoding, const char *object, Py_ssize_t length, - Py_ssize_t start, Py_ssize_t end, const char *reason) -{ - assert(length < INT_MAX); - assert(start < INT_MAX); - assert(end < INT_MAX); - return PyObject_CallFunction(PyExc_UnicodeDecodeError, "ss#nns", - encoding, object, length, start, end, reason); -} - - -static PyObject * -UnicodeTranslateError__init__(PyObject *self, PyObject *args) -{ - PyObject *rtnval = NULL; - PyObject *object; - PyObject *start; - PyObject *end; - PyObject *reason; - - if (!(self = get_self(args))) - return NULL; - - if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args)))) - return NULL; - - if (!set_args_and_message(self, args)) { - Py_DECREF(args); - return NULL; - } - - if (!PyArg_ParseTuple(args, "O!O!O!O!", - &PyUnicode_Type, &object, - &PyInt_Type, &start, - &PyInt_Type, &end, - &PyString_Type, &reason)) - goto finally; - - if (PyObject_SetAttrString(self, "object", object)) - goto finally; - if (PyObject_SetAttrString(self, "start", start)) - goto finally; - if (PyObject_SetAttrString(self, "end", end)) - goto finally; - if (PyObject_SetAttrString(self, "reason", reason)) - goto finally; - - rtnval = Py_None; - Py_INCREF(rtnval); - - finally: - Py_DECREF(args); - return rtnval; -} - - -static PyObject * -UnicodeTranslateError__str__(PyObject *self, PyObject *arg) -{ - PyObject *objectObj = NULL; - Py_ssize_t start; - Py_ssize_t end; - PyObject *reasonObj = NULL; - PyObject *result = NULL; - - self = arg; - - if (!(objectObj = PyUnicodeTranslateError_GetObject(self))) - goto error; - - if (PyUnicodeTranslateError_GetStart(self, &start)) - goto error; - - if (PyUnicodeTranslateError_GetEnd(self, &end)) - goto error; - - if (!(reasonObj = PyUnicodeTranslateError_GetReason(self))) - goto error; - - if (end==start+1) { - int badchar = (int)PyUnicode_AS_UNICODE(objectObj)[start]; - char badchar_str[20]; - if (badchar <= 0xff) - PyOS_snprintf(badchar_str, sizeof(badchar_str), "x%02x", badchar); - else if (badchar <= 0xffff) - PyOS_snprintf(badchar_str, sizeof(badchar_str), "u%04x", badchar); - else - PyOS_snprintf(badchar_str, sizeof(badchar_str), "U%08x", badchar); - result = PyString_FromFormat( - "can't translate character u'\\%s' in position %zd: %.400s", - badchar_str, - start, - PyString_AS_STRING(reasonObj) - ); - } - else { - result = PyString_FromFormat( - "can't translate characters in position %zd-%zd: %.400s", - start, - (end-1), - PyString_AS_STRING(reasonObj) - ); - } - -error: - Py_XDECREF(reasonObj); - Py_XDECREF(objectObj); - return result; -} - -static PyMethodDef UnicodeTranslateError_methods[] = { - {"__init__", UnicodeTranslateError__init__, METH_VARARGS}, - {"__str__", UnicodeTranslateError__str__, METH_O}, - {NULL, NULL} -}; - - -PyObject * PyUnicodeTranslateError_Create( - const Py_UNICODE *object, Py_ssize_t length, - Py_ssize_t start, Py_ssize_t end, const char *reason) -{ - return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns", - object, length, start, end, reason); -} -#endif - - - -/* Exception doc strings */ - -PyDoc_STRVAR(AssertionError__doc__, "Assertion failed."); - -PyDoc_STRVAR(LookupError__doc__, "Base class for lookup errors."); - -PyDoc_STRVAR(IndexError__doc__, "Sequence index out of range."); - -PyDoc_STRVAR(KeyError__doc__, "Mapping key not found."); - -PyDoc_STRVAR(ArithmeticError__doc__, "Base class for arithmetic errors."); - -PyDoc_STRVAR(OverflowError__doc__, "Result too large to be represented."); - -PyDoc_STRVAR(ZeroDivisionError__doc__, -"Second argument to a division or modulo operation was zero."); - -PyDoc_STRVAR(FloatingPointError__doc__, "Floating point operation failed."); - -PyDoc_STRVAR(ValueError__doc__, -"Inappropriate argument value (of correct type)."); - -PyDoc_STRVAR(UnicodeError__doc__, "Unicode related error."); - -#ifdef Py_USING_UNICODE -PyDoc_STRVAR(UnicodeEncodeError__doc__, "Unicode encoding error."); - -PyDoc_STRVAR(UnicodeDecodeError__doc__, "Unicode decoding error."); - -PyDoc_STRVAR(UnicodeTranslateError__doc__, "Unicode translation error."); -#endif - -PyDoc_STRVAR(SystemError__doc__, -"Internal error in the Python interpreter.\n\ -\n\ -Please report this to the Python maintainer, along with the traceback,\n\ -the Python version, and the hardware/OS platform and version."); - -PyDoc_STRVAR(ReferenceError__doc__, -"Weak ref proxy used after referent went away."); - -PyDoc_STRVAR(MemoryError__doc__, "Out of memory."); - -PyDoc_STRVAR(IndentationError__doc__, "Improper indentation."); - -PyDoc_STRVAR(TabError__doc__, "Improper mixture of spaces and tabs."); - -/* Warning category docstrings */ - -PyDoc_STRVAR(Warning__doc__, "Base class for warning categories."); - -PyDoc_STRVAR(UserWarning__doc__, -"Base class for warnings generated by user code."); - -PyDoc_STRVAR(DeprecationWarning__doc__, -"Base class for warnings about deprecated features."); - -PyDoc_STRVAR(PendingDeprecationWarning__doc__, -"Base class for warnings about features which will be deprecated " -"in the future."); - -PyDoc_STRVAR(SyntaxWarning__doc__, -"Base class for warnings about dubious syntax."); - -PyDoc_STRVAR(OverflowWarning__doc__, -"Base class for warnings about numeric overflow. Won't exist in Python 2.5."); - -PyDoc_STRVAR(RuntimeWarning__doc__, -"Base class for warnings about dubious runtime behavior."); - -PyDoc_STRVAR(FutureWarning__doc__, -"Base class for warnings about constructs that will change semantically " -"in the future."); - - - -/* module global functions */ -static PyMethodDef functions[] = { - /* Sentinel */ - {NULL, NULL} -}; - - - -/* Global C API defined exceptions */ - -PyObject *PyExc_BaseException; -PyObject *PyExc_Exception; -PyObject *PyExc_StopIteration; -PyObject *PyExc_GeneratorExit; -PyObject *PyExc_StandardError; -PyObject *PyExc_ArithmeticError; -PyObject *PyExc_LookupError; - -PyObject *PyExc_AssertionError; -PyObject *PyExc_AttributeError; -PyObject *PyExc_EOFError; -PyObject *PyExc_FloatingPointError; -PyObject *PyExc_EnvironmentError; -PyObject *PyExc_IOError; -PyObject *PyExc_OSError; -PyObject *PyExc_ImportError; -PyObject *PyExc_IndexError; -PyObject *PyExc_KeyError; -PyObject *PyExc_KeyboardInterrupt; -PyObject *PyExc_MemoryError; -PyObject *PyExc_NameError; -PyObject *PyExc_OverflowError; -PyObject *PyExc_RuntimeError; -PyObject *PyExc_NotImplementedError; -PyObject *PyExc_SyntaxError; -PyObject *PyExc_IndentationError; -PyObject *PyExc_TabError; -PyObject *PyExc_ReferenceError; -PyObject *PyExc_SystemError; -PyObject *PyExc_SystemExit; -PyObject *PyExc_UnboundLocalError; -PyObject *PyExc_UnicodeError; -PyObject *PyExc_UnicodeEncodeError; -PyObject *PyExc_UnicodeDecodeError; -PyObject *PyExc_UnicodeTranslateError; -PyObject *PyExc_TypeError; -PyObject *PyExc_ValueError; -PyObject *PyExc_ZeroDivisionError; -#ifdef MS_WINDOWS -PyObject *PyExc_WindowsError; -#endif -#ifdef __VMS -PyObject *PyExc_VMSError; -#endif - -/* Pre-computed MemoryError instance. Best to create this as early as - * possible and not wait until a MemoryError is actually raised! - */ -PyObject *PyExc_MemoryErrorInst; - -/* Predefined warning categories */ -PyObject *PyExc_Warning; -PyObject *PyExc_UserWarning; -PyObject *PyExc_DeprecationWarning; -PyObject *PyExc_PendingDeprecationWarning; -PyObject *PyExc_SyntaxWarning; -/* PyExc_OverflowWarning should be removed for Python 2.5 */ -PyObject *PyExc_OverflowWarning; -PyObject *PyExc_RuntimeWarning; -PyObject *PyExc_FutureWarning; - - - -/* mapping between exception names and their PyObject ** */ -static struct { - char *name; - PyObject **exc; - PyObject **base; /* NULL == PyExc_StandardError */ - char *docstr; - PyMethodDef *methods; - int (*classinit)(PyObject *); -} exctable[] = { - /* - * The first four classes MUST appear in exactly this order - */ - {"BaseException", &PyExc_BaseException}, - {"Exception", &PyExc_Exception, &PyExc_BaseException, Exception__doc__}, - {"StopIteration", &PyExc_StopIteration, &PyExc_Exception, - StopIteration__doc__}, - {"GeneratorExit", &PyExc_GeneratorExit, &PyExc_Exception, - GeneratorExit__doc__}, - {"StandardError", &PyExc_StandardError, &PyExc_Exception, - StandardError__doc__}, - {"TypeError", &PyExc_TypeError, 0, TypeError__doc__}, - /* - * The rest appear in depth-first order of the hierarchy - */ - {"SystemExit", &PyExc_SystemExit, &PyExc_BaseException, SystemExit__doc__, - SystemExit_methods}, - {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, &PyExc_BaseException, - KeyboardInterrupt__doc__}, - {"ImportError", &PyExc_ImportError, 0, ImportError__doc__}, - {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__, - EnvironmentError_methods}, - {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__}, - {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__}, -#ifdef MS_WINDOWS - {"WindowsError", &PyExc_WindowsError, &PyExc_OSError, - WindowsError__doc__}, -#endif /* MS_WINDOWS */ -#ifdef __VMS - {"VMSError", &PyExc_VMSError, &PyExc_OSError, - VMSError__doc__}, -#endif - {"EOFError", &PyExc_EOFError, 0, EOFError__doc__}, - {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__}, - {"NotImplementedError", &PyExc_NotImplementedError, - &PyExc_RuntimeError, NotImplementedError__doc__}, - {"NameError", &PyExc_NameError, 0, NameError__doc__}, - {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError, - UnboundLocalError__doc__}, - {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__}, - {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__, - SyntaxError_methods, SyntaxError__classinit__}, - {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError, - IndentationError__doc__}, - {"TabError", &PyExc_TabError, &PyExc_IndentationError, - TabError__doc__}, - {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__}, - {"LookupError", &PyExc_LookupError, 0, LookupError__doc__}, - {"IndexError", &PyExc_IndexError, &PyExc_LookupError, - IndexError__doc__}, - {"KeyError", &PyExc_KeyError, &PyExc_LookupError, - KeyError__doc__, KeyError_methods}, - {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__}, - {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError, - OverflowError__doc__}, - {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError, - ZeroDivisionError__doc__}, - {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError, - FloatingPointError__doc__}, - {"ValueError", &PyExc_ValueError, 0, ValueError__doc__}, - {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__}, -#ifdef Py_USING_UNICODE - {"UnicodeEncodeError", &PyExc_UnicodeEncodeError, &PyExc_UnicodeError, - UnicodeEncodeError__doc__, UnicodeEncodeError_methods}, - {"UnicodeDecodeError", &PyExc_UnicodeDecodeError, &PyExc_UnicodeError, - UnicodeDecodeError__doc__, UnicodeDecodeError_methods}, - {"UnicodeTranslateError", &PyExc_UnicodeTranslateError, &PyExc_UnicodeError, - UnicodeTranslateError__doc__, UnicodeTranslateError_methods}, -#endif - {"ReferenceError", &PyExc_ReferenceError, 0, ReferenceError__doc__}, - {"SystemError", &PyExc_SystemError, 0, SystemError__doc__}, - {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__}, - /* Warning categories */ - {"Warning", &PyExc_Warning, &PyExc_Exception, Warning__doc__}, - {"UserWarning", &PyExc_UserWarning, &PyExc_Warning, UserWarning__doc__}, - {"DeprecationWarning", &PyExc_DeprecationWarning, &PyExc_Warning, - DeprecationWarning__doc__}, - {"PendingDeprecationWarning", &PyExc_PendingDeprecationWarning, &PyExc_Warning, - PendingDeprecationWarning__doc__}, - {"SyntaxWarning", &PyExc_SyntaxWarning, &PyExc_Warning, SyntaxWarning__doc__}, - /* OverflowWarning should be removed for Python 2.5 */ - {"OverflowWarning", &PyExc_OverflowWarning, &PyExc_Warning, - OverflowWarning__doc__}, - {"RuntimeWarning", &PyExc_RuntimeWarning, &PyExc_Warning, - RuntimeWarning__doc__}, - {"FutureWarning", &PyExc_FutureWarning, &PyExc_Warning, - FutureWarning__doc__}, - /* Sentinel */ - {NULL} -}; - - - -void -_PyExc_Init(void) -{ - char *modulename = "exceptions"; - Py_ssize_t modnamesz = strlen(modulename); - int i; - PyObject *me, *mydict, *bltinmod, *bdict, *doc, *args; - - me = Py_InitModule(modulename, functions); - if (me == NULL) - goto err; - mydict = PyModule_GetDict(me); - if (mydict == NULL) - goto err; - bltinmod = PyImport_ImportModule("__builtin__"); - if (bltinmod == NULL) - goto err; - bdict = PyModule_GetDict(bltinmod); - if (bdict == NULL) - goto err; - doc = PyString_FromString(module__doc__); - if (doc == NULL) - goto err; - - i = PyDict_SetItemString(mydict, "__doc__", doc); - Py_DECREF(doc); - if (i < 0) { - err: - Py_FatalError("exceptions bootstrapping error."); - return; - } - - /* This is the base class of all exceptions, so make it first. */ - if (make_BaseException(modulename) || - PyDict_SetItemString(mydict, "BaseException", PyExc_BaseException) || - PyDict_SetItemString(bdict, "BaseException", PyExc_BaseException)) - { - Py_FatalError("Base class `BaseException' could not be created."); - } - - /* Now we can programmatically create all the remaining exceptions. - * Remember to start the loop at 1 to skip Exceptions. - */ - for (i=1; exctable[i].name; i++) { - int status; - char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2); - PyObject *base; - - (void)strcpy(cname, modulename); - (void)strcat(cname, "."); - (void)strcat(cname, exctable[i].name); - - if (exctable[i].base == 0) - base = PyExc_StandardError; - else - base = *exctable[i].base; - - status = make_class(exctable[i].exc, base, cname, - exctable[i].methods, - exctable[i].docstr); - - PyMem_DEL(cname); - - if (status) - Py_FatalError("Standard exception classes could not be created."); - - if (exctable[i].classinit) { - status = (*exctable[i].classinit)(*exctable[i].exc); - if (status) - Py_FatalError("An exception class could not be initialized."); - } - - /* Now insert the class into both this module and the __builtin__ - * module. - */ - if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) || - PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc)) - { - Py_FatalError("Module dictionary insertion problem."); - } - } - - /* Now we need to pre-allocate a MemoryError instance */ - args = PyTuple_New(0); - if (!args || - !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args))) - { - Py_FatalError("Cannot pre-allocate MemoryError instance\n"); - } - Py_DECREF(args); - - /* We're done with __builtin__ */ - Py_DECREF(bltinmod); -} - - -void -_PyExc_Fini(void) -{ - int i; - - Py_XDECREF(PyExc_MemoryErrorInst); - PyExc_MemoryErrorInst = NULL; - - for (i=0; exctable[i].name; i++) { - /* clear the class's dictionary, freeing up circular references - * between the class and its methods. - */ - PyObject* cdict = PyObject_GetAttrString(*exctable[i].exc, "__dict__"); - PyDict_Clear(cdict); - Py_DECREF(cdict); - - /* Now decref the exception class */ - Py_XDECREF(*exctable[i].exc); - *exctable[i].exc = NULL; - } -} diff --git a/Python/getcwd.c b/Python/getcwd.c index 5c57291459..967d484b35 100644 --- a/Python/getcwd.c +++ b/Python/getcwd.c @@ -14,8 +14,12 @@ #endif #ifndef MAXPATHLEN +#if defined(PATH_MAX) && PATH_MAX > 1024 +#define MAXPATHLEN PATH_MAX +#else #define MAXPATHLEN 1024 #endif +#endif extern char *getwd(char *); diff --git a/Python/graminit.c b/Python/graminit.c index a6ac124ed6..33ef64b8b7 100644 --- a/Python/graminit.c +++ b/Python/graminit.c @@ -517,41 +517,36 @@ static arc arcs_26_1[2] = { {12, 3}, }; static arc arcs_26_2[3] = { - {75, 4}, + {75, 2}, {12, 3}, - {72, 5}, + {72, 4}, }; static arc arcs_26_3[1] = { - {72, 5}, + {72, 4}, }; -static arc arcs_26_4[2] = { - {75, 4}, - {12, 3}, +static arc arcs_26_4[3] = { + {28, 5}, + {13, 6}, + {76, 5}, }; -static arc arcs_26_5[3] = { - {28, 6}, - {13, 7}, - {76, 6}, +static arc arcs_26_5[1] = { + {0, 5}, }; static arc arcs_26_6[1] = { - {0, 6}, + {76, 7}, }; static arc arcs_26_7[1] = { - {76, 8}, -}; -static arc arcs_26_8[1] = { - {15, 6}, + {15, 5}, }; -static state states_26[9] = { +static state states_26[8] = { {1, arcs_26_0}, {2, arcs_26_1}, {3, arcs_26_2}, {1, arcs_26_3}, - {2, arcs_26_4}, - {3, arcs_26_5}, + {3, arcs_26_4}, + {1, arcs_26_5}, {1, arcs_26_6}, {1, arcs_26_7}, - {1, arcs_26_8}, }; static arc arcs_27_0[1] = { {19, 1}, @@ -1836,7 +1831,7 @@ static dfa dfas[84] = { "\000\000\000\000\000\000\000\000\000\005\000\000\000\000\000\000\000\000\000\000\000"}, {281, "import_name", 0, 3, states_25, "\000\000\000\000\000\000\000\000\000\001\000\000\000\000\000\000\000\000\000\000\000"}, - {282, "import_from", 0, 9, states_26, + {282, "import_from", 0, 8, states_26, "\000\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000"}, {283, "import_as_name", 0, 4, states_27, "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, diff --git a/Python/import.c b/Python/import.c index daae15fb8e..094e4fd00a 100644 --- a/Python/import.c +++ b/Python/import.c @@ -1044,7 +1044,7 @@ get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks, PyObject *hook = PyList_GetItem(path_hooks, j); if (hook == NULL) return NULL; - importer = PyObject_CallFunction(hook, "O", p); + importer = PyObject_CallFunctionObjArgs(hook, p, NULL); if (importer != NULL) break; @@ -1241,7 +1241,33 @@ find_module(char *fullname, char *subname, PyObject *path, char *buf, if (importer == NULL) return NULL; /* Note: importer is a borrowed reference */ - if (importer != Py_None) { + if (importer == Py_False) { + /* Cached as not being a valid dir. */ + Py_XDECREF(copy); + continue; + } + else if (importer == Py_True) { + /* Cached as being a valid dir, so just + * continue below. */ + } + else if (importer == Py_None) { + /* No importer was found, so it has to be a file. + * Check if the directory is valid. */ +#ifdef HAVE_STAT + if (stat(buf, &statbuf) != 0) { + /* Directory does not exist. */ + PyDict_SetItem(path_importer_cache, + v, Py_False); + Py_XDECREF(copy); + continue; + } else { + PyDict_SetItem(path_importer_cache, + v, Py_True); + } +#endif + } + else { + /* A real import hook importer was found. */ PyObject *loader; loader = PyObject_CallMethod(importer, "find_module", @@ -1254,9 +1280,11 @@ find_module(char *fullname, char *subname, PyObject *path, char *buf, return &importhookdescr; } Py_DECREF(loader); + Py_XDECREF(copy); + continue; } - /* no hook was successful, use builtin import */ } + /* no hook was found, use builtin import */ if (len > 0 && buf[len-1] != SEP #ifdef ALTSEP @@ -1272,19 +1300,42 @@ find_module(char *fullname, char *subname, PyObject *path, char *buf, #ifdef HAVE_STAT if (stat(buf, &statbuf) == 0 && /* it exists */ S_ISDIR(statbuf.st_mode) && /* it's a directory */ - find_init_module(buf) && /* it has __init__.py */ - case_ok(buf, len, namelen, name)) { /* and case matches */ - Py_XDECREF(copy); - return &fd_package; + case_ok(buf, len, namelen, name)) { /* case matches */ + if (find_init_module(buf)) { /* and has __init__.py */ + Py_XDECREF(copy); + return &fd_package; + } + else { + char warnstr[MAXPATHLEN+80]; + sprintf(warnstr, "Not importing directory " + "'%.*s': missing __init__.py", + MAXPATHLEN, buf); + if (PyErr_Warn(PyExc_ImportWarning, + warnstr)) { + Py_XDECREF(copy); + return NULL; + } + } } #else /* XXX How are you going to test for directories? */ #ifdef RISCOS if (isdir(buf) && - find_init_module(buf) && case_ok(buf, len, namelen, name)) { - Py_XDECREF(copy); - return &fd_package; + if (find_init_module(buf)) { + Py_XDECREF(copy); + return &fd_package; + } + else { + char warnstr[MAXPATHLEN+80]; + sprintf(warnstr, "Not importing directory " + "'%.*s': missing __init__.py", + MAXPATHLEN, buf); + if (PyErr_Warn(PyExc_ImportWarning, + warnstr)) { + Py_XDECREF(copy); + return NULL; + } } #endif #endif @@ -2477,8 +2528,8 @@ PyImport_Import(PyObject *module_name) goto err; /* Call the _import__ function with the proper argument list */ - r = PyObject_CallFunction(import, "OOOO", - module_name, globals, globals, silly_list); + r = PyObject_CallFunctionObjArgs(import, module_name, globals, + globals, silly_list, NULL); err: Py_XDECREF(globals); diff --git a/Python/mystrtoul.c b/Python/mystrtoul.c index 8e60c0c072..380b37da90 100644 --- a/Python/mystrtoul.c +++ b/Python/mystrtoul.c @@ -15,6 +15,66 @@ /* strtol and strtoul, renamed to avoid conflicts */ + +#include <ctype.h> +#ifndef DONT_HAVE_ERRNO_H +#include <errno.h> +#endif + +/* Static overflow check values for bases 2 through 36. + * smallmax[base] is the largest unsigned long i such that + * i * base doesn't overflow unsigned long. + */ +static unsigned long smallmax[] = { + 0, /* bases 0 and 1 are invalid */ + 0, + ULONG_MAX / 2, + ULONG_MAX / 3, + ULONG_MAX / 4, + ULONG_MAX / 5, + ULONG_MAX / 6, + ULONG_MAX / 7, + ULONG_MAX / 8, + ULONG_MAX / 9, + ULONG_MAX / 10, + ULONG_MAX / 11, + ULONG_MAX / 12, + ULONG_MAX / 13, + ULONG_MAX / 14, + ULONG_MAX / 15, + ULONG_MAX / 16, + ULONG_MAX / 17, + ULONG_MAX / 18, + ULONG_MAX / 19, + ULONG_MAX / 20, + ULONG_MAX / 21, + ULONG_MAX / 22, + ULONG_MAX / 23, + ULONG_MAX / 24, + ULONG_MAX / 25, + ULONG_MAX / 26, + ULONG_MAX / 27, + ULONG_MAX / 28, + ULONG_MAX / 29, + ULONG_MAX / 30, + ULONG_MAX / 31, + ULONG_MAX / 32, + ULONG_MAX / 33, + ULONG_MAX / 34, + ULONG_MAX / 35, + ULONG_MAX / 36, +}; + +/* maximum digits that can't ever overflow for bases 2 through 36, + * calculated by [int(math.floor(math.log(2**32, i))) for i in range(2, 37)]. + * Note that this is pessimistic if sizeof(long) > 4. + */ +static int digitlimit[] = { + 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */ + 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */ + 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */ + 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */ + /* ** strtoul ** This is a general purpose routine for converting @@ -28,98 +88,100 @@ ** Errors due to bad pointers will probably result in ** exceptions - we don't check for them. */ - -#include <ctype.h> -#ifndef DONT_HAVE_ERRNO_H -#include <errno.h> -#endif - unsigned long PyOS_strtoul(register char *str, char **ptr, int base) { - register unsigned long result; /* return value of the function */ - register int c; /* current input character */ - register unsigned long temp; /* used in overflow testing */ - int ovf; /* true if overflow occurred */ + register unsigned long result = 0; /* return value of the function */ + register int c; /* current input character */ + register int ovlimit; /* required digits to overflow */ + + /* skip leading white space */ + while (*str && isspace(Py_CHARMASK(*str))) + ++str; - result = 0; - ovf = 0; + /* check for leading 0 or 0x for auto-base or base 16 */ + switch (base) { + case 0: /* look for leading 0, 0x or 0X */ + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') { + ++str; + base = 16; + } + else + base = 8; + } + else + base = 10; + break; -/* catch silly bases */ - if (base != 0 && (base < 2 || base > 36)) - { - if (ptr) - *ptr = str; - return 0; - } - -/* skip leading white space */ - while (*str && isspace(Py_CHARMASK(*str))) - str++; - -/* check for leading 0 or 0x for auto-base or base 16 */ - switch (base) - { - case 0: /* look for leading 0, 0x or 0X */ - if (*str == '0') - { - str++; - if (*str == 'x' || *str == 'X') - { - str++; - base = 16; - } - else - base = 8; + case 16: /* skip leading 0x or 0X */ + if (*str == '0') { + ++str; + if (*str == 'x' || *str == 'X') + ++str; + } + break; } - else - base = 10; - break; - - case 16: /* skip leading 0x or 0X */ - if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X')) - str += 2; - break; - } - -/* do the conversion */ - while ((c = Py_CHARMASK(*str)) != '\0') - { - if (isdigit(c) && c - '0' < base) - c -= '0'; - else - { - if (isupper(c)) - c = tolower(c); - if (c >= 'a' && c <= 'z') - c -= 'a' - 10; - else /* non-"digit" character */ - break; - if (c >= base) /* non-"digit" character */ - break; + + /* catch silly bases */ + if (base < 2 || base > 36) { + if (ptr) + *ptr = str; + return 0; } - temp = result; - result = result * base + c; - if(base == 10) { - if(((long)(result - c) / base != (long)temp)) /* overflow */ - ovf = 1; + + /* skip leading zeroes */ + while (*str == '0') + ++str; + + /* base is guaranteed to be in [2, 36] at this point */ + ovlimit = digitlimit[base]; + + /* do the conversion until non-digit character encountered */ + while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) { + if (ovlimit > 0) /* no overflow check required */ + result = result * base + c; + else { /* requires overflow check */ + register unsigned long temp_result; + + if (ovlimit < 0) /* guaranteed overflow */ + goto overflowed; + + /* there could be an overflow */ + /* check overflow just from shifting */ + if (result > smallmax[base]) + goto overflowed; + + result *= base; + + /* check overflow from the digit's value */ + temp_result = result + c; + if (temp_result < result) + goto overflowed; + + result = temp_result; + } + + ++str; + --ovlimit; } - else { - if ((result - c) / base != temp) /* overflow */ - ovf = 1; + + /* set pointer to point to the last character scanned */ + if (ptr) + *ptr = str; + + return result; + +overflowed: + if (ptr) { + /* spool through remaining digit characters */ + while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base) + ++str; + *ptr = str; } - str++; - } - -/* set pointer to point to the last character scanned */ - if (ptr) - *ptr = str; - if (ovf) - { - result = (unsigned long) ~0L; errno = ERANGE; - } - return result; + return (unsigned long)-1; } long @@ -127,25 +189,25 @@ PyOS_strtol(char *str, char **ptr, int base) { long result; char sign; - + while (*str && isspace(Py_CHARMASK(*str))) str++; - + sign = *str; if (sign == '+' || sign == '-') str++; - + result = (long) PyOS_strtoul(str, ptr, base); - + /* Signal overflow if the result appears negative, except for the largest negative integer */ if (result < 0 && !(sign == '-' && result == -result)) { errno = ERANGE; result = 0x7fffffff; } - + if (sign == '-') result = -result; - + return result; } diff --git a/Python/pystrtod.c b/Python/pystrtod.c index db4cad17d7..8a71c285a9 100644 --- a/Python/pystrtod.c +++ b/Python/pystrtod.c @@ -101,7 +101,7 @@ PyOS_ascii_strtod(const char *nptr, char **endptr) char *copy, *c; /* We need to convert the '.' to the locale specific decimal point */ - copy = (char *)malloc(end - nptr + 1 + decimal_point_len); + copy = (char *)PyMem_MALLOC(end - nptr + 1 + decimal_point_len); c = copy; memcpy(c, nptr, decimal_point_pos - nptr); @@ -122,7 +122,7 @@ PyOS_ascii_strtod(const char *nptr, char **endptr) fail_pos = (char *)nptr + (fail_pos - copy); } - free(copy); + PyMem_FREE(copy); } else { diff --git a/Python/pythonrun.c b/Python/pythonrun.c index 99d6d9dd46..8283fc5c98 100644 --- a/Python/pythonrun.c +++ b/Python/pythonrun.c @@ -1078,7 +1078,8 @@ PyErr_PrintEx(int set_sys_last_vars) Py_XDECREF(tb); } -void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) +void +PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) { int err = 0; PyObject *f = PySys_GetObject("stderr"); @@ -1126,19 +1127,22 @@ void PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb) } else if (PyExceptionClass_Check(exception)) { char* className = PyExceptionClass_Name(exception); - PyObject* moduleName = - PyObject_GetAttrString(exception, "__module__"); + char *dot = strrchr(className, '.'); + PyObject* moduleName; + if (dot != NULL) + className = dot+1; + moduleName = PyObject_GetAttrString(exception, "__module__"); if (moduleName == NULL) err = PyFile_WriteString("<unknown>", f); else { char* modstr = PyString_AsString(moduleName); - Py_DECREF(moduleName); if (modstr && strcmp(modstr, "exceptions")) { err = PyFile_WriteString(modstr, f); err += PyFile_WriteString(".", f); } + Py_DECREF(moduleName); } if (err == 0) { if (className == NULL) diff --git a/Python/structmember.c b/Python/structmember.c index 0a24d9d26c..54eb0556f7 100644 --- a/Python/structmember.c +++ b/Python/structmember.c @@ -260,8 +260,9 @@ PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) PyErr_BadArgument(); return -1; } else { - *(PY_LONG_LONG*)addr = PyLong_AsLongLong(v); - if ((*addr == -1) && PyErr_Occurred()) { + PY_LONG_LONG value; + *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v); + if ((value == -1) && PyErr_Occurred()) { return -1; } } @@ -271,8 +272,10 @@ PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v) PyErr_BadArgument(); return -1; } else { - *(unsigned PY_LONG_LONG*)addr = PyLong_AsUnsignedLongLong(v); - if ((*addr == -1) && PyErr_Occurred()) { + unsigned PY_LONG_LONG value; + *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v); + if ((value == (unsigned PY_LONG_LONG)-1) && + PyErr_Occurred()) { return -1; } } diff --git a/Python/thread_nt.h b/Python/thread_nt.h index e52d288f21..5141053b03 100644 --- a/Python/thread_nt.h +++ b/Python/thread_nt.h @@ -170,7 +170,7 @@ bootstrap(void *call) long PyThread_start_new_thread(void (*func)(void *), void *arg) { - uintptr_t rv; + Py_uintptr_t rv; callobj obj; dprintf(("%ld: PyThread_start_new_thread called\n", @@ -186,7 +186,7 @@ PyThread_start_new_thread(void (*func)(void *), void *arg) return -1; rv = _beginthread(bootstrap, 0, &obj); /* use default stack size */ - if (rv == (uintptr_t)-1) { + if (rv == (Py_uintptr_t)-1) { /* I've seen errno == EAGAIN here, which means "there are * too many threads". */ |