Conversion of exceptions over from faked-up classes to new-style C types.

This commit is contained in:
Richard Jones 2006-05-27 12:29:24 +00:00
parent 1fcdc232db
commit 7b9558d37d
16 changed files with 2316 additions and 2163 deletions

View File

@ -2711,7 +2711,7 @@ standard module \module{__builtin__}\refbimodindex{__builtin__}:
'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',

View File

@ -4,6 +4,72 @@
extern "C" {
#endif
/* Error objects */
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
} PyBaseExceptionObject;
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
PyObject *msg;
PyObject *filename;
PyObject *lineno;
PyObject *offset;
PyObject *text;
PyObject *print_file_and_line;
} PySyntaxErrorObject;
#ifdef Py_USING_UNICODE
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
PyObject *encoding;
PyObject *object;
PyObject *start;
PyObject *end;
PyObject *reason;
} PyUnicodeErrorObject;
#endif
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
PyObject *code;
} PySystemExitObject;
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
PyObject *myerrno;
PyObject *strerror;
PyObject *filename;
} PyEnvironmentErrorObject;
#ifdef MS_WINDOWS
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *args;
PyObject *message;
PyObject *myerrno;
PyObject *strerror;
PyObject *filename;
PyObject *winerror;
} PyWindowsErrorObject;
#endif
/* Error handling definitions */
@ -104,8 +170,6 @@ PyAPI_DATA(PyObject *) PyExc_UserWarning;
PyAPI_DATA(PyObject *) PyExc_DeprecationWarning;
PyAPI_DATA(PyObject *) PyExc_PendingDeprecationWarning;
PyAPI_DATA(PyObject *) PyExc_SyntaxWarning;
/* PyExc_OverflowWarning will go away for Python 2.5 */
PyAPI_DATA(PyObject *) PyExc_OverflowWarning;
PyAPI_DATA(PyObject *) PyExc_RuntimeWarning;
PyAPI_DATA(PyObject *) PyExc_FutureWarning;
PyAPI_DATA(PyObject *) PyExc_ImportWarning;

View File

@ -95,15 +95,7 @@ def _maybe_compile(compiler, source, filename, symbol):
if code:
return code
try:
e1 = err1.__dict__
except AttributeError:
e1 = err1
try:
e2 = err2.__dict__
except AttributeError:
e2 = err2
if not code1 and e1 == e2:
if not code1 and repr(err1) == repr(err2):
raise SyntaxError, err1
def _compile(source, filename, symbol):

View File

@ -294,20 +294,20 @@ class StructureTestCase(unittest.TestCase):
# In Python 2.5, Exception is a new-style class, and the repr changed
if issubclass(Exception, object):
self.failUnlessEqual(msg,
"(Phone) <class 'exceptions.TypeError'>: "
"(Phone) <type 'exceptions.TypeError'>: "
"expected string or Unicode object, int found")
else:
self.failUnlessEqual(msg,
"(Phone) exceptions.TypeError: "
"(Phone) TypeError: "
"expected string or Unicode object, int found")
cls, msg = self.get_except(Person, "Someone", ("a", "b", "c"))
self.failUnlessEqual(cls, RuntimeError)
if issubclass(Exception, object):
self.failUnlessEqual(msg,
"(Phone) <class 'exceptions.ValueError'>: too many initializers")
"(Phone) <type 'exceptions.ValueError'>: too many initializers")
else:
self.failUnlessEqual(msg, "(Phone) exceptions.ValueError: too many initializers")
self.failUnlessEqual(msg, "(Phone) ValueError: too many initializers")
def get_except(self, func, *args):

View File

@ -15,6 +15,7 @@ BaseException
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
| +-- ImportError
| +-- LookupError
@ -43,5 +44,4 @@ BaseException
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- OverflowWarning [not generated by the interpreter]
+-- ImportWarning

View File

@ -488,12 +488,12 @@ INFO:a.b.c.d:Info 5
-- log_test4 begin ---------------------------------------------------
config0: ok.
config1: ok.
config2: <class 'exceptions.AttributeError'>
config3: <class 'exceptions.KeyError'>
config2: <type 'exceptions.AttributeError'>
config3: <type 'exceptions.KeyError'>
-- log_test4 end ---------------------------------------------------
-- log_test5 begin ---------------------------------------------------
ERROR:root:just testing
<class 'exceptions.KeyError'>... Don't panic!
<type 'exceptions.KeyError'>... Don't panic!
-- log_test5 end ---------------------------------------------------
-- logrecv output begin ---------------------------------------------------
ERR -> CRITICAL: Message 0 (via logrecv.tcp.ERR)

View File

@ -18,30 +18,12 @@ class PosReturn:
self.pos = len(exc.object)
return (u"<?>", oldpos)
# A UnicodeEncodeError object without a start attribute
class NoStartUnicodeEncodeError(UnicodeEncodeError):
def __init__(self):
UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad")
del self.start
# A UnicodeEncodeError object with a bad start attribute
class BadStartUnicodeEncodeError(UnicodeEncodeError):
def __init__(self):
UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad")
self.start = []
# A UnicodeEncodeError object without an end attribute
class NoEndUnicodeEncodeError(UnicodeEncodeError):
def __init__(self):
UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad")
del self.end
# A UnicodeEncodeError object without an object attribute
class NoObjectUnicodeEncodeError(UnicodeEncodeError):
def __init__(self):
UnicodeEncodeError.__init__(self, "ascii", u"", 0, 1, "bad")
del self.object
# A UnicodeEncodeError object with a bad object attribute
class BadObjectUnicodeEncodeError(UnicodeEncodeError):
def __init__(self):
@ -477,56 +459,16 @@ class CodecCallbackTest(unittest.TestCase):
codecs.replace_errors,
UnicodeError("ouch")
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoStartUnicodeEncodeError()
)
self.assertRaises(
TypeError,
codecs.replace_errors,
BadStartUnicodeEncodeError()
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoEndUnicodeEncodeError()
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoObjectUnicodeEncodeError()
)
self.assertRaises(
TypeError,
codecs.replace_errors,
BadObjectUnicodeEncodeError()
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoEndUnicodeDecodeError()
)
self.assertRaises(
TypeError,
codecs.replace_errors,
BadObjectUnicodeDecodeError()
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoStartUnicodeTranslateError()
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoEndUnicodeTranslateError()
)
self.assertRaises(
AttributeError,
codecs.replace_errors,
NoObjectUnicodeTranslateError()
)
# With the correct exception, "replace" returns an "?" or u"\ufffd" replacement
self.assertEquals(
codecs.replace_errors(UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch")),
@ -565,21 +507,6 @@ class CodecCallbackTest(unittest.TestCase):
codecs.xmlcharrefreplace_errors,
UnicodeTranslateError(u"\u3042", 0, 1, "ouch")
)
self.assertRaises(
AttributeError,
codecs.xmlcharrefreplace_errors,
NoStartUnicodeEncodeError()
)
self.assertRaises(
AttributeError,
codecs.xmlcharrefreplace_errors,
NoEndUnicodeEncodeError()
)
self.assertRaises(
AttributeError,
codecs.xmlcharrefreplace_errors,
NoObjectUnicodeEncodeError()
)
# Use the correct exception
cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042)
s = "".join(unichr(c) for c in cs)

View File

@ -81,14 +81,6 @@ try: x = undefined_variable
except NameError: pass
r(OverflowError)
# XXX
# Obscure: in 2.2 and 2.3, this test relied on changing OverflowWarning
# into an error, in order to trigger OverflowError. In 2.4, OverflowWarning
# should no longer be generated, so the focus of the test shifts to showing
# that OverflowError *isn't* generated. OverflowWarning should be gone
# in Python 2.5, and then the filterwarnings() call, and this comment,
# should go away.
warnings.filterwarnings("error", "", OverflowWarning, __name__)
x = 1
for dummy in range(128):
x += x # this simply shouldn't blow up
@ -206,3 +198,88 @@ if not sys.platform.startswith('java'):
test_capi2()
unlink(TESTFN)
# test that exception attributes are happy.
try: str(u'Hello \u00E1')
except Exception, e: sampleUnicodeEncodeError = e
try: unicode('\xff')
except Exception, e: sampleUnicodeDecodeError = e
exceptionList = [
( BaseException, (), { 'message' : '', 'args' : () }),
( BaseException, (1, ), { 'message' : 1, 'args' : ( 1, ) }),
( BaseException, ('foo', ), { 'message' : 'foo', 'args' : ( 'foo', ) }),
( BaseException, ('foo', 1), { 'message' : '', 'args' : ( 'foo', 1 ) }),
( SystemExit, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ),
'code' : 'foo' }),
( IOError, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ), }),
( IOError, ('foo', 'bar'), { 'message' : '',
'args' : ('foo', 'bar'), }),
( IOError, ('foo', 'bar', 'baz'),
{ 'message' : '', 'args' : ('foo', 'bar'), }),
( EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
{ 'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
'strerror' : 'strErrorStr',
'errno' : 'errnoStr', 'filename' : 'filenameStr' }),
( EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
{ 'message' : '', 'args' : (1, 'strErrorStr'),
'strerror' : 'strErrorStr', 'errno' : 1,
'filename' : 'filenameStr' }),
( SyntaxError, ('msgStr',),
{ 'message' : 'msgStr', 'args' : ('msgStr', ),
'print_file_and_line' : None, 'msg' : 'msgStr',
'filename' : None, 'lineno' : None, 'offset' : None,
'text' : None }),
( SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
'textStr')),
{ 'message' : '', 'args' : ('msgStr', ('filenameStr',
'linenoStr', 'offsetStr', 'textStr' )),
'print_file_and_line' : None, 'msg' : 'msgStr',
'filename' : 'filenameStr', 'lineno' : 'linenoStr',
'offset' : 'offsetStr', 'text' : 'textStr' }),
( SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
'textStr', 'print_file_and_lineStr'),
{ 'message' : '', 'args' : ('msgStr', 'filenameStr',
'linenoStr', 'offsetStr', 'textStr',
'print_file_and_lineStr'),
'print_file_and_line' : None, 'msg' : 'msgStr',
'filename' : None, 'lineno' : None, 'offset' : None,
'text' : None }),
( UnicodeError, (),
{ 'message' : '', 'args' : (), }),
( sampleUnicodeEncodeError,
{ 'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
'ordinal not in range(128)'),
'encoding' : 'ascii', 'object' : u'Hello \xe1',
'start' : 6, 'reason' : 'ordinal not in range(128)' }),
( sampleUnicodeDecodeError,
{ 'message' : '', 'args' : ('ascii', '\xff', 0, 1,
'ordinal not in range(128)'),
'encoding' : 'ascii', 'object' : '\xff',
'start' : 0, 'reason' : 'ordinal not in range(128)' }),
( UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
{ 'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
'object' : u'\u3042', 'reason' : 'ouch',
'start' : 0, 'end' : 1 }),
]
try:
exceptionList.append(
( WindowsError, (1, 'strErrorStr', 'filenameStr'),
{ 'message' : '', 'args' : (1, 'strErrorStr'),
'strerror' : 'strErrorStr',
'errno' : 22, 'filename' : 'filenameStr',
'winerror' : 1 }))
except NameError: pass
for args in exceptionList:
expected = args[-1]
try:
if len(args) == 2: raise args[0]
else: raise apply(args[0], args[1])
except BaseException, e:
for checkArgName in expected.keys():
if repr(getattr(e, checkArgName)) != repr(expected[checkArgName]):
raise TestFailed('Checking exception arguments, exception '
'"%s", attribute "%s" expected %s got %s.' %
( repr(e), checkArgName,
repr(expected[checkArgName]),
repr(getattr(e, checkArgName)) ))

View File

@ -261,6 +261,4 @@ def _getcategory(category):
# Module initialization
_processoptions(sys.warnoptions)
# XXX OverflowWarning should go away for Python 2.5.
simplefilter("ignore", category=OverflowWarning, append=1)
simplefilter("ignore", category=PendingDeprecationWarning, append=1)

View File

@ -240,7 +240,6 @@ PYTHON_OBJS= \
Python/asdl.o \
Python/ast.o \
Python/bltinmodule.o \
Python/exceptions.o \
Python/ceval.o \
Python/compile.o \
Python/codecs.o \
@ -289,6 +288,7 @@ OBJECT_OBJS= \
Objects/complexobject.o \
Objects/descrobject.o \
Objects/enumobject.o \
Objects/exceptions.o \
Objects/genobject.o \
Objects/fileobject.o \
Objects/floatobject.o \

View File

@ -5625,7 +5625,6 @@ init_stuff(PyObject *module_dict)
if (!( t=PyDict_New())) return -1;
if (!( r=PyRun_String(
"def __init__(self, *args): self.args=args\n\n"
"def __str__(self):\n"
" return self.args and ('%s' % self.args[0]) or '(what)'\n",
Py_file_input,
@ -5645,7 +5644,6 @@ init_stuff(PyObject *module_dict)
if (!( t=PyDict_New())) return -1;
if (!( r=PyRun_String(
"def __init__(self, *args): self.args=args\n\n"
"def __str__(self):\n"
" a=self.args\n"
" a=a and type(a[0]) or '(what)'\n"

2130
Objects/exceptions.c Normal file

File diff suppressed because it is too large Load Diff

View File

@ -494,7 +494,7 @@
RelativePath="..\Python\errors.c">
</File>
<File
RelativePath="..\Python\exceptions.c">
RelativePath="..\Objects\exceptions.c">
</File>
<File
RelativePath="..\Objects\fileobject.c">

View File

@ -557,9 +557,6 @@ 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;
if (PyTuple_Check(base)) {
bases = base;
/* INCREF as we create a new ref in the else branch */
@ -569,7 +566,9 @@ PyErr_NewException(char *name, PyObject *base, PyObject *dict)
if (bases == NULL)
goto failure;
}
result = PyClass_New(bases, dict, classname);
/* Create a real new-style class. */
result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
dot+1, bases, dict);
failure:
Py_XDECREF(bases);
Py_XDECREF(mydict);
@ -590,8 +589,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);
@ -641,15 +643,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);
@ -677,18 +675,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);
@ -709,7 +703,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();

File diff suppressed because it is too large Load Diff

View File

@ -1084,7 +1084,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");
@ -1132,19 +1133,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)