blob: 1a218c123d8f0e364e6714c64d0b26701f1c22d4 [file] [log] [blame]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001/*
2 * New exceptions.c written in Iceland by Richard Jones and Georg Brandl.
3 *
4 * Thanks go to Tim Peters and Michael Hudson for debugging.
5 */
6
Thomas Wouters477c8d52006-05-27 19:21:47 +00007#define PY_SSIZE_T_CLEAN
8#include <Python.h>
9#include "structmember.h"
10#include "osdefs.h"
11
Thomas Wouters477c8d52006-05-27 19:21:47 +000012
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020013/* Compatibility aliases */
14PyObject *PyExc_EnvironmentError = NULL;
15PyObject *PyExc_IOError = NULL;
16#ifdef MS_WINDOWS
17PyObject *PyExc_WindowsError = NULL;
18#endif
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020019
20/* The dict map from errno codes to OSError subclasses */
21static PyObject *errnomap = NULL;
22
23
Thomas Wouters477c8d52006-05-27 19:21:47 +000024/* NOTE: If the exception class hierarchy changes, don't forget to update
25 * Lib/test/exception_hierarchy.txt
26 */
27
Thomas Wouters477c8d52006-05-27 19:21:47 +000028/*
29 * BaseException
30 */
31static PyObject *
32BaseException_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
33{
34 PyBaseExceptionObject *self;
35
36 self = (PyBaseExceptionObject *)type->tp_alloc(type, 0);
Guido van Rossumd8faa362007-04-27 19:54:29 +000037 if (!self)
38 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000039 /* the dict is created on the fly in PyObject_GenericSetAttr */
Guido van Rossumebe3e162007-05-17 18:20:34 +000040 self->dict = NULL;
Collin Winter1966f1c2007-09-01 20:26:44 +000041 self->traceback = self->cause = self->context = NULL;
Benjamin Petersond5a1c442012-05-14 22:09:31 -070042 self->suppress_context = 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +000043
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010044 if (args) {
45 self->args = args;
46 Py_INCREF(args);
47 return (PyObject *)self;
48 }
49
Thomas Wouters477c8d52006-05-27 19:21:47 +000050 self->args = PyTuple_New(0);
51 if (!self->args) {
52 Py_DECREF(self);
53 return NULL;
54 }
55
Thomas Wouters477c8d52006-05-27 19:21:47 +000056 return (PyObject *)self;
57}
58
59static int
60BaseException_init(PyBaseExceptionObject *self, PyObject *args, PyObject *kwds)
61{
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010062 PyObject *tmp;
63
Christian Heimes90aa7642007-12-19 02:45:37 +000064 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000065 return -1;
66
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010067 tmp = self->args;
Thomas Wouters477c8d52006-05-27 19:21:47 +000068 self->args = args;
69 Py_INCREF(self->args);
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010070 Py_XDECREF(tmp);
Thomas Wouters477c8d52006-05-27 19:21:47 +000071
Thomas Wouters477c8d52006-05-27 19:21:47 +000072 return 0;
73}
74
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000076BaseException_clear(PyBaseExceptionObject *self)
77{
78 Py_CLEAR(self->dict);
79 Py_CLEAR(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000080 Py_CLEAR(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +000081 Py_CLEAR(self->cause);
82 Py_CLEAR(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +000083 return 0;
84}
85
86static void
87BaseException_dealloc(PyBaseExceptionObject *self)
88{
Thomas Wouters89f507f2006-12-13 04:49:30 +000089 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000090 BaseException_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +000091 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +000092}
93
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094static int
Thomas Wouters477c8d52006-05-27 19:21:47 +000095BaseException_traverse(PyBaseExceptionObject *self, visitproc visit, void *arg)
96{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097 Py_VISIT(self->dict);
Thomas Wouters477c8d52006-05-27 19:21:47 +000098 Py_VISIT(self->args);
Collin Winter828f04a2007-08-31 00:04:24 +000099 Py_VISIT(self->traceback);
Collin Winter1966f1c2007-09-01 20:26:44 +0000100 Py_VISIT(self->cause);
101 Py_VISIT(self->context);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102 return 0;
103}
104
105static PyObject *
106BaseException_str(PyBaseExceptionObject *self)
107{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000108 switch (PyTuple_GET_SIZE(self->args)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 case 0:
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +0000110 return PyUnicode_FromString("");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000111 case 1:
Thomas Heller519a0422007-11-15 20:48:54 +0000112 return PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000113 default:
Thomas Heller519a0422007-11-15 20:48:54 +0000114 return PyObject_Str(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116}
117
118static PyObject *
119BaseException_repr(PyBaseExceptionObject *self)
120{
Serhiy Storchakac6792272013-10-19 21:03:34 +0300121 const char *name;
122 const char *dot;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123
Serhiy Storchakac6792272013-10-19 21:03:34 +0300124 name = Py_TYPE(self)->tp_name;
125 dot = (const char *) strrchr(name, '.');
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 if (dot != NULL) name = dot+1;
127
Walter Dörwald7569dfe2007-05-19 21:49:49 +0000128 return PyUnicode_FromFormat("%s%R", name, self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000129}
130
131/* Pickling support */
132static PyObject *
133BaseException_reduce(PyBaseExceptionObject *self)
134{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000135 if (self->args && self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +0000136 return PyTuple_Pack(3, Py_TYPE(self), self->args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137 else
Christian Heimes90aa7642007-12-19 02:45:37 +0000138 return PyTuple_Pack(2, Py_TYPE(self), self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000139}
140
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000141/*
142 * Needed for backward compatibility, since exceptions used to store
143 * all their attributes in the __dict__. Code is taken from cPickle's
144 * load_build function.
145 */
146static PyObject *
147BaseException_setstate(PyObject *self, PyObject *state)
148{
149 PyObject *d_key, *d_value;
150 Py_ssize_t i = 0;
151
152 if (state != Py_None) {
153 if (!PyDict_Check(state)) {
154 PyErr_SetString(PyExc_TypeError, "state is not a dictionary");
155 return NULL;
156 }
157 while (PyDict_Next(state, &i, &d_key, &d_value)) {
158 if (PyObject_SetAttr(self, d_key, d_value) < 0)
159 return NULL;
160 }
161 }
162 Py_RETURN_NONE;
163}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164
Collin Winter828f04a2007-08-31 00:04:24 +0000165static PyObject *
166BaseException_with_traceback(PyObject *self, PyObject *tb) {
167 if (PyException_SetTraceback(self, tb))
168 return NULL;
169
170 Py_INCREF(self);
171 return self;
172}
173
Georg Brandl76941002008-05-05 21:38:47 +0000174PyDoc_STRVAR(with_traceback_doc,
175"Exception.with_traceback(tb) --\n\
176 set self.__traceback__ to tb and return self.");
177
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178
179static PyMethodDef BaseException_methods[] = {
180 {"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000181 {"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
Georg Brandl76941002008-05-05 21:38:47 +0000182 {"with_traceback", (PyCFunction)BaseException_with_traceback, METH_O,
183 with_traceback_doc},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000184 {NULL, NULL, 0, NULL},
185};
186
Thomas Wouters477c8d52006-05-27 19:21:47 +0000187static PyObject *
188BaseException_get_args(PyBaseExceptionObject *self)
189{
190 if (self->args == NULL) {
191 Py_INCREF(Py_None);
192 return Py_None;
193 }
194 Py_INCREF(self->args);
195 return self->args;
196}
197
198static int
199BaseException_set_args(PyBaseExceptionObject *self, PyObject *val)
200{
201 PyObject *seq;
202 if (val == NULL) {
203 PyErr_SetString(PyExc_TypeError, "args may not be deleted");
204 return -1;
205 }
206 seq = PySequence_Tuple(val);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500207 if (!seq)
208 return -1;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000209 Py_CLEAR(self->args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210 self->args = seq;
211 return 0;
212}
213
Collin Winter828f04a2007-08-31 00:04:24 +0000214static PyObject *
215BaseException_get_tb(PyBaseExceptionObject *self)
216{
217 if (self->traceback == NULL) {
218 Py_INCREF(Py_None);
219 return Py_None;
220 }
221 Py_INCREF(self->traceback);
222 return self->traceback;
223}
224
225static int
226BaseException_set_tb(PyBaseExceptionObject *self, PyObject *tb)
227{
228 if (tb == NULL) {
229 PyErr_SetString(PyExc_TypeError, "__traceback__ may not be deleted");
230 return -1;
231 }
232 else if (!(tb == Py_None || PyTraceBack_Check(tb))) {
233 PyErr_SetString(PyExc_TypeError,
234 "__traceback__ must be a traceback or None");
235 return -1;
236 }
237
238 Py_XINCREF(tb);
239 Py_XDECREF(self->traceback);
240 self->traceback = tb;
241 return 0;
242}
243
Georg Brandlab6f2f62009-03-31 04:16:10 +0000244static PyObject *
245BaseException_get_context(PyObject *self) {
246 PyObject *res = PyException_GetContext(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500247 if (res)
248 return res; /* new reference already returned above */
Georg Brandlab6f2f62009-03-31 04:16:10 +0000249 Py_RETURN_NONE;
250}
251
252static int
253BaseException_set_context(PyObject *self, PyObject *arg) {
254 if (arg == NULL) {
255 PyErr_SetString(PyExc_TypeError, "__context__ may not be deleted");
256 return -1;
257 } else if (arg == Py_None) {
258 arg = NULL;
259 } else if (!PyExceptionInstance_Check(arg)) {
260 PyErr_SetString(PyExc_TypeError, "exception context must be None "
261 "or derive from BaseException");
262 return -1;
263 } else {
264 /* PyException_SetContext steals this reference */
265 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 }
Georg Brandlab6f2f62009-03-31 04:16:10 +0000267 PyException_SetContext(self, arg);
268 return 0;
269}
270
271static PyObject *
272BaseException_get_cause(PyObject *self) {
273 PyObject *res = PyException_GetCause(self);
Benjamin Peterson90b13582012-02-03 19:22:31 -0500274 if (res)
275 return res; /* new reference already returned above */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700276 Py_RETURN_NONE;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000277}
278
279static int
280BaseException_set_cause(PyObject *self, PyObject *arg) {
281 if (arg == NULL) {
282 PyErr_SetString(PyExc_TypeError, "__cause__ may not be deleted");
283 return -1;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700284 } else if (arg == Py_None) {
285 arg = NULL;
286 } else if (!PyExceptionInstance_Check(arg)) {
287 PyErr_SetString(PyExc_TypeError, "exception cause must be None "
288 "or derive from BaseException");
289 return -1;
290 } else {
291 /* PyException_SetCause steals this reference */
292 Py_INCREF(arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 }
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700294 PyException_SetCause(self, arg);
295 return 0;
Georg Brandlab6f2f62009-03-31 04:16:10 +0000296}
297
Guido van Rossum360e4b82007-05-14 22:51:27 +0000298
Thomas Wouters477c8d52006-05-27 19:21:47 +0000299static PyGetSetDef BaseException_getset[] = {
Benjamin Peterson23d7f122012-02-19 20:02:57 -0500300 {"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000301 {"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
Collin Winter828f04a2007-08-31 00:04:24 +0000302 {"__traceback__", (getter)BaseException_get_tb, (setter)BaseException_set_tb},
Georg Brandlab6f2f62009-03-31 04:16:10 +0000303 {"__context__", (getter)BaseException_get_context,
304 (setter)BaseException_set_context, PyDoc_STR("exception context")},
305 {"__cause__", (getter)BaseException_get_cause,
306 (setter)BaseException_set_cause, PyDoc_STR("exception cause")},
Thomas Wouters477c8d52006-05-27 19:21:47 +0000307 {NULL},
308};
309
310
Collin Winter828f04a2007-08-31 00:04:24 +0000311PyObject *
312PyException_GetTraceback(PyObject *self) {
313 PyBaseExceptionObject *base_self = (PyBaseExceptionObject *)self;
314 Py_XINCREF(base_self->traceback);
315 return base_self->traceback;
316}
317
318
319int
320PyException_SetTraceback(PyObject *self, PyObject *tb) {
321 return BaseException_set_tb((PyBaseExceptionObject *)self, tb);
322}
323
324PyObject *
325PyException_GetCause(PyObject *self) {
326 PyObject *cause = ((PyBaseExceptionObject *)self)->cause;
327 Py_XINCREF(cause);
328 return cause;
329}
330
331/* Steals a reference to cause */
332void
333PyException_SetCause(PyObject *self, PyObject *cause) {
334 PyObject *old_cause = ((PyBaseExceptionObject *)self)->cause;
335 ((PyBaseExceptionObject *)self)->cause = cause;
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700336 ((PyBaseExceptionObject *)self)->suppress_context = 1;
Collin Winter828f04a2007-08-31 00:04:24 +0000337 Py_XDECREF(old_cause);
338}
339
340PyObject *
341PyException_GetContext(PyObject *self) {
342 PyObject *context = ((PyBaseExceptionObject *)self)->context;
343 Py_XINCREF(context);
344 return context;
345}
346
347/* Steals a reference to context */
348void
349PyException_SetContext(PyObject *self, PyObject *context) {
350 PyObject *old_context = ((PyBaseExceptionObject *)self)->context;
351 ((PyBaseExceptionObject *)self)->context = context;
352 Py_XDECREF(old_context);
353}
354
355
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700356static struct PyMemberDef BaseException_members[] = {
357 {"__suppress_context__", T_BOOL,
Antoine Pitrou32bc80c2012-05-16 12:51:55 +0200358 offsetof(PyBaseExceptionObject, suppress_context)},
359 {NULL}
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700360};
361
362
Thomas Wouters477c8d52006-05-27 19:21:47 +0000363static PyTypeObject _PyExc_BaseException = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000364 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +0000365 "BaseException", /*tp_name*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366 sizeof(PyBaseExceptionObject), /*tp_basicsize*/
367 0, /*tp_itemsize*/
368 (destructor)BaseException_dealloc, /*tp_dealloc*/
369 0, /*tp_print*/
370 0, /*tp_getattr*/
371 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +0000372 0, /* tp_reserved; */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 (reprfunc)BaseException_repr, /*tp_repr*/
374 0, /*tp_as_number*/
Brett Cannonba7bf492007-02-27 00:15:55 +0000375 0, /*tp_as_sequence*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 0, /*tp_as_mapping*/
377 0, /*tp_hash */
378 0, /*tp_call*/
379 (reprfunc)BaseException_str, /*tp_str*/
380 PyObject_GenericGetAttr, /*tp_getattro*/
381 PyObject_GenericSetAttr, /*tp_setattro*/
382 0, /*tp_as_buffer*/
Thomas Wouters27d517b2007-02-25 20:39:11 +0000383 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
Thomas Wouters477c8d52006-05-27 19:21:47 +0000385 PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
386 (traverseproc)BaseException_traverse, /* tp_traverse */
387 (inquiry)BaseException_clear, /* tp_clear */
388 0, /* tp_richcompare */
389 0, /* tp_weaklistoffset */
390 0, /* tp_iter */
391 0, /* tp_iternext */
392 BaseException_methods, /* tp_methods */
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700393 BaseException_members, /* tp_members */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000394 BaseException_getset, /* tp_getset */
395 0, /* tp_base */
396 0, /* tp_dict */
397 0, /* tp_descr_get */
398 0, /* tp_descr_set */
399 offsetof(PyBaseExceptionObject, dict), /* tp_dictoffset */
400 (initproc)BaseException_init, /* tp_init */
401 0, /* tp_alloc */
402 BaseException_new, /* tp_new */
403};
404/* the CPython API expects exceptions to be (PyObject *) - both a hold-over
405from the previous implmentation and also allowing Python objects to be used
406in the API */
407PyObject *PyExc_BaseException = (PyObject *)&_PyExc_BaseException;
408
409/* note these macros omit the last semicolon so the macro invocation may
410 * include it and not look strange.
411 */
412#define SimpleExtendsException(EXCBASE, EXCNAME, EXCDOC) \
413static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000414 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000415 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000416 sizeof(PyBaseExceptionObject), \
417 0, (destructor)BaseException_dealloc, 0, 0, 0, 0, 0, 0, 0, \
418 0, 0, 0, 0, 0, 0, 0, \
419 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
420 PyDoc_STR(EXCDOC), (traverseproc)BaseException_traverse, \
421 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
422 0, 0, 0, offsetof(PyBaseExceptionObject, dict), \
423 (initproc)BaseException_init, 0, BaseException_new,\
424}; \
425PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
426
427#define MiddlingExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCDOC) \
428static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000429 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000430 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431 sizeof(Py ## EXCSTORE ## Object), \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000432 0, (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433 0, 0, 0, 0, 0, \
434 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000435 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
436 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, 0, 0, 0, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200438 (initproc)EXCSTORE ## _init, 0, 0, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439}; \
440PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
441
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200442#define ComplexExtendsException(EXCBASE, EXCNAME, EXCSTORE, EXCNEW, \
443 EXCMETHODS, EXCMEMBERS, EXCGETSET, \
444 EXCSTR, EXCDOC) \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445static PyTypeObject _PyExc_ ## EXCNAME = { \
Martin v. Löwis9f2e3462007-07-21 17:22:18 +0000446 PyVarObject_HEAD_INIT(NULL, 0) \
Neal Norwitz2633c692007-02-26 22:22:47 +0000447 # EXCNAME, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448 sizeof(Py ## EXCSTORE ## Object), 0, \
449 (destructor)EXCSTORE ## _dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \
450 (reprfunc)EXCSTR, 0, 0, 0, \
451 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, \
452 PyDoc_STR(EXCDOC), (traverseproc)EXCSTORE ## _traverse, \
453 (inquiry)EXCSTORE ## _clear, 0, 0, 0, 0, EXCMETHODS, \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200454 EXCMEMBERS, EXCGETSET, &_ ## EXCBASE, \
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455 0, 0, 0, offsetof(Py ## EXCSTORE ## Object, dict), \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200456 (initproc)EXCSTORE ## _init, 0, EXCNEW,\
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457}; \
458PyObject *PyExc_ ## EXCNAME = (PyObject *)&_PyExc_ ## EXCNAME
459
460
461/*
462 * Exception extends BaseException
463 */
464SimpleExtendsException(PyExc_BaseException, Exception,
465 "Common base class for all non-exit exceptions.");
466
467
468/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000469 * TypeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000470 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000471SimpleExtendsException(PyExc_Exception, TypeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000472 "Inappropriate argument type.");
473
474
475/*
476 * StopIteration extends Exception
477 */
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000478
479static PyMemberDef StopIteration_members[] = {
480 {"value", T_OBJECT, offsetof(PyStopIterationObject, value), 0,
481 PyDoc_STR("generator return value")},
482 {NULL} /* Sentinel */
483};
484
485static int
486StopIteration_init(PyStopIterationObject *self, PyObject *args, PyObject *kwds)
487{
488 Py_ssize_t size = PyTuple_GET_SIZE(args);
489 PyObject *value;
490
491 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
492 return -1;
493 Py_CLEAR(self->value);
494 if (size > 0)
495 value = PyTuple_GET_ITEM(args, 0);
496 else
497 value = Py_None;
498 Py_INCREF(value);
499 self->value = value;
500 return 0;
501}
502
503static int
504StopIteration_clear(PyStopIterationObject *self)
505{
506 Py_CLEAR(self->value);
507 return BaseException_clear((PyBaseExceptionObject *)self);
508}
509
510static void
511StopIteration_dealloc(PyStopIterationObject *self)
512{
513 _PyObject_GC_UNTRACK(self);
514 StopIteration_clear(self);
515 Py_TYPE(self)->tp_free((PyObject *)self);
516}
517
518static int
519StopIteration_traverse(PyStopIterationObject *self, visitproc visit, void *arg)
520{
521 Py_VISIT(self->value);
522 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
523}
524
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000525ComplexExtendsException(
526 PyExc_Exception, /* base */
527 StopIteration, /* name */
528 StopIteration, /* prefix for *_init, etc */
529 0, /* new */
530 0, /* methods */
531 StopIteration_members, /* members */
532 0, /* getset */
533 0, /* str */
534 "Signal the end from iterator.__next__()."
535);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000536
537
538/*
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000539 * GeneratorExit extends BaseException
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 */
Christian Heimescbf3b5c2007-12-03 21:02:03 +0000541SimpleExtendsException(PyExc_BaseException, GeneratorExit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000542 "Request that a generator exit.");
543
544
545/*
546 * SystemExit extends BaseException
547 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000548
549static int
550SystemExit_init(PySystemExitObject *self, PyObject *args, PyObject *kwds)
551{
552 Py_ssize_t size = PyTuple_GET_SIZE(args);
553
554 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
555 return -1;
556
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000557 if (size == 0)
558 return 0;
559 Py_CLEAR(self->code);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000560 if (size == 1)
561 self->code = PyTuple_GET_ITEM(args, 0);
Victor Stinner92236e52011-05-26 14:25:54 +0200562 else /* size > 1 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 self->code = args;
564 Py_INCREF(self->code);
565 return 0;
566}
567
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000568static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000569SystemExit_clear(PySystemExitObject *self)
570{
571 Py_CLEAR(self->code);
572 return BaseException_clear((PyBaseExceptionObject *)self);
573}
574
575static void
576SystemExit_dealloc(PySystemExitObject *self)
577{
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000579 SystemExit_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +0000580 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581}
582
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000583static int
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584SystemExit_traverse(PySystemExitObject *self, visitproc visit, void *arg)
585{
586 Py_VISIT(self->code);
587 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
588}
589
590static PyMemberDef SystemExit_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +0000591 {"code", T_OBJECT, offsetof(PySystemExitObject, code), 0,
592 PyDoc_STR("exception code")},
593 {NULL} /* Sentinel */
594};
595
596ComplexExtendsException(PyExc_BaseException, SystemExit, SystemExit,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200597 0, 0, SystemExit_members, 0, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000598 "Request to exit from the interpreter.");
599
600/*
601 * KeyboardInterrupt extends BaseException
602 */
603SimpleExtendsException(PyExc_BaseException, KeyboardInterrupt,
604 "Program interrupted by user.");
605
606
607/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000608 * ImportError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000609 */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000610
Brett Cannon79ec55e2012-04-12 20:24:54 -0400611static int
612ImportError_init(PyImportErrorObject *self, PyObject *args, PyObject *kwds)
613{
614 PyObject *msg = NULL;
615 PyObject *name = NULL;
616 PyObject *path = NULL;
617
618/* Macro replacement doesn't allow ## to start the first line of a macro,
619 so we move the assignment and NULL check into the if-statement. */
620#define GET_KWD(kwd) { \
621 kwd = PyDict_GetItemString(kwds, #kwd); \
622 if (kwd) { \
623 Py_CLEAR(self->kwd); \
624 self->kwd = kwd; \
625 Py_INCREF(self->kwd);\
626 if (PyDict_DelItemString(kwds, #kwd)) \
627 return -1; \
628 } \
629 }
630
631 if (kwds) {
632 GET_KWD(name);
633 GET_KWD(path);
634 }
635
636 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
637 return -1;
638 if (PyTuple_GET_SIZE(args) != 1)
639 return 0;
640 if (!PyArg_UnpackTuple(args, "ImportError", 1, 1, &msg))
641 return -1;
642
643 Py_CLEAR(self->msg); /* replacing */
644 self->msg = msg;
645 Py_INCREF(self->msg);
646
647 return 0;
648}
649
650static int
651ImportError_clear(PyImportErrorObject *self)
652{
653 Py_CLEAR(self->msg);
654 Py_CLEAR(self->name);
655 Py_CLEAR(self->path);
656 return BaseException_clear((PyBaseExceptionObject *)self);
657}
658
659static void
660ImportError_dealloc(PyImportErrorObject *self)
661{
662 _PyObject_GC_UNTRACK(self);
663 ImportError_clear(self);
664 Py_TYPE(self)->tp_free((PyObject *)self);
665}
666
667static int
668ImportError_traverse(PyImportErrorObject *self, visitproc visit, void *arg)
669{
670 Py_VISIT(self->msg);
671 Py_VISIT(self->name);
672 Py_VISIT(self->path);
673 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
674}
675
676static PyObject *
677ImportError_str(PyImportErrorObject *self)
678{
Brett Cannon07c6e712012-08-24 13:05:09 -0400679 if (self->msg && PyUnicode_CheckExact(self->msg)) {
Brett Cannon79ec55e2012-04-12 20:24:54 -0400680 Py_INCREF(self->msg);
681 return self->msg;
682 }
683 else {
684 return BaseException_str((PyBaseExceptionObject *)self);
685 }
686}
687
688static PyMemberDef ImportError_members[] = {
689 {"msg", T_OBJECT, offsetof(PyImportErrorObject, msg), 0,
690 PyDoc_STR("exception message")},
691 {"name", T_OBJECT, offsetof(PyImportErrorObject, name), 0,
692 PyDoc_STR("module name")},
693 {"path", T_OBJECT, offsetof(PyImportErrorObject, path), 0,
694 PyDoc_STR("module path")},
695 {NULL} /* Sentinel */
696};
697
698static PyMethodDef ImportError_methods[] = {
699 {NULL}
700};
701
702ComplexExtendsException(PyExc_Exception, ImportError,
703 ImportError, 0 /* new */,
704 ImportError_methods, ImportError_members,
705 0 /* getset */, ImportError_str,
706 "Import can't find module, or can't find name in "
707 "module.");
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708
709/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200710 * OSError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711 */
712
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200713#ifdef MS_WINDOWS
714#include "errmap.h"
715#endif
716
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717/* Where a function has a single filename, such as open() or some
718 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
719 * called, giving a third argument which is the filename. But, so
720 * that old code using in-place unpacking doesn't break, e.g.:
721 *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200722 * except OSError, (errno, strerror):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000723 *
724 * we hack args so that it only contains two items. This also
725 * means we need our own __str__() which prints out the filename
726 * when it was supplied.
Larry Hastingsb0827312014-02-09 22:05:19 -0800727 *
728 * (If a function has two filenames, such as rename(), symlink(),
Larry Hastings8f9f0f12014-02-10 03:43:57 -0800729 * or copy(), PyErr_SetFromErrnoWithFilenameObjects() is called,
730 * which allows passing in a second filename.)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000731 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200732
Antoine Pitroue0e27352011-12-15 14:31:28 +0100733/* This function doesn't cleanup on error, the caller should */
734static int
735oserror_parse_args(PyObject **p_args,
736 PyObject **myerrno, PyObject **strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800737 PyObject **filename, PyObject **filename2
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200738#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100739 , PyObject **winerror
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200740#endif
Antoine Pitroue0e27352011-12-15 14:31:28 +0100741 )
742{
743 Py_ssize_t nargs;
744 PyObject *args = *p_args;
Larry Hastingsb0827312014-02-09 22:05:19 -0800745#ifndef MS_WINDOWS
746 /*
747 * ignored on non-Windows platforms,
748 * but parsed so OSError has a consistent signature
749 */
750 PyObject *_winerror = NULL;
751 PyObject **winerror = &_winerror;
752#endif /* MS_WINDOWS */
Thomas Wouters477c8d52006-05-27 19:21:47 +0000753
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200754 nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000755
Larry Hastingsb0827312014-02-09 22:05:19 -0800756 if (nargs >= 2 && nargs <= 5) {
757 if (!PyArg_UnpackTuple(args, "OSError", 2, 5,
758 myerrno, strerror,
759 filename, winerror, filename2))
Antoine Pitroue0e27352011-12-15 14:31:28 +0100760 return -1;
Larry Hastingsb0827312014-02-09 22:05:19 -0800761#ifdef MS_WINDOWS
Antoine Pitroue0e27352011-12-15 14:31:28 +0100762 if (*winerror && PyLong_Check(*winerror)) {
763 long errcode, winerrcode;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200764 PyObject *newargs;
765 Py_ssize_t i;
766
Antoine Pitroue0e27352011-12-15 14:31:28 +0100767 winerrcode = PyLong_AsLong(*winerror);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200768 if (winerrcode == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100769 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200770 /* Set errno to the corresponding POSIX errno (overriding
771 first argument). Windows Socket error codes (>= 10000)
772 have the same value as their POSIX counterparts.
773 */
774 if (winerrcode < 10000)
775 errcode = winerror_to_errno(winerrcode);
776 else
777 errcode = winerrcode;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100778 *myerrno = PyLong_FromLong(errcode);
779 if (!*myerrno)
780 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200781 newargs = PyTuple_New(nargs);
782 if (!newargs)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100783 return -1;
784 PyTuple_SET_ITEM(newargs, 0, *myerrno);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200785 for (i = 1; i < nargs; i++) {
786 PyObject *val = PyTuple_GET_ITEM(args, i);
787 Py_INCREF(val);
788 PyTuple_SET_ITEM(newargs, i, val);
789 }
790 Py_DECREF(args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100791 args = *p_args = newargs;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200792 }
Larry Hastingsb0827312014-02-09 22:05:19 -0800793#endif /* MS_WINDOWS */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200794 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000795
Antoine Pitroue0e27352011-12-15 14:31:28 +0100796 return 0;
797}
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798
Antoine Pitroue0e27352011-12-15 14:31:28 +0100799static int
800oserror_init(PyOSErrorObject *self, PyObject **p_args,
801 PyObject *myerrno, PyObject *strerror,
Larry Hastingsb0827312014-02-09 22:05:19 -0800802 PyObject *filename, PyObject *filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100803#ifdef MS_WINDOWS
804 , PyObject *winerror
805#endif
806 )
807{
808 PyObject *args = *p_args;
809 Py_ssize_t nargs = PyTuple_GET_SIZE(args);
Thomas Wouters477c8d52006-05-27 19:21:47 +0000810
811 /* self->filename will remain Py_None otherwise */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200812 if (filename && filename != Py_None) {
Antoine Pitroue0e27352011-12-15 14:31:28 +0100813 if (Py_TYPE(self) == (PyTypeObject *) PyExc_BlockingIOError &&
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200814 PyNumber_Check(filename)) {
815 /* BlockingIOError's 3rd argument can be the number of
816 * characters written.
817 */
818 self->written = PyNumber_AsSsize_t(filename, PyExc_ValueError);
819 if (self->written == -1 && PyErr_Occurred())
Antoine Pitroue0e27352011-12-15 14:31:28 +0100820 return -1;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200821 }
822 else {
823 Py_INCREF(filename);
824 self->filename = filename;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000825
Larry Hastingsb0827312014-02-09 22:05:19 -0800826 if (filename2 && filename2 != Py_None) {
827 Py_INCREF(filename2);
828 self->filename2 = filename2;
829 }
830
831 if (nargs >= 2 && nargs <= 5) {
832 /* filename, filename2, and winerror are removed from the args tuple
833 (for compatibility purposes, see test_exceptions.py) */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100834 PyObject *subslice = PyTuple_GetSlice(args, 0, 2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200835 if (!subslice)
Antoine Pitroue0e27352011-12-15 14:31:28 +0100836 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200838 Py_DECREF(args); /* replacing args */
Antoine Pitroue0e27352011-12-15 14:31:28 +0100839 *p_args = args = subslice;
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200840 }
841 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000842 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200843 Py_XINCREF(myerrno);
844 self->myerrno = myerrno;
845
846 Py_XINCREF(strerror);
847 self->strerror = strerror;
848
849#ifdef MS_WINDOWS
850 Py_XINCREF(winerror);
851 self->winerror = winerror;
852#endif
853
Antoine Pitroue0e27352011-12-15 14:31:28 +0100854 /* Steals the reference to args */
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200855 Py_CLEAR(self->args);
Antoine Pitroue0e27352011-12-15 14:31:28 +0100856 self->args = args;
Victor Stinner46ef3192013-11-14 22:31:41 +0100857 *p_args = args = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100858
859 return 0;
860}
861
862static PyObject *
863OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
864static int
865OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds);
866
867static int
868oserror_use_init(PyTypeObject *type)
869{
Martin Panter7462b6492015-11-02 03:37:02 +0000870 /* When __init__ is defined in an OSError subclass, we want any
Antoine Pitroue0e27352011-12-15 14:31:28 +0100871 extraneous argument to __new__ to be ignored. The only reasonable
872 solution, given __new__ takes a variable number of arguments,
873 is to defer arg parsing and initialization to __init__.
874
875 But when __new__ is overriden as well, it should call our __new__
876 with the right arguments.
877
878 (see http://bugs.python.org/issue12555#msg148829 )
879 */
880 if (type->tp_init != (initproc) OSError_init &&
881 type->tp_new == (newfunc) OSError_new) {
882 assert((PyObject *) type != PyExc_OSError);
883 return 1;
884 }
885 return 0;
886}
887
888static PyObject *
889OSError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
890{
891 PyOSErrorObject *self = NULL;
Larry Hastingsb0827312014-02-09 22:05:19 -0800892 PyObject *myerrno = NULL, *strerror = NULL;
893 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100894#ifdef MS_WINDOWS
895 PyObject *winerror = NULL;
896#endif
897
Victor Stinner46ef3192013-11-14 22:31:41 +0100898 Py_INCREF(args);
899
Antoine Pitroue0e27352011-12-15 14:31:28 +0100900 if (!oserror_use_init(type)) {
901 if (!_PyArg_NoKeywords(type->tp_name, kwds))
Victor Stinner46ef3192013-11-14 22:31:41 +0100902 goto error;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100903
Larry Hastingsb0827312014-02-09 22:05:19 -0800904 if (oserror_parse_args(&args, &myerrno, &strerror,
905 &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100906#ifdef MS_WINDOWS
907 , &winerror
908#endif
909 ))
910 goto error;
911
912 if (myerrno && PyLong_Check(myerrno) &&
913 errnomap && (PyObject *) type == PyExc_OSError) {
914 PyObject *newtype;
915 newtype = PyDict_GetItem(errnomap, myerrno);
916 if (newtype) {
917 assert(PyType_Check(newtype));
918 type = (PyTypeObject *) newtype;
919 }
920 else if (PyErr_Occurred())
921 goto error;
922 }
923 }
924
925 self = (PyOSErrorObject *) type->tp_alloc(type, 0);
926 if (!self)
927 goto error;
928
929 self->dict = NULL;
930 self->traceback = self->cause = self->context = NULL;
931 self->written = -1;
932
933 if (!oserror_use_init(type)) {
Larry Hastingsb0827312014-02-09 22:05:19 -0800934 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100935#ifdef MS_WINDOWS
936 , winerror
937#endif
938 ))
939 goto error;
940 }
Antoine Pitrouf87289b2012-06-30 23:37:47 +0200941 else {
942 self->args = PyTuple_New(0);
943 if (self->args == NULL)
944 goto error;
945 }
Antoine Pitroue0e27352011-12-15 14:31:28 +0100946
Victor Stinner46ef3192013-11-14 22:31:41 +0100947 Py_XDECREF(args);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200948 return (PyObject *) self;
949
950error:
951 Py_XDECREF(args);
952 Py_XDECREF(self);
953 return NULL;
954}
955
956static int
Antoine Pitroue0e27352011-12-15 14:31:28 +0100957OSError_init(PyOSErrorObject *self, PyObject *args, PyObject *kwds)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200958{
Larry Hastingsb0827312014-02-09 22:05:19 -0800959 PyObject *myerrno = NULL, *strerror = NULL;
960 PyObject *filename = NULL, *filename2 = NULL;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100961#ifdef MS_WINDOWS
962 PyObject *winerror = NULL;
963#endif
964
965 if (!oserror_use_init(Py_TYPE(self)))
966 /* Everything already done in OSError_new */
967 return 0;
968
969 if (!_PyArg_NoKeywords(Py_TYPE(self)->tp_name, kwds))
970 return -1;
971
972 Py_INCREF(args);
Larry Hastingsb0827312014-02-09 22:05:19 -0800973 if (oserror_parse_args(&args, &myerrno, &strerror, &filename, &filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100974#ifdef MS_WINDOWS
975 , &winerror
976#endif
977 ))
978 goto error;
979
Larry Hastingsb0827312014-02-09 22:05:19 -0800980 if (oserror_init(self, &args, myerrno, strerror, filename, filename2
Antoine Pitroue0e27352011-12-15 14:31:28 +0100981#ifdef MS_WINDOWS
982 , winerror
983#endif
984 ))
985 goto error;
986
Thomas Wouters477c8d52006-05-27 19:21:47 +0000987 return 0;
Antoine Pitroue0e27352011-12-15 14:31:28 +0100988
989error:
990 Py_XDECREF(args);
991 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992}
993
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000994static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200995OSError_clear(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000996{
997 Py_CLEAR(self->myerrno);
998 Py_CLEAR(self->strerror);
999 Py_CLEAR(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001000 Py_CLEAR(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001001#ifdef MS_WINDOWS
1002 Py_CLEAR(self->winerror);
1003#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004 return BaseException_clear((PyBaseExceptionObject *)self);
1005}
1006
1007static void
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001008OSError_dealloc(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001010 _PyObject_GC_UNTRACK(self);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001011 OSError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001012 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001013}
1014
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001015static int
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001016OSError_traverse(PyOSErrorObject *self, visitproc visit,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001017 void *arg)
1018{
1019 Py_VISIT(self->myerrno);
1020 Py_VISIT(self->strerror);
1021 Py_VISIT(self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001022 Py_VISIT(self->filename2);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001023#ifdef MS_WINDOWS
1024 Py_VISIT(self->winerror);
1025#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00001026 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1027}
1028
1029static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001030OSError_str(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001031{
Larry Hastingsb0827312014-02-09 22:05:19 -08001032#define OR_NONE(x) ((x)?(x):Py_None)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001033#ifdef MS_WINDOWS
1034 /* If available, winerror has the priority over myerrno */
Larry Hastingsb0827312014-02-09 22:05:19 -08001035 if (self->winerror && self->filename) {
1036 if (self->filename2) {
1037 return PyUnicode_FromFormat("[WinError %S] %S: %R -> %R",
1038 OR_NONE(self->winerror),
1039 OR_NONE(self->strerror),
1040 self->filename,
1041 self->filename2);
1042 } else {
1043 return PyUnicode_FromFormat("[WinError %S] %S: %R",
1044 OR_NONE(self->winerror),
1045 OR_NONE(self->strerror),
1046 self->filename);
1047 }
1048 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001049 if (self->winerror && self->strerror)
Richard Oudkerk30147712012-08-28 19:33:26 +01001050 return PyUnicode_FromFormat("[WinError %S] %S",
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001051 self->winerror ? self->winerror: Py_None,
1052 self->strerror ? self->strerror: Py_None);
1053#endif
Larry Hastingsb0827312014-02-09 22:05:19 -08001054 if (self->filename) {
1055 if (self->filename2) {
1056 return PyUnicode_FromFormat("[Errno %S] %S: %R -> %R",
1057 OR_NONE(self->myerrno),
1058 OR_NONE(self->strerror),
1059 self->filename,
1060 self->filename2);
1061 } else {
1062 return PyUnicode_FromFormat("[Errno %S] %S: %R",
1063 OR_NONE(self->myerrno),
1064 OR_NONE(self->strerror),
1065 self->filename);
1066 }
1067 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001068 if (self->myerrno && self->strerror)
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001069 return PyUnicode_FromFormat("[Errno %S] %S",
1070 self->myerrno ? self->myerrno: Py_None,
1071 self->strerror ? self->strerror: Py_None);
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001072 return BaseException_str((PyBaseExceptionObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073}
1074
Thomas Wouters477c8d52006-05-27 19:21:47 +00001075static PyObject *
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001076OSError_reduce(PyOSErrorObject *self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001077{
1078 PyObject *args = self->args;
1079 PyObject *res = NULL, *tmp;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001080
Thomas Wouters477c8d52006-05-27 19:21:47 +00001081 /* self->args is only the first two real arguments if there was a
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001082 * file name given to OSError. */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001083 if (PyTuple_GET_SIZE(args) == 2 && self->filename) {
Larry Hastingsb0827312014-02-09 22:05:19 -08001084 Py_ssize_t size = self->filename2 ? 5 : 3;
1085 args = PyTuple_New(size);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001086 if (!args)
1087 return NULL;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001088
1089 tmp = PyTuple_GET_ITEM(self->args, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001090 Py_INCREF(tmp);
1091 PyTuple_SET_ITEM(args, 0, tmp);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001092
1093 tmp = PyTuple_GET_ITEM(self->args, 1);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001094 Py_INCREF(tmp);
1095 PyTuple_SET_ITEM(args, 1, tmp);
1096
1097 Py_INCREF(self->filename);
1098 PyTuple_SET_ITEM(args, 2, self->filename);
Larry Hastingsb0827312014-02-09 22:05:19 -08001099
1100 if (self->filename2) {
1101 /*
1102 * This tuple is essentially used as OSError(*args).
1103 * So, to recreate filename2, we need to pass in
1104 * winerror as well.
1105 */
1106 Py_INCREF(Py_None);
1107 PyTuple_SET_ITEM(args, 3, Py_None);
1108
1109 /* filename2 */
1110 Py_INCREF(self->filename2);
1111 PyTuple_SET_ITEM(args, 4, self->filename2);
1112 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001113 } else
Thomas Wouters477c8d52006-05-27 19:21:47 +00001114 Py_INCREF(args);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001115
1116 if (self->dict)
Christian Heimes90aa7642007-12-19 02:45:37 +00001117 res = PyTuple_Pack(3, Py_TYPE(self), args, self->dict);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001118 else
Christian Heimes90aa7642007-12-19 02:45:37 +00001119 res = PyTuple_Pack(2, Py_TYPE(self), args);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001120 Py_DECREF(args);
1121 return res;
1122}
1123
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001124static PyObject *
1125OSError_written_get(PyOSErrorObject *self, void *context)
1126{
1127 if (self->written == -1) {
1128 PyErr_SetString(PyExc_AttributeError, "characters_written");
1129 return NULL;
1130 }
1131 return PyLong_FromSsize_t(self->written);
1132}
Thomas Wouters477c8d52006-05-27 19:21:47 +00001133
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001134static int
1135OSError_written_set(PyOSErrorObject *self, PyObject *arg, void *context)
1136{
1137 Py_ssize_t n;
1138 n = PyNumber_AsSsize_t(arg, PyExc_ValueError);
1139 if (n == -1 && PyErr_Occurred())
1140 return -1;
1141 self->written = n;
1142 return 0;
1143}
1144
1145static PyMemberDef OSError_members[] = {
1146 {"errno", T_OBJECT, offsetof(PyOSErrorObject, myerrno), 0,
1147 PyDoc_STR("POSIX exception code")},
1148 {"strerror", T_OBJECT, offsetof(PyOSErrorObject, strerror), 0,
1149 PyDoc_STR("exception strerror")},
1150 {"filename", T_OBJECT, offsetof(PyOSErrorObject, filename), 0,
1151 PyDoc_STR("exception filename")},
Larry Hastingsb0827312014-02-09 22:05:19 -08001152 {"filename2", T_OBJECT, offsetof(PyOSErrorObject, filename2), 0,
1153 PyDoc_STR("second exception filename")},
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001154#ifdef MS_WINDOWS
1155 {"winerror", T_OBJECT, offsetof(PyOSErrorObject, winerror), 0,
1156 PyDoc_STR("Win32 exception code")},
1157#endif
1158 {NULL} /* Sentinel */
1159};
1160
1161static PyMethodDef OSError_methods[] = {
1162 {"__reduce__", (PyCFunction)OSError_reduce, METH_NOARGS},
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 {NULL}
1164};
1165
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001166static PyGetSetDef OSError_getset[] = {
1167 {"characters_written", (getter) OSError_written_get,
1168 (setter) OSError_written_set, NULL},
1169 {NULL}
1170};
1171
1172
1173ComplexExtendsException(PyExc_Exception, OSError,
1174 OSError, OSError_new,
1175 OSError_methods, OSError_members, OSError_getset,
1176 OSError_str,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001177 "Base class for I/O related errors.");
1178
1179
1180/*
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001181 * Various OSError subclasses
Thomas Wouters477c8d52006-05-27 19:21:47 +00001182 */
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001183MiddlingExtendsException(PyExc_OSError, BlockingIOError, OSError,
1184 "I/O operation would block.");
1185MiddlingExtendsException(PyExc_OSError, ConnectionError, OSError,
1186 "Connection error.");
1187MiddlingExtendsException(PyExc_OSError, ChildProcessError, OSError,
1188 "Child process error.");
1189MiddlingExtendsException(PyExc_ConnectionError, BrokenPipeError, OSError,
1190 "Broken pipe.");
1191MiddlingExtendsException(PyExc_ConnectionError, ConnectionAbortedError, OSError,
1192 "Connection aborted.");
1193MiddlingExtendsException(PyExc_ConnectionError, ConnectionRefusedError, OSError,
1194 "Connection refused.");
1195MiddlingExtendsException(PyExc_ConnectionError, ConnectionResetError, OSError,
1196 "Connection reset.");
1197MiddlingExtendsException(PyExc_OSError, FileExistsError, OSError,
1198 "File already exists.");
1199MiddlingExtendsException(PyExc_OSError, FileNotFoundError, OSError,
1200 "File not found.");
1201MiddlingExtendsException(PyExc_OSError, IsADirectoryError, OSError,
1202 "Operation doesn't work on directories.");
1203MiddlingExtendsException(PyExc_OSError, NotADirectoryError, OSError,
1204 "Operation only works on directories.");
1205MiddlingExtendsException(PyExc_OSError, InterruptedError, OSError,
1206 "Interrupted by signal.");
1207MiddlingExtendsException(PyExc_OSError, PermissionError, OSError,
1208 "Not enough permissions.");
1209MiddlingExtendsException(PyExc_OSError, ProcessLookupError, OSError,
1210 "Process not found.");
1211MiddlingExtendsException(PyExc_OSError, TimeoutError, OSError,
1212 "Timeout expired.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001213
1214/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001215 * EOFError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001216 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001217SimpleExtendsException(PyExc_Exception, EOFError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001218 "Read beyond end of file.");
1219
1220
1221/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001222 * RuntimeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001223 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001224SimpleExtendsException(PyExc_Exception, RuntimeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001225 "Unspecified run-time error.");
1226
1227
1228/*
1229 * NotImplementedError extends RuntimeError
1230 */
1231SimpleExtendsException(PyExc_RuntimeError, NotImplementedError,
1232 "Method or function hasn't been implemented yet.");
1233
1234/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001235 * NameError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001236 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001237SimpleExtendsException(PyExc_Exception, NameError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238 "Name not found globally.");
1239
1240/*
1241 * UnboundLocalError extends NameError
1242 */
1243SimpleExtendsException(PyExc_NameError, UnboundLocalError,
1244 "Local name referenced but not bound to a value.");
1245
1246/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001247 * AttributeError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001248 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001249SimpleExtendsException(PyExc_Exception, AttributeError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001250 "Attribute not found.");
1251
1252
1253/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001254 * SyntaxError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001255 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001257/* Helper function to customise error message for some syntax errors */
1258static int _report_missing_parentheses(PySyntaxErrorObject *self);
1259
Thomas Wouters477c8d52006-05-27 19:21:47 +00001260static int
1261SyntaxError_init(PySyntaxErrorObject *self, PyObject *args, PyObject *kwds)
1262{
1263 PyObject *info = NULL;
1264 Py_ssize_t lenargs = PyTuple_GET_SIZE(args);
1265
1266 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1267 return -1;
1268
1269 if (lenargs >= 1) {
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001270 Py_CLEAR(self->msg);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271 self->msg = PyTuple_GET_ITEM(args, 0);
1272 Py_INCREF(self->msg);
1273 }
1274 if (lenargs == 2) {
1275 info = PyTuple_GET_ITEM(args, 1);
1276 info = PySequence_Tuple(info);
Benjamin Peterson90b13582012-02-03 19:22:31 -05001277 if (!info)
1278 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001280 if (PyTuple_GET_SIZE(info) != 4) {
1281 /* not a very good error message, but it's what Python 2.4 gives */
1282 PyErr_SetString(PyExc_IndexError, "tuple index out of range");
1283 Py_DECREF(info);
1284 return -1;
1285 }
1286
1287 Py_CLEAR(self->filename);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001288 self->filename = PyTuple_GET_ITEM(info, 0);
1289 Py_INCREF(self->filename);
1290
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001291 Py_CLEAR(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001292 self->lineno = PyTuple_GET_ITEM(info, 1);
1293 Py_INCREF(self->lineno);
1294
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001295 Py_CLEAR(self->offset);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001296 self->offset = PyTuple_GET_ITEM(info, 2);
1297 Py_INCREF(self->offset);
1298
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001299 Py_CLEAR(self->text);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001300 self->text = PyTuple_GET_ITEM(info, 3);
1301 Py_INCREF(self->text);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001302
1303 Py_DECREF(info);
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10001304
1305 /* Issue #21669: Custom error for 'print' & 'exec' as statements */
1306 if (self->text && PyUnicode_Check(self->text)) {
1307 if (_report_missing_parentheses(self) < 0) {
1308 return -1;
1309 }
1310 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001311 }
1312 return 0;
1313}
1314
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001315static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001316SyntaxError_clear(PySyntaxErrorObject *self)
1317{
1318 Py_CLEAR(self->msg);
1319 Py_CLEAR(self->filename);
1320 Py_CLEAR(self->lineno);
1321 Py_CLEAR(self->offset);
1322 Py_CLEAR(self->text);
1323 Py_CLEAR(self->print_file_and_line);
1324 return BaseException_clear((PyBaseExceptionObject *)self);
1325}
1326
1327static void
1328SyntaxError_dealloc(PySyntaxErrorObject *self)
1329{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001330 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001331 SyntaxError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001332 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001333}
1334
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001335static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001336SyntaxError_traverse(PySyntaxErrorObject *self, visitproc visit, void *arg)
1337{
1338 Py_VISIT(self->msg);
1339 Py_VISIT(self->filename);
1340 Py_VISIT(self->lineno);
1341 Py_VISIT(self->offset);
1342 Py_VISIT(self->text);
1343 Py_VISIT(self->print_file_and_line);
1344 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1345}
1346
1347/* This is called "my_basename" instead of just "basename" to avoid name
1348 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
1349 defined, and Python does define that. */
Victor Stinner6237daf2010-04-28 17:26:19 +00001350static PyObject*
1351my_basename(PyObject *name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001352{
Victor Stinner6237daf2010-04-28 17:26:19 +00001353 Py_ssize_t i, size, offset;
Victor Stinner31392e72011-10-05 20:14:23 +02001354 int kind;
1355 void *data;
1356
1357 if (PyUnicode_READY(name))
1358 return NULL;
1359 kind = PyUnicode_KIND(name);
1360 data = PyUnicode_DATA(name);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001361 size = PyUnicode_GET_LENGTH(name);
Victor Stinner6237daf2010-04-28 17:26:19 +00001362 offset = 0;
1363 for(i=0; i < size; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 if (PyUnicode_READ(kind, data, i) == SEP)
Victor Stinner6237daf2010-04-28 17:26:19 +00001365 offset = i + 1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 if (offset != 0)
1368 return PyUnicode_Substring(name, offset, size);
1369 else {
Victor Stinner6237daf2010-04-28 17:26:19 +00001370 Py_INCREF(name);
1371 return name;
1372 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001373}
1374
1375
1376static PyObject *
1377SyntaxError_str(PySyntaxErrorObject *self)
1378{
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001379 int have_lineno = 0;
Victor Stinner6237daf2010-04-28 17:26:19 +00001380 PyObject *filename;
1381 PyObject *result;
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001382 /* Below, we always ignore overflow errors, just printing -1.
1383 Still, we cannot allow an OverflowError to be raised, so
1384 we need to call PyLong_AsLongAndOverflow. */
1385 int overflow;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001386
1387 /* XXX -- do all the additional formatting with filename and
1388 lineno here */
1389
Neal Norwitzed2b7392007-08-26 04:51:10 +00001390 if (self->filename && PyUnicode_Check(self->filename)) {
Victor Stinner6237daf2010-04-28 17:26:19 +00001391 filename = my_basename(self->filename);
1392 if (filename == NULL)
1393 return NULL;
1394 } else {
1395 filename = NULL;
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001396 }
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001397 have_lineno = (self->lineno != NULL) && PyLong_CheckExact(self->lineno);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001399 if (!filename && !have_lineno)
Thomas Heller519a0422007-11-15 20:48:54 +00001400 return PyObject_Str(self->msg ? self->msg : Py_None);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001401
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001402 if (filename && have_lineno)
Victor Stinner6237daf2010-04-28 17:26:19 +00001403 result = PyUnicode_FromFormat("%S (%U, line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001404 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001405 filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Martin v. Löwis10a60b32007-07-18 02:28:27 +00001407 else if (filename)
Victor Stinner6237daf2010-04-28 17:26:19 +00001408 result = PyUnicode_FromFormat("%S (%U)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001409 self->msg ? self->msg : Py_None,
Victor Stinner6237daf2010-04-28 17:26:19 +00001410 filename);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001411 else /* only have_lineno */
Victor Stinner6237daf2010-04-28 17:26:19 +00001412 result = PyUnicode_FromFormat("%S (line %ld)",
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001413 self->msg ? self->msg : Py_None,
Martin v. Löwisd1a1d1e2007-12-04 22:10:37 +00001414 PyLong_AsLongAndOverflow(self->lineno, &overflow));
Victor Stinner6237daf2010-04-28 17:26:19 +00001415 Py_XDECREF(filename);
1416 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001417}
1418
1419static PyMemberDef SyntaxError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001420 {"msg", T_OBJECT, offsetof(PySyntaxErrorObject, msg), 0,
1421 PyDoc_STR("exception msg")},
1422 {"filename", T_OBJECT, offsetof(PySyntaxErrorObject, filename), 0,
1423 PyDoc_STR("exception filename")},
1424 {"lineno", T_OBJECT, offsetof(PySyntaxErrorObject, lineno), 0,
1425 PyDoc_STR("exception lineno")},
1426 {"offset", T_OBJECT, offsetof(PySyntaxErrorObject, offset), 0,
1427 PyDoc_STR("exception offset")},
1428 {"text", T_OBJECT, offsetof(PySyntaxErrorObject, text), 0,
1429 PyDoc_STR("exception text")},
1430 {"print_file_and_line", T_OBJECT,
1431 offsetof(PySyntaxErrorObject, print_file_and_line), 0,
1432 PyDoc_STR("exception print_file_and_line")},
1433 {NULL} /* Sentinel */
1434};
1435
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001436ComplexExtendsException(PyExc_Exception, SyntaxError, SyntaxError,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001437 0, 0, SyntaxError_members, 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001438 SyntaxError_str, "Invalid syntax.");
1439
1440
1441/*
1442 * IndentationError extends SyntaxError
1443 */
1444MiddlingExtendsException(PyExc_SyntaxError, IndentationError, SyntaxError,
1445 "Improper indentation.");
1446
1447
1448/*
1449 * TabError extends IndentationError
1450 */
1451MiddlingExtendsException(PyExc_IndentationError, TabError, SyntaxError,
1452 "Improper mixture of spaces and tabs.");
1453
1454
1455/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001456 * LookupError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001457 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001458SimpleExtendsException(PyExc_Exception, LookupError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001459 "Base class for lookup errors.");
1460
1461
1462/*
1463 * IndexError extends LookupError
1464 */
1465SimpleExtendsException(PyExc_LookupError, IndexError,
1466 "Sequence index out of range.");
1467
1468
1469/*
1470 * KeyError extends LookupError
1471 */
1472static PyObject *
1473KeyError_str(PyBaseExceptionObject *self)
1474{
1475 /* If args is a tuple of exactly one item, apply repr to args[0].
1476 This is done so that e.g. the exception raised by {}[''] prints
1477 KeyError: ''
1478 rather than the confusing
1479 KeyError
1480 alone. The downside is that if KeyError is raised with an explanatory
1481 string, that string will be displayed in quotes. Too bad.
1482 If args is anything else, use the default BaseException__str__().
1483 */
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001484 if (PyTuple_GET_SIZE(self->args) == 1) {
Walter Dörwaldf5bec7c2007-05-26 15:03:32 +00001485 return PyObject_Repr(PyTuple_GET_ITEM(self->args, 0));
Thomas Wouters477c8d52006-05-27 19:21:47 +00001486 }
1487 return BaseException_str(self);
1488}
1489
1490ComplexExtendsException(PyExc_LookupError, KeyError, BaseException,
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02001491 0, 0, 0, 0, KeyError_str, "Mapping key not found.");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001492
1493
1494/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001495 * ValueError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001497SimpleExtendsException(PyExc_Exception, ValueError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001498 "Inappropriate argument value (of correct type).");
1499
1500/*
1501 * UnicodeError extends ValueError
1502 */
1503
1504SimpleExtendsException(PyExc_ValueError, UnicodeError,
1505 "Unicode related error.");
1506
Thomas Wouters477c8d52006-05-27 19:21:47 +00001507static PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +00001508get_string(PyObject *attr, const char *name)
Walter Dörwald612344f2007-05-04 19:28:21 +00001509{
1510 if (!attr) {
1511 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1512 return NULL;
1513 }
1514
Christian Heimes72b710a2008-05-26 13:28:38 +00001515 if (!PyBytes_Check(attr)) {
Walter Dörwald612344f2007-05-04 19:28:21 +00001516 PyErr_Format(PyExc_TypeError, "%.200s attribute must be bytes", name);
1517 return NULL;
1518 }
1519 Py_INCREF(attr);
1520 return attr;
1521}
1522
1523static PyObject *
Thomas Wouters477c8d52006-05-27 19:21:47 +00001524get_unicode(PyObject *attr, const char *name)
1525{
1526 if (!attr) {
1527 PyErr_Format(PyExc_TypeError, "%.200s attribute not set", name);
1528 return NULL;
1529 }
1530
1531 if (!PyUnicode_Check(attr)) {
1532 PyErr_Format(PyExc_TypeError,
1533 "%.200s attribute must be unicode", name);
1534 return NULL;
1535 }
1536 Py_INCREF(attr);
1537 return attr;
1538}
1539
Walter Dörwaldd2034312007-05-18 16:29:38 +00001540static int
1541set_unicodefromstring(PyObject **attr, const char *value)
1542{
1543 PyObject *obj = PyUnicode_FromString(value);
1544 if (!obj)
1545 return -1;
1546 Py_CLEAR(*attr);
1547 *attr = obj;
1548 return 0;
1549}
1550
Thomas Wouters477c8d52006-05-27 19:21:47 +00001551PyObject *
1552PyUnicodeEncodeError_GetEncoding(PyObject *exc)
1553{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001554 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001555}
1556
1557PyObject *
1558PyUnicodeDecodeError_GetEncoding(PyObject *exc)
1559{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001560 return get_unicode(((PyUnicodeErrorObject *)exc)->encoding, "encoding");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001561}
1562
1563PyObject *
1564PyUnicodeEncodeError_GetObject(PyObject *exc)
1565{
1566 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1567}
1568
1569PyObject *
1570PyUnicodeDecodeError_GetObject(PyObject *exc)
1571{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001572 return get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001573}
1574
1575PyObject *
1576PyUnicodeTranslateError_GetObject(PyObject *exc)
1577{
1578 return get_unicode(((PyUnicodeErrorObject *)exc)->object, "object");
1579}
1580
1581int
1582PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1583{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001584 Py_ssize_t size;
1585 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1586 "object");
1587 if (!obj)
1588 return -1;
1589 *start = ((PyUnicodeErrorObject *)exc)->start;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001590 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001591 if (*start<0)
1592 *start = 0; /*XXX check for values <0*/
1593 if (*start>=size)
1594 *start = size-1;
1595 Py_DECREF(obj);
1596 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001597}
1598
1599
1600int
1601PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
1602{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001603 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001604 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001605 if (!obj)
1606 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001607 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001608 *start = ((PyUnicodeErrorObject *)exc)->start;
1609 if (*start<0)
1610 *start = 0;
1611 if (*start>=size)
1612 *start = size-1;
1613 Py_DECREF(obj);
1614 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001615}
1616
1617
1618int
1619PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
1620{
1621 return PyUnicodeEncodeError_GetStart(exc, start);
1622}
1623
1624
1625int
1626PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
1627{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001628 ((PyUnicodeErrorObject *)exc)->start = start;
1629 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001630}
1631
1632
1633int
1634PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
1635{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001636 ((PyUnicodeErrorObject *)exc)->start = start;
1637 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638}
1639
1640
1641int
1642PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
1643{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001644 ((PyUnicodeErrorObject *)exc)->start = start;
1645 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001646}
1647
1648
1649int
1650PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1651{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001652 Py_ssize_t size;
1653 PyObject *obj = get_unicode(((PyUnicodeErrorObject *)exc)->object,
1654 "object");
1655 if (!obj)
1656 return -1;
1657 *end = ((PyUnicodeErrorObject *)exc)->end;
Victor Stinner9e30aa52011-11-21 02:49:52 +01001658 size = PyUnicode_GET_LENGTH(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001659 if (*end<1)
1660 *end = 1;
1661 if (*end>size)
1662 *end = size;
1663 Py_DECREF(obj);
1664 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001665}
1666
1667
1668int
1669PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
1670{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001671 Py_ssize_t size;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001672 PyObject *obj = get_string(((PyUnicodeErrorObject *)exc)->object, "object");
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001673 if (!obj)
1674 return -1;
Christian Heimes72b710a2008-05-26 13:28:38 +00001675 size = PyBytes_GET_SIZE(obj);
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001676 *end = ((PyUnicodeErrorObject *)exc)->end;
1677 if (*end<1)
1678 *end = 1;
1679 if (*end>size)
1680 *end = size;
1681 Py_DECREF(obj);
1682 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001683}
1684
1685
1686int
1687PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *start)
1688{
1689 return PyUnicodeEncodeError_GetEnd(exc, start);
1690}
1691
1692
1693int
1694PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1695{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001696 ((PyUnicodeErrorObject *)exc)->end = end;
1697 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001698}
1699
1700
1701int
1702PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
1703{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001704 ((PyUnicodeErrorObject *)exc)->end = end;
1705 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001706}
1707
1708
1709int
1710PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
1711{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001712 ((PyUnicodeErrorObject *)exc)->end = end;
1713 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001714}
1715
1716PyObject *
1717PyUnicodeEncodeError_GetReason(PyObject *exc)
1718{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001719 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001720}
1721
1722
1723PyObject *
1724PyUnicodeDecodeError_GetReason(PyObject *exc)
1725{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001726 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001727}
1728
1729
1730PyObject *
1731PyUnicodeTranslateError_GetReason(PyObject *exc)
1732{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001733 return get_unicode(((PyUnicodeErrorObject *)exc)->reason, "reason");
Thomas Wouters477c8d52006-05-27 19:21:47 +00001734}
1735
1736
1737int
1738PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
1739{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001740 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1741 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001742}
1743
1744
1745int
1746PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
1747{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001748 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1749 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001750}
1751
1752
1753int
1754PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
1755{
Walter Dörwaldd2034312007-05-18 16:29:38 +00001756 return set_unicodefromstring(&((PyUnicodeErrorObject *)exc)->reason,
1757 reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001758}
1759
1760
Thomas Wouters477c8d52006-05-27 19:21:47 +00001761static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001762UnicodeError_clear(PyUnicodeErrorObject *self)
1763{
1764 Py_CLEAR(self->encoding);
1765 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001766 Py_CLEAR(self->reason);
1767 return BaseException_clear((PyBaseExceptionObject *)self);
1768}
1769
1770static void
1771UnicodeError_dealloc(PyUnicodeErrorObject *self)
1772{
Thomas Wouters89f507f2006-12-13 04:49:30 +00001773 _PyObject_GC_UNTRACK(self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001774 UnicodeError_clear(self);
Christian Heimes90aa7642007-12-19 02:45:37 +00001775 Py_TYPE(self)->tp_free((PyObject *)self);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001776}
1777
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001778static int
Thomas Wouters477c8d52006-05-27 19:21:47 +00001779UnicodeError_traverse(PyUnicodeErrorObject *self, visitproc visit, void *arg)
1780{
1781 Py_VISIT(self->encoding);
1782 Py_VISIT(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001783 Py_VISIT(self->reason);
1784 return BaseException_traverse((PyBaseExceptionObject *)self, visit, arg);
1785}
1786
1787static PyMemberDef UnicodeError_members[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001788 {"encoding", T_OBJECT, offsetof(PyUnicodeErrorObject, encoding), 0,
1789 PyDoc_STR("exception encoding")},
1790 {"object", T_OBJECT, offsetof(PyUnicodeErrorObject, object), 0,
1791 PyDoc_STR("exception object")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001792 {"start", T_PYSSIZET, offsetof(PyUnicodeErrorObject, start), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001793 PyDoc_STR("exception start")},
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001794 {"end", T_PYSSIZET, offsetof(PyUnicodeErrorObject, end), 0,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001795 PyDoc_STR("exception end")},
1796 {"reason", T_OBJECT, offsetof(PyUnicodeErrorObject, reason), 0,
1797 PyDoc_STR("exception reason")},
1798 {NULL} /* Sentinel */
1799};
1800
1801
1802/*
1803 * UnicodeEncodeError extends UnicodeError
1804 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001805
1806static int
1807UnicodeEncodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1808{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001809 PyUnicodeErrorObject *err;
1810
Thomas Wouters477c8d52006-05-27 19:21:47 +00001811 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1812 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001813
1814 err = (PyUnicodeErrorObject *)self;
1815
1816 Py_CLEAR(err->encoding);
1817 Py_CLEAR(err->object);
1818 Py_CLEAR(err->reason);
1819
1820 if (!PyArg_ParseTuple(args, "O!O!nnO!",
1821 &PyUnicode_Type, &err->encoding,
1822 &PyUnicode_Type, &err->object,
1823 &err->start,
1824 &err->end,
1825 &PyUnicode_Type, &err->reason)) {
1826 err->encoding = err->object = err->reason = NULL;
1827 return -1;
1828 }
1829
Martin v. Löwisb09af032011-11-04 11:16:41 +01001830 if (PyUnicode_READY(err->object) < -1) {
1831 err->encoding = NULL;
1832 return -1;
1833 }
1834
Guido van Rossum98297ee2007-11-06 21:34:58 +00001835 Py_INCREF(err->encoding);
1836 Py_INCREF(err->object);
1837 Py_INCREF(err->reason);
1838
1839 return 0;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001840}
1841
1842static PyObject *
1843UnicodeEncodeError_str(PyObject *self)
1844{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001845 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001846 PyObject *result = NULL;
1847 PyObject *reason_str = NULL;
1848 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001849
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001850 if (!uself->object)
1851 /* Not properly initialized. */
1852 return PyUnicode_FromString("");
1853
Eric Smith0facd772010-02-24 15:42:29 +00001854 /* Get reason and encoding as strings, which they might not be if
1855 they've been modified after we were contructed. */
1856 reason_str = PyObject_Str(uself->reason);
1857 if (reason_str == NULL)
1858 goto done;
1859 encoding_str = PyObject_Str(uself->encoding);
1860 if (encoding_str == NULL)
1861 goto done;
1862
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001863 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
1864 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00001865 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001866 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001867 fmt = "'%U' codec can't encode character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001868 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00001869 fmt = "'%U' codec can't encode character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001870 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00001871 fmt = "'%U' codec can't encode character '\\U%08x' in position %zd: %U";
Eric Smith0facd772010-02-24 15:42:29 +00001872 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001873 fmt,
Eric Smith0facd772010-02-24 15:42:29 +00001874 encoding_str,
Victor Stinnerda1ddf32011-11-20 22:50:23 +01001875 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001876 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001877 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001878 }
Eric Smith0facd772010-02-24 15:42:29 +00001879 else {
1880 result = PyUnicode_FromFormat(
1881 "'%U' codec can't encode characters in position %zd-%zd: %U",
1882 encoding_str,
1883 uself->start,
1884 uself->end-1,
1885 reason_str);
1886 }
1887done:
1888 Py_XDECREF(reason_str);
1889 Py_XDECREF(encoding_str);
1890 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001891}
1892
1893static PyTypeObject _PyExc_UnicodeEncodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001894 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00001895 "UnicodeEncodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00001896 sizeof(PyUnicodeErrorObject), 0,
1897 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1898 (reprfunc)UnicodeEncodeError_str, 0, 0, 0,
1899 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001900 PyDoc_STR("Unicode encoding error."), (traverseproc)UnicodeError_traverse,
1901 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001902 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001903 (initproc)UnicodeEncodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00001904};
1905PyObject *PyExc_UnicodeEncodeError = (PyObject *)&_PyExc_UnicodeEncodeError;
1906
1907PyObject *
1908PyUnicodeEncodeError_Create(
1909 const char *encoding, const Py_UNICODE *object, Py_ssize_t length,
1910 Py_ssize_t start, Py_ssize_t end, const char *reason)
1911{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001912 return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001913 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001914}
1915
1916
1917/*
1918 * UnicodeDecodeError extends UnicodeError
1919 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001920
1921static int
1922UnicodeDecodeError_init(PyObject *self, PyObject *args, PyObject *kwds)
1923{
Guido van Rossum98297ee2007-11-06 21:34:58 +00001924 PyUnicodeErrorObject *ude;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001925
Thomas Wouters477c8d52006-05-27 19:21:47 +00001926 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
1927 return -1;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001928
1929 ude = (PyUnicodeErrorObject *)self;
1930
1931 Py_CLEAR(ude->encoding);
1932 Py_CLEAR(ude->object);
1933 Py_CLEAR(ude->reason);
1934
1935 if (!PyArg_ParseTuple(args, "O!OnnO!",
1936 &PyUnicode_Type, &ude->encoding,
1937 &ude->object,
1938 &ude->start,
1939 &ude->end,
1940 &PyUnicode_Type, &ude->reason)) {
1941 ude->encoding = ude->object = ude->reason = NULL;
1942 return -1;
1943 }
1944
Guido van Rossum98297ee2007-11-06 21:34:58 +00001945 Py_INCREF(ude->encoding);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001946 Py_INCREF(ude->object);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001947 Py_INCREF(ude->reason);
1948
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001949 if (!PyBytes_Check(ude->object)) {
1950 Py_buffer view;
1951 if (PyObject_GetBuffer(ude->object, &view, PyBUF_SIMPLE) != 0)
1952 goto error;
1953 Py_CLEAR(ude->object);
1954 ude->object = PyBytes_FromStringAndSize(view.buf, view.len);
1955 PyBuffer_Release(&view);
1956 if (!ude->object)
1957 goto error;
1958 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001959 return 0;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001960
1961error:
1962 Py_CLEAR(ude->encoding);
1963 Py_CLEAR(ude->object);
1964 Py_CLEAR(ude->reason);
1965 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001966}
1967
1968static PyObject *
1969UnicodeDecodeError_str(PyObject *self)
1970{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001971 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00001972 PyObject *result = NULL;
1973 PyObject *reason_str = NULL;
1974 PyObject *encoding_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001975
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001976 if (!uself->object)
1977 /* Not properly initialized. */
1978 return PyUnicode_FromString("");
1979
Eric Smith0facd772010-02-24 15:42:29 +00001980 /* Get reason and encoding as strings, which they might not be if
1981 they've been modified after we were contructed. */
1982 reason_str = PyObject_Str(uself->reason);
1983 if (reason_str == NULL)
1984 goto done;
1985 encoding_str = PyObject_Str(uself->encoding);
1986 if (encoding_str == NULL)
1987 goto done;
1988
1989 if (uself->start < PyBytes_GET_SIZE(uself->object) && uself->end == uself->start+1) {
Christian Heimes72b710a2008-05-26 13:28:38 +00001990 int byte = (int)(PyBytes_AS_STRING(((PyUnicodeErrorObject *)self)->object)[uself->start]&0xff);
Eric Smith0facd772010-02-24 15:42:29 +00001991 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00001992 "'%U' codec can't decode byte 0x%02x in position %zd: %U",
Eric Smith0facd772010-02-24 15:42:29 +00001993 encoding_str,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001994 byte,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001995 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00001996 reason_str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001997 }
Eric Smith0facd772010-02-24 15:42:29 +00001998 else {
1999 result = PyUnicode_FromFormat(
2000 "'%U' codec can't decode bytes in position %zd-%zd: %U",
2001 encoding_str,
2002 uself->start,
2003 uself->end-1,
2004 reason_str
2005 );
2006 }
2007done:
2008 Py_XDECREF(reason_str);
2009 Py_XDECREF(encoding_str);
2010 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002011}
2012
2013static PyTypeObject _PyExc_UnicodeDecodeError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002014 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002015 "UnicodeDecodeError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002016 sizeof(PyUnicodeErrorObject), 0,
2017 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2018 (reprfunc)UnicodeDecodeError_str, 0, 0, 0,
2019 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002020 PyDoc_STR("Unicode decoding error."), (traverseproc)UnicodeError_traverse,
2021 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002022 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002023 (initproc)UnicodeDecodeError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002024};
2025PyObject *PyExc_UnicodeDecodeError = (PyObject *)&_PyExc_UnicodeDecodeError;
2026
2027PyObject *
2028PyUnicodeDecodeError_Create(
2029 const char *encoding, const char *object, Py_ssize_t length,
2030 Py_ssize_t start, Py_ssize_t end, const char *reason)
2031{
Victor Stinner7eeb5b52010-06-07 19:57:46 +00002032 return PyObject_CallFunction(PyExc_UnicodeDecodeError, "sy#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002033 encoding, object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002034}
2035
2036
2037/*
2038 * UnicodeTranslateError extends UnicodeError
2039 */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040
2041static int
2042UnicodeTranslateError_init(PyUnicodeErrorObject *self, PyObject *args,
2043 PyObject *kwds)
2044{
2045 if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
2046 return -1;
2047
2048 Py_CLEAR(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002049 Py_CLEAR(self->reason);
2050
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002051 if (!PyArg_ParseTuple(args, "O!nnO!",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002052 &PyUnicode_Type, &self->object,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002053 &self->start,
2054 &self->end,
Walter Dörwaldd2034312007-05-18 16:29:38 +00002055 &PyUnicode_Type, &self->reason)) {
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002056 self->object = self->reason = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002057 return -1;
2058 }
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002059
Thomas Wouters477c8d52006-05-27 19:21:47 +00002060 Py_INCREF(self->object);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002061 Py_INCREF(self->reason);
2062
2063 return 0;
2064}
2065
2066
2067static PyObject *
2068UnicodeTranslateError_str(PyObject *self)
2069{
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002070 PyUnicodeErrorObject *uself = (PyUnicodeErrorObject *)self;
Eric Smith0facd772010-02-24 15:42:29 +00002071 PyObject *result = NULL;
2072 PyObject *reason_str = NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002073
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04002074 if (!uself->object)
2075 /* Not properly initialized. */
2076 return PyUnicode_FromString("");
2077
Eric Smith0facd772010-02-24 15:42:29 +00002078 /* Get reason as a string, which it might not be if it's been
2079 modified after we were contructed. */
2080 reason_str = PyObject_Str(uself->reason);
2081 if (reason_str == NULL)
2082 goto done;
2083
Victor Stinner53b33e72011-11-21 01:17:27 +01002084 if (uself->start < PyUnicode_GET_LENGTH(uself->object) && uself->end == uself->start+1) {
2085 Py_UCS4 badchar = PyUnicode_ReadChar(uself->object, uself->start);
Walter Dörwald787b03b2007-06-05 13:29:29 +00002086 const char *fmt;
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002087 if (badchar <= 0xff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002088 fmt = "can't translate character '\\x%02x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002089 else if (badchar <= 0xffff)
Walter Dörwald32a4c712007-06-20 09:25:34 +00002090 fmt = "can't translate character '\\u%04x' in position %zd: %U";
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002091 else
Walter Dörwald32a4c712007-06-20 09:25:34 +00002092 fmt = "can't translate character '\\U%08x' in position %zd: %U";
Benjamin Petersonc5f4e1e2010-02-25 01:22:28 +00002093 result = PyUnicode_FromFormat(
Walter Dörwald787b03b2007-06-05 13:29:29 +00002094 fmt,
Victor Stinner53b33e72011-11-21 01:17:27 +01002095 (int)badchar,
Guido van Rossum7eaf8222007-06-18 17:58:50 +00002096 uself->start,
Eric Smith0facd772010-02-24 15:42:29 +00002097 reason_str
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002098 );
Eric Smith0facd772010-02-24 15:42:29 +00002099 } else {
2100 result = PyUnicode_FromFormat(
2101 "can't translate characters in position %zd-%zd: %U",
2102 uself->start,
2103 uself->end-1,
2104 reason_str
2105 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00002106 }
Eric Smith0facd772010-02-24 15:42:29 +00002107done:
2108 Py_XDECREF(reason_str);
2109 return result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002110}
2111
2112static PyTypeObject _PyExc_UnicodeTranslateError = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002113 PyVarObject_HEAD_INIT(NULL, 0)
Neal Norwitz2633c692007-02-26 22:22:47 +00002114 "UnicodeTranslateError",
Thomas Wouters477c8d52006-05-27 19:21:47 +00002115 sizeof(PyUnicodeErrorObject), 0,
2116 (destructor)UnicodeError_dealloc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
2117 (reprfunc)UnicodeTranslateError_str, 0, 0, 0,
2118 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002119 PyDoc_STR("Unicode translation error."), (traverseproc)UnicodeError_traverse,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002120 (inquiry)UnicodeError_clear, 0, 0, 0, 0, 0, UnicodeError_members,
2121 0, &_PyExc_UnicodeError, 0, 0, 0, offsetof(PyUnicodeErrorObject, dict),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002122 (initproc)UnicodeTranslateError_init, 0, BaseException_new,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002123};
2124PyObject *PyExc_UnicodeTranslateError = (PyObject *)&_PyExc_UnicodeTranslateError;
2125
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002126/* Deprecated. */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127PyObject *
2128PyUnicodeTranslateError_Create(
2129 const Py_UNICODE *object, Py_ssize_t length,
2130 Py_ssize_t start, Py_ssize_t end, const char *reason)
2131{
2132 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#nns",
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002133 object, length, start, end, reason);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002134}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002136PyObject *
2137_PyUnicodeTranslateError_Create(
2138 PyObject *object,
2139 Py_ssize_t start, Py_ssize_t end, const char *reason)
2140{
Victor Stinner69598d42014-04-04 20:59:44 +02002141 return PyObject_CallFunction(PyExc_UnicodeTranslateError, "Onns",
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002142 object, start, end, reason);
2143}
Thomas Wouters477c8d52006-05-27 19:21:47 +00002144
2145/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002146 * AssertionError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002147 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002148SimpleExtendsException(PyExc_Exception, AssertionError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002149 "Assertion failed.");
2150
2151
2152/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002153 * ArithmeticError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002154 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002155SimpleExtendsException(PyExc_Exception, ArithmeticError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002156 "Base class for arithmetic errors.");
2157
2158
2159/*
2160 * FloatingPointError extends ArithmeticError
2161 */
2162SimpleExtendsException(PyExc_ArithmeticError, FloatingPointError,
2163 "Floating point operation failed.");
2164
2165
2166/*
2167 * OverflowError extends ArithmeticError
2168 */
2169SimpleExtendsException(PyExc_ArithmeticError, OverflowError,
2170 "Result too large to be represented.");
2171
2172
2173/*
2174 * ZeroDivisionError extends ArithmeticError
2175 */
2176SimpleExtendsException(PyExc_ArithmeticError, ZeroDivisionError,
2177 "Second argument to a division or modulo operation was zero.");
2178
2179
2180/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002181 * SystemError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002182 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002183SimpleExtendsException(PyExc_Exception, SystemError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002184 "Internal error in the Python interpreter.\n"
2185 "\n"
2186 "Please report this to the Python maintainer, along with the traceback,\n"
2187 "the Python version, and the hardware/OS platform and version.");
2188
2189
2190/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002191 * ReferenceError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002192 */
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002193SimpleExtendsException(PyExc_Exception, ReferenceError,
Thomas Wouters477c8d52006-05-27 19:21:47 +00002194 "Weak ref proxy used after referent went away.");
2195
2196
2197/*
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002198 * MemoryError extends Exception
Thomas Wouters477c8d52006-05-27 19:21:47 +00002199 */
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002200
2201#define MEMERRORS_SAVE 16
2202static PyBaseExceptionObject *memerrors_freelist = NULL;
2203static int memerrors_numfree = 0;
2204
2205static PyObject *
2206MemoryError_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2207{
2208 PyBaseExceptionObject *self;
2209
2210 if (type != (PyTypeObject *) PyExc_MemoryError)
2211 return BaseException_new(type, args, kwds);
2212 if (memerrors_freelist == NULL)
2213 return BaseException_new(type, args, kwds);
2214 /* Fetch object from freelist and revive it */
2215 self = memerrors_freelist;
2216 self->args = PyTuple_New(0);
2217 /* This shouldn't happen since the empty tuple is persistent */
2218 if (self->args == NULL)
2219 return NULL;
2220 memerrors_freelist = (PyBaseExceptionObject *) self->dict;
2221 memerrors_numfree--;
2222 self->dict = NULL;
2223 _Py_NewReference((PyObject *)self);
2224 _PyObject_GC_TRACK(self);
2225 return (PyObject *)self;
2226}
2227
2228static void
2229MemoryError_dealloc(PyBaseExceptionObject *self)
2230{
2231 _PyObject_GC_UNTRACK(self);
2232 BaseException_clear(self);
2233 if (memerrors_numfree >= MEMERRORS_SAVE)
2234 Py_TYPE(self)->tp_free((PyObject *)self);
2235 else {
2236 self->dict = (PyObject *) memerrors_freelist;
2237 memerrors_freelist = self;
2238 memerrors_numfree++;
2239 }
2240}
2241
2242static void
2243preallocate_memerrors(void)
2244{
2245 /* We create enough MemoryErrors and then decref them, which will fill
2246 up the freelist. */
2247 int i;
2248 PyObject *errors[MEMERRORS_SAVE];
2249 for (i = 0; i < MEMERRORS_SAVE; i++) {
2250 errors[i] = MemoryError_new((PyTypeObject *) PyExc_MemoryError,
2251 NULL, NULL);
2252 if (!errors[i])
2253 Py_FatalError("Could not preallocate MemoryError object");
2254 }
2255 for (i = 0; i < MEMERRORS_SAVE; i++) {
2256 Py_DECREF(errors[i]);
2257 }
2258}
2259
2260static void
2261free_preallocated_memerrors(void)
2262{
2263 while (memerrors_freelist != NULL) {
2264 PyObject *self = (PyObject *) memerrors_freelist;
2265 memerrors_freelist = (PyBaseExceptionObject *) memerrors_freelist->dict;
2266 Py_TYPE(self)->tp_free((PyObject *)self);
2267 }
2268}
2269
2270
2271static PyTypeObject _PyExc_MemoryError = {
2272 PyVarObject_HEAD_INIT(NULL, 0)
2273 "MemoryError",
2274 sizeof(PyBaseExceptionObject),
2275 0, (destructor)MemoryError_dealloc, 0, 0, 0, 0, 0, 0, 0,
2276 0, 0, 0, 0, 0, 0, 0,
2277 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
2278 PyDoc_STR("Out of memory."), (traverseproc)BaseException_traverse,
2279 (inquiry)BaseException_clear, 0, 0, 0, 0, 0, 0, 0, &_PyExc_Exception,
2280 0, 0, 0, offsetof(PyBaseExceptionObject, dict),
2281 (initproc)BaseException_init, 0, MemoryError_new
2282};
2283PyObject *PyExc_MemoryError = (PyObject *) &_PyExc_MemoryError;
2284
Thomas Wouters477c8d52006-05-27 19:21:47 +00002285
Travis E. Oliphantb99f7622007-08-18 11:21:56 +00002286/*
2287 * BufferError extends Exception
2288 */
2289SimpleExtendsException(PyExc_Exception, BufferError, "Buffer error.");
2290
Thomas Wouters477c8d52006-05-27 19:21:47 +00002291
2292/* Warning category docstrings */
2293
2294/*
2295 * Warning extends Exception
2296 */
2297SimpleExtendsException(PyExc_Exception, Warning,
2298 "Base class for warning categories.");
2299
2300
2301/*
2302 * UserWarning extends Warning
2303 */
2304SimpleExtendsException(PyExc_Warning, UserWarning,
2305 "Base class for warnings generated by user code.");
2306
2307
2308/*
2309 * DeprecationWarning extends Warning
2310 */
2311SimpleExtendsException(PyExc_Warning, DeprecationWarning,
2312 "Base class for warnings about deprecated features.");
2313
2314
2315/*
2316 * PendingDeprecationWarning extends Warning
2317 */
2318SimpleExtendsException(PyExc_Warning, PendingDeprecationWarning,
2319 "Base class for warnings about features which will be deprecated\n"
2320 "in the future.");
2321
2322
2323/*
2324 * SyntaxWarning extends Warning
2325 */
2326SimpleExtendsException(PyExc_Warning, SyntaxWarning,
2327 "Base class for warnings about dubious syntax.");
2328
2329
2330/*
2331 * RuntimeWarning extends Warning
2332 */
2333SimpleExtendsException(PyExc_Warning, RuntimeWarning,
2334 "Base class for warnings about dubious runtime behavior.");
2335
2336
2337/*
2338 * FutureWarning extends Warning
2339 */
2340SimpleExtendsException(PyExc_Warning, FutureWarning,
2341 "Base class for warnings about constructs that will change semantically\n"
2342 "in the future.");
2343
2344
2345/*
2346 * ImportWarning extends Warning
2347 */
2348SimpleExtendsException(PyExc_Warning, ImportWarning,
2349 "Base class for warnings about probable mistakes in module imports");
2350
2351
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002352/*
2353 * UnicodeWarning extends Warning
2354 */
2355SimpleExtendsException(PyExc_Warning, UnicodeWarning,
2356 "Base class for warnings about Unicode related problems, mostly\n"
2357 "related to conversion problems.");
2358
Georg Brandl08be72d2010-10-24 15:11:22 +00002359
Guido van Rossum98297ee2007-11-06 21:34:58 +00002360/*
2361 * BytesWarning extends Warning
2362 */
2363SimpleExtendsException(PyExc_Warning, BytesWarning,
2364 "Base class for warnings about bytes and buffer related problems, mostly\n"
2365 "related to conversion from str or comparing to str.");
2366
2367
Georg Brandl08be72d2010-10-24 15:11:22 +00002368/*
2369 * ResourceWarning extends Warning
2370 */
2371SimpleExtendsException(PyExc_Warning, ResourceWarning,
2372 "Base class for warnings about resource usage.");
2373
2374
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002375
Thomas Wouters89d996e2007-09-08 17:39:28 +00002376/* Pre-computed RuntimeError instance for when recursion depth is reached.
2377 Meant to be used when normalizing the exception for exceeding the recursion
2378 depth will cause its own infinite recursion.
2379*/
2380PyObject *PyExc_RecursionErrorInst = NULL;
2381
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002382#define PRE_INIT(TYPE) \
2383 if (!(_PyExc_ ## TYPE.tp_flags & Py_TPFLAGS_READY)) { \
2384 if (PyType_Ready(&_PyExc_ ## TYPE) < 0) \
2385 Py_FatalError("exceptions bootstrapping error."); \
2386 Py_INCREF(PyExc_ ## TYPE); \
2387 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002388
Antoine Pitrou55f217f2012-01-18 21:23:13 +01002389#define POST_INIT(TYPE) \
Thomas Wouters477c8d52006-05-27 19:21:47 +00002390 if (PyDict_SetItemString(bdict, # TYPE, PyExc_ ## TYPE)) \
2391 Py_FatalError("Module dictionary insertion problem.");
2392
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002393#define INIT_ALIAS(NAME, TYPE) Py_INCREF(PyExc_ ## TYPE); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002394 Py_XDECREF(PyExc_ ## NAME); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002395 PyExc_ ## NAME = PyExc_ ## TYPE; \
2396 if (PyDict_SetItemString(bdict, # NAME, PyExc_ ## NAME)) \
2397 Py_FatalError("Module dictionary insertion problem.");
2398
2399#define ADD_ERRNO(TYPE, CODE) { \
2400 PyObject *_code = PyLong_FromLong(CODE); \
2401 assert(_PyObject_RealIsSubclass(PyExc_ ## TYPE, PyExc_OSError)); \
2402 if (!_code || PyDict_SetItem(errnomap, _code, PyExc_ ## TYPE)) \
2403 Py_FatalError("errmap insertion problem."); \
Antoine Pitrou8b0a74e2012-01-18 21:29:05 +01002404 Py_DECREF(_code); \
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002405 }
2406
2407#ifdef MS_WINDOWS
Antoine Pitrou7faf7052013-03-31 22:48:04 +02002408#include <winsock2.h>
Brian Curtin401f9f32012-05-13 11:19:23 -05002409/* The following constants were added to errno.h in VS2010 but have
2410 preferred WSA equivalents. */
2411#undef EADDRINUSE
2412#undef EADDRNOTAVAIL
2413#undef EAFNOSUPPORT
2414#undef EALREADY
2415#undef ECONNABORTED
2416#undef ECONNREFUSED
2417#undef ECONNRESET
2418#undef EDESTADDRREQ
2419#undef EHOSTUNREACH
2420#undef EINPROGRESS
2421#undef EISCONN
2422#undef ELOOP
2423#undef EMSGSIZE
2424#undef ENETDOWN
2425#undef ENETRESET
2426#undef ENETUNREACH
2427#undef ENOBUFS
2428#undef ENOPROTOOPT
2429#undef ENOTCONN
2430#undef ENOTSOCK
2431#undef EOPNOTSUPP
2432#undef EPROTONOSUPPORT
2433#undef EPROTOTYPE
2434#undef ETIMEDOUT
2435#undef EWOULDBLOCK
2436
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002437#if defined(WSAEALREADY) && !defined(EALREADY)
2438#define EALREADY WSAEALREADY
2439#endif
2440#if defined(WSAECONNABORTED) && !defined(ECONNABORTED)
2441#define ECONNABORTED WSAECONNABORTED
2442#endif
2443#if defined(WSAECONNREFUSED) && !defined(ECONNREFUSED)
2444#define ECONNREFUSED WSAECONNREFUSED
2445#endif
2446#if defined(WSAECONNRESET) && !defined(ECONNRESET)
2447#define ECONNRESET WSAECONNRESET
2448#endif
2449#if defined(WSAEINPROGRESS) && !defined(EINPROGRESS)
2450#define EINPROGRESS WSAEINPROGRESS
2451#endif
2452#if defined(WSAESHUTDOWN) && !defined(ESHUTDOWN)
2453#define ESHUTDOWN WSAESHUTDOWN
2454#endif
2455#if defined(WSAETIMEDOUT) && !defined(ETIMEDOUT)
2456#define ETIMEDOUT WSAETIMEDOUT
2457#endif
2458#if defined(WSAEWOULDBLOCK) && !defined(EWOULDBLOCK)
2459#define EWOULDBLOCK WSAEWOULDBLOCK
2460#endif
2461#endif /* MS_WINDOWS */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002462
Martin v. Löwis1a214512008-06-11 05:26:20 +00002463void
Brett Cannonfd074152012-04-14 14:10:13 -04002464_PyExc_Init(PyObject *bltinmod)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002465{
Brett Cannonfd074152012-04-14 14:10:13 -04002466 PyObject *bdict;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002467
2468 PRE_INIT(BaseException)
2469 PRE_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002470 PRE_INIT(TypeError)
2471 PRE_INIT(StopIteration)
2472 PRE_INIT(GeneratorExit)
2473 PRE_INIT(SystemExit)
2474 PRE_INIT(KeyboardInterrupt)
2475 PRE_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002476 PRE_INIT(OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002477 PRE_INIT(EOFError)
2478 PRE_INIT(RuntimeError)
2479 PRE_INIT(NotImplementedError)
2480 PRE_INIT(NameError)
2481 PRE_INIT(UnboundLocalError)
2482 PRE_INIT(AttributeError)
2483 PRE_INIT(SyntaxError)
2484 PRE_INIT(IndentationError)
2485 PRE_INIT(TabError)
2486 PRE_INIT(LookupError)
2487 PRE_INIT(IndexError)
2488 PRE_INIT(KeyError)
2489 PRE_INIT(ValueError)
2490 PRE_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002491 PRE_INIT(UnicodeEncodeError)
2492 PRE_INIT(UnicodeDecodeError)
2493 PRE_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002494 PRE_INIT(AssertionError)
2495 PRE_INIT(ArithmeticError)
2496 PRE_INIT(FloatingPointError)
2497 PRE_INIT(OverflowError)
2498 PRE_INIT(ZeroDivisionError)
2499 PRE_INIT(SystemError)
2500 PRE_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002501 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002502 PRE_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002503 PRE_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002504 PRE_INIT(Warning)
2505 PRE_INIT(UserWarning)
2506 PRE_INIT(DeprecationWarning)
2507 PRE_INIT(PendingDeprecationWarning)
2508 PRE_INIT(SyntaxWarning)
2509 PRE_INIT(RuntimeWarning)
2510 PRE_INIT(FutureWarning)
2511 PRE_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002512 PRE_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002513 PRE_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002514 PRE_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002515
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002516 /* OSError subclasses */
2517 PRE_INIT(ConnectionError);
2518
2519 PRE_INIT(BlockingIOError);
2520 PRE_INIT(BrokenPipeError);
2521 PRE_INIT(ChildProcessError);
2522 PRE_INIT(ConnectionAbortedError);
2523 PRE_INIT(ConnectionRefusedError);
2524 PRE_INIT(ConnectionResetError);
2525 PRE_INIT(FileExistsError);
2526 PRE_INIT(FileNotFoundError);
2527 PRE_INIT(IsADirectoryError);
2528 PRE_INIT(NotADirectoryError);
2529 PRE_INIT(InterruptedError);
2530 PRE_INIT(PermissionError);
2531 PRE_INIT(ProcessLookupError);
2532 PRE_INIT(TimeoutError);
2533
Thomas Wouters477c8d52006-05-27 19:21:47 +00002534 bdict = PyModule_GetDict(bltinmod);
2535 if (bdict == NULL)
2536 Py_FatalError("exceptions bootstrapping error.");
2537
2538 POST_INIT(BaseException)
2539 POST_INIT(Exception)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002540 POST_INIT(TypeError)
2541 POST_INIT(StopIteration)
2542 POST_INIT(GeneratorExit)
2543 POST_INIT(SystemExit)
2544 POST_INIT(KeyboardInterrupt)
2545 POST_INIT(ImportError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002546 POST_INIT(OSError)
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002547 INIT_ALIAS(EnvironmentError, OSError)
2548 INIT_ALIAS(IOError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002549#ifdef MS_WINDOWS
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002550 INIT_ALIAS(WindowsError, OSError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002551#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +00002552 POST_INIT(EOFError)
2553 POST_INIT(RuntimeError)
2554 POST_INIT(NotImplementedError)
2555 POST_INIT(NameError)
2556 POST_INIT(UnboundLocalError)
2557 POST_INIT(AttributeError)
2558 POST_INIT(SyntaxError)
2559 POST_INIT(IndentationError)
2560 POST_INIT(TabError)
2561 POST_INIT(LookupError)
2562 POST_INIT(IndexError)
2563 POST_INIT(KeyError)
2564 POST_INIT(ValueError)
2565 POST_INIT(UnicodeError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002566 POST_INIT(UnicodeEncodeError)
2567 POST_INIT(UnicodeDecodeError)
2568 POST_INIT(UnicodeTranslateError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002569 POST_INIT(AssertionError)
2570 POST_INIT(ArithmeticError)
2571 POST_INIT(FloatingPointError)
2572 POST_INIT(OverflowError)
2573 POST_INIT(ZeroDivisionError)
2574 POST_INIT(SystemError)
2575 POST_INIT(ReferenceError)
Neal Norwitzfaa54a32007-08-19 04:23:20 +00002576 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002577 POST_INIT(MemoryError)
Benjamin Peterson2b968d62008-07-05 23:38:30 +00002578 POST_INIT(BufferError)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002579 POST_INIT(Warning)
2580 POST_INIT(UserWarning)
2581 POST_INIT(DeprecationWarning)
2582 POST_INIT(PendingDeprecationWarning)
2583 POST_INIT(SyntaxWarning)
2584 POST_INIT(RuntimeWarning)
2585 POST_INIT(FutureWarning)
2586 POST_INIT(ImportWarning)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002587 POST_INIT(UnicodeWarning)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002588 POST_INIT(BytesWarning)
Georg Brandl08be72d2010-10-24 15:11:22 +00002589 POST_INIT(ResourceWarning)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002590
Antoine Pitrouac456a12012-01-18 21:35:21 +01002591 if (!errnomap) {
2592 errnomap = PyDict_New();
2593 if (!errnomap)
2594 Py_FatalError("Cannot allocate map from errnos to OSError subclasses");
2595 }
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002596
2597 /* OSError subclasses */
2598 POST_INIT(ConnectionError);
2599
2600 POST_INIT(BlockingIOError);
2601 ADD_ERRNO(BlockingIOError, EAGAIN);
2602 ADD_ERRNO(BlockingIOError, EALREADY);
2603 ADD_ERRNO(BlockingIOError, EINPROGRESS);
2604 ADD_ERRNO(BlockingIOError, EWOULDBLOCK);
2605 POST_INIT(BrokenPipeError);
2606 ADD_ERRNO(BrokenPipeError, EPIPE);
2607 ADD_ERRNO(BrokenPipeError, ESHUTDOWN);
2608 POST_INIT(ChildProcessError);
2609 ADD_ERRNO(ChildProcessError, ECHILD);
2610 POST_INIT(ConnectionAbortedError);
2611 ADD_ERRNO(ConnectionAbortedError, ECONNABORTED);
2612 POST_INIT(ConnectionRefusedError);
2613 ADD_ERRNO(ConnectionRefusedError, ECONNREFUSED);
2614 POST_INIT(ConnectionResetError);
2615 ADD_ERRNO(ConnectionResetError, ECONNRESET);
2616 POST_INIT(FileExistsError);
2617 ADD_ERRNO(FileExistsError, EEXIST);
2618 POST_INIT(FileNotFoundError);
2619 ADD_ERRNO(FileNotFoundError, ENOENT);
2620 POST_INIT(IsADirectoryError);
2621 ADD_ERRNO(IsADirectoryError, EISDIR);
2622 POST_INIT(NotADirectoryError);
2623 ADD_ERRNO(NotADirectoryError, ENOTDIR);
2624 POST_INIT(InterruptedError);
2625 ADD_ERRNO(InterruptedError, EINTR);
2626 POST_INIT(PermissionError);
2627 ADD_ERRNO(PermissionError, EACCES);
2628 ADD_ERRNO(PermissionError, EPERM);
2629 POST_INIT(ProcessLookupError);
2630 ADD_ERRNO(ProcessLookupError, ESRCH);
2631 POST_INIT(TimeoutError);
2632 ADD_ERRNO(TimeoutError, ETIMEDOUT);
2633
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002634 preallocate_memerrors();
Thomas Wouters477c8d52006-05-27 19:21:47 +00002635
Antoine Pitrou1c7ade52012-01-18 16:13:31 +01002636 if (!PyExc_RecursionErrorInst) {
2637 PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
2638 if (!PyExc_RecursionErrorInst)
2639 Py_FatalError("Cannot pre-allocate RuntimeError instance for "
2640 "recursion errors");
2641 else {
2642 PyBaseExceptionObject *err_inst =
2643 (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
2644 PyObject *args_tuple;
2645 PyObject *exc_message;
2646 exc_message = PyUnicode_FromString("maximum recursion depth exceeded");
2647 if (!exc_message)
2648 Py_FatalError("cannot allocate argument for RuntimeError "
2649 "pre-allocation");
2650 args_tuple = PyTuple_Pack(1, exc_message);
2651 if (!args_tuple)
2652 Py_FatalError("cannot allocate tuple for RuntimeError "
2653 "pre-allocation");
2654 Py_DECREF(exc_message);
2655 if (BaseException_init(err_inst, args_tuple, NULL))
2656 Py_FatalError("init of pre-allocated RuntimeError failed");
2657 Py_DECREF(args_tuple);
2658 }
Thomas Wouters89d996e2007-09-08 17:39:28 +00002659 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00002660}
2661
2662void
2663_PyExc_Fini(void)
2664{
Benjamin Peterson78565b22009-06-28 19:19:51 +00002665 Py_CLEAR(PyExc_RecursionErrorInst);
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00002666 free_preallocated_memerrors();
Antoine Pitrou6b4883d2011-10-12 02:54:14 +02002667 Py_CLEAR(errnomap);
Thomas Wouters477c8d52006-05-27 19:21:47 +00002668}
Nick Coghlan8b097b42013-11-13 23:49:21 +10002669
2670/* Helper to do the equivalent of "raise X from Y" in C, but always using
2671 * the current exception rather than passing one in.
2672 *
2673 * We currently limit this to *only* exceptions that use the BaseException
2674 * tp_init and tp_new methods, since we can be reasonably sure we can wrap
2675 * those correctly without losing data and without losing backwards
2676 * compatibility.
2677 *
2678 * We also aim to rule out *all* exceptions that might be storing additional
2679 * state, whether by having a size difference relative to BaseException,
2680 * additional arguments passed in during construction or by having a
2681 * non-empty instance dict.
2682 *
2683 * We need to be very careful with what we wrap, since changing types to
2684 * a broader exception type would be backwards incompatible for
2685 * existing codecs, and with different init or new method implementations
2686 * may either not support instantiation with PyErr_Format or lose
2687 * information when instantiated that way.
2688 *
2689 * XXX (ncoghlan): This could be made more comprehensive by exploiting the
2690 * fact that exceptions are expected to support pickling. If more builtin
2691 * exceptions (e.g. AttributeError) start to be converted to rich
2692 * exceptions with additional attributes, that's probably a better approach
2693 * to pursue over adding special cases for particular stateful subclasses.
2694 *
2695 * Returns a borrowed reference to the new exception (if any), NULL if the
2696 * existing exception was left in place.
2697 */
2698PyObject *
2699_PyErr_TrySetFromCause(const char *format, ...)
2700{
2701 PyObject* msg_prefix;
2702 PyObject *exc, *val, *tb;
2703 PyTypeObject *caught_type;
Christian Heimes6a3db252013-11-14 01:47:14 +01002704 PyObject **dictptr;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002705 PyObject *instance_args;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002706 Py_ssize_t num_args, caught_type_size, base_exc_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002707 PyObject *new_exc, *new_val, *new_tb;
2708 va_list vargs;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002709 int same_basic_size;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002710
Nick Coghlan8b097b42013-11-13 23:49:21 +10002711 PyErr_Fetch(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002712 caught_type = (PyTypeObject *)exc;
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002713 /* Ensure type info indicates no extra state is stored at the C level
2714 * and that the type can be reinstantiated using PyErr_Format
2715 */
2716 caught_type_size = caught_type->tp_basicsize;
2717 base_exc_size = _PyExc_BaseException.tp_basicsize;
2718 same_basic_size = (
2719 caught_type_size == base_exc_size ||
2720 (PyType_SUPPORTS_WEAKREFS(caught_type) &&
2721 (caught_type_size == base_exc_size + sizeof(PyObject *))
2722 )
2723 );
Benjamin Peterson079c9982013-11-13 23:25:01 -05002724 if (caught_type->tp_init != (initproc)BaseException_init ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002725 caught_type->tp_new != BaseException_new ||
Nick Coghlanf1de55f2013-11-19 22:33:10 +10002726 !same_basic_size ||
Benjamin Peterson079c9982013-11-13 23:25:01 -05002727 caught_type->tp_itemsize != _PyExc_BaseException.tp_itemsize) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002728 /* We can't be sure we can wrap this safely, since it may contain
2729 * more state than just the exception type. Accordingly, we just
2730 * leave it alone.
2731 */
2732 PyErr_Restore(exc, val, tb);
2733 return NULL;
2734 }
2735
2736 /* Check the args are empty or contain a single string */
2737 PyErr_NormalizeException(&exc, &val, &tb);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002738 instance_args = ((PyBaseExceptionObject *)val)->args;
Nick Coghlan8b097b42013-11-13 23:49:21 +10002739 num_args = PyTuple_GET_SIZE(instance_args);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002740 if (num_args > 1 ||
Nick Coghlan8b097b42013-11-13 23:49:21 +10002741 (num_args == 1 &&
Benjamin Peterson079c9982013-11-13 23:25:01 -05002742 !PyUnicode_CheckExact(PyTuple_GET_ITEM(instance_args, 0)))) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002743 /* More than 1 arg, or the one arg we do have isn't a string
2744 */
2745 PyErr_Restore(exc, val, tb);
2746 return NULL;
2747 }
2748
2749 /* Ensure the instance dict is also empty */
Christian Heimes6a3db252013-11-14 01:47:14 +01002750 dictptr = _PyObject_GetDictPtr(val);
Benjamin Peterson079c9982013-11-13 23:25:01 -05002751 if (dictptr != NULL && *dictptr != NULL &&
2752 PyObject_Length(*dictptr) > 0) {
Nick Coghlan8b097b42013-11-13 23:49:21 +10002753 /* While we could potentially copy a non-empty instance dictionary
2754 * to the replacement exception, for now we take the more
2755 * conservative path of leaving exceptions with attributes set
2756 * alone.
2757 */
2758 PyErr_Restore(exc, val, tb);
2759 return NULL;
2760 }
2761
2762 /* For exceptions that we can wrap safely, we chain the original
2763 * exception to a new one of the exact same type with an
2764 * error message that mentions the additional details and the
2765 * original exception.
2766 *
2767 * It would be nice to wrap OSError and various other exception
2768 * types as well, but that's quite a bit trickier due to the extra
2769 * state potentially stored on OSError instances.
2770 */
Nick Coghlan77b286b2014-01-27 00:53:38 +10002771 /* Ensure the traceback is set correctly on the existing exception */
2772 if (tb != NULL) {
2773 PyException_SetTraceback(val, tb);
2774 Py_DECREF(tb);
2775 }
Benjamin Petersone109ee82013-11-13 23:49:49 -05002776
Christian Heimes507eabd2013-11-14 01:39:35 +01002777#ifdef HAVE_STDARG_PROTOTYPES
2778 va_start(vargs, format);
2779#else
2780 va_start(vargs);
2781#endif
Nick Coghlan8b097b42013-11-13 23:49:21 +10002782 msg_prefix = PyUnicode_FromFormatV(format, vargs);
Christian Heimes507eabd2013-11-14 01:39:35 +01002783 va_end(vargs);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002784 if (msg_prefix == NULL) {
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002785 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002786 Py_DECREF(val);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002787 return NULL;
Benjamin Petersone109ee82013-11-13 23:49:49 -05002788 }
Nick Coghlan8b097b42013-11-13 23:49:21 +10002789
2790 PyErr_Format(exc, "%U (%s: %S)",
2791 msg_prefix, Py_TYPE(val)->tp_name, val);
Nick Coghlan4b9b9362013-11-16 00:34:13 +10002792 Py_DECREF(exc);
Benjamin Petersone109ee82013-11-13 23:49:49 -05002793 Py_DECREF(msg_prefix);
Nick Coghlan8b097b42013-11-13 23:49:21 +10002794 PyErr_Fetch(&new_exc, &new_val, &new_tb);
2795 PyErr_NormalizeException(&new_exc, &new_val, &new_tb);
2796 PyException_SetCause(new_val, val);
2797 PyErr_Restore(new_exc, new_val, new_tb);
2798 return new_val;
2799}
Nick Coghlan5b1fdc12014-06-16 19:48:02 +10002800
2801
2802/* To help with migration from Python 2, SyntaxError.__init__ applies some
2803 * heuristics to try to report a more meaningful exception when print and
2804 * exec are used like statements.
2805 *
2806 * The heuristics are currently expected to detect the following cases:
2807 * - top level statement
2808 * - statement in a nested suite
2809 * - trailing section of a one line complex statement
2810 *
2811 * They're currently known not to trigger:
2812 * - after a semi-colon
2813 *
2814 * The error message can be a bit odd in cases where the "arguments" are
2815 * completely illegal syntactically, but that isn't worth the hassle of
2816 * fixing.
2817 *
2818 * We also can't do anything about cases that are legal Python 3 syntax
2819 * but mean something entirely different from what they did in Python 2
2820 * (omitting the arguments entirely, printing items preceded by a unary plus
2821 * or minus, using the stream redirection syntax).
2822 */
2823
2824static int
2825_check_for_legacy_statements(PySyntaxErrorObject *self, Py_ssize_t start)
2826{
2827 /* Return values:
2828 * -1: an error occurred
2829 * 0: nothing happened
2830 * 1: the check triggered & the error message was changed
2831 */
2832 static PyObject *print_prefix = NULL;
2833 static PyObject *exec_prefix = NULL;
2834 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2835 int kind = PyUnicode_KIND(self->text);
2836 void *data = PyUnicode_DATA(self->text);
2837
2838 /* Ignore leading whitespace */
2839 while (start < text_len) {
2840 Py_UCS4 ch = PyUnicode_READ(kind, data, start);
2841 if (!Py_UNICODE_ISSPACE(ch))
2842 break;
2843 start++;
2844 }
2845 /* Checking against an empty or whitespace-only part of the string */
2846 if (start == text_len) {
2847 return 0;
2848 }
2849
2850 /* Check for legacy print statements */
2851 if (print_prefix == NULL) {
2852 print_prefix = PyUnicode_InternFromString("print ");
2853 if (print_prefix == NULL) {
2854 return -1;
2855 }
2856 }
2857 if (PyUnicode_Tailmatch(self->text, print_prefix,
2858 start, text_len, -1)) {
2859 Py_CLEAR(self->msg);
2860 self->msg = PyUnicode_FromString(
2861 "Missing parentheses in call to 'print'");
2862 return 1;
2863 }
2864
2865 /* Check for legacy exec statements */
2866 if (exec_prefix == NULL) {
2867 exec_prefix = PyUnicode_InternFromString("exec ");
2868 if (exec_prefix == NULL) {
2869 return -1;
2870 }
2871 }
2872 if (PyUnicode_Tailmatch(self->text, exec_prefix,
2873 start, text_len, -1)) {
2874 Py_CLEAR(self->msg);
2875 self->msg = PyUnicode_FromString(
2876 "Missing parentheses in call to 'exec'");
2877 return 1;
2878 }
2879 /* Fall back to the default error message */
2880 return 0;
2881}
2882
2883static int
2884_report_missing_parentheses(PySyntaxErrorObject *self)
2885{
2886 Py_UCS4 left_paren = 40;
2887 Py_ssize_t left_paren_index;
2888 Py_ssize_t text_len = PyUnicode_GET_LENGTH(self->text);
2889 int legacy_check_result = 0;
2890
2891 /* Skip entirely if there is an opening parenthesis */
2892 left_paren_index = PyUnicode_FindChar(self->text, left_paren,
2893 0, text_len, 1);
2894 if (left_paren_index < -1) {
2895 return -1;
2896 }
2897 if (left_paren_index != -1) {
2898 /* Use default error message for any line with an opening paren */
2899 return 0;
2900 }
2901 /* Handle the simple statement case */
2902 legacy_check_result = _check_for_legacy_statements(self, 0);
2903 if (legacy_check_result < 0) {
2904 return -1;
2905
2906 }
2907 if (legacy_check_result == 0) {
2908 /* Handle the one-line complex statement case */
2909 Py_UCS4 colon = 58;
2910 Py_ssize_t colon_index;
2911 colon_index = PyUnicode_FindChar(self->text, colon,
2912 0, text_len, 1);
2913 if (colon_index < -1) {
2914 return -1;
2915 }
2916 if (colon_index >= 0 && colon_index < text_len) {
2917 /* Check again, starting from just after the colon */
2918 if (_check_for_legacy_statements(self, colon_index+1) < 0) {
2919 return -1;
2920 }
2921 }
2922 }
2923 return 0;
2924}