blob: 607d5cf57cf9ea19bee1beed11c16ecb9cadbf14 [file] [log] [blame]
Barry Warsaw675ac282000-05-26 19:05:16 +00001/* This module provides the suite of standard class-based exceptions for
2 * Python's builtin module. This is a complete C implementation of what,
3 * in Python 1.5.2, was contained in the exceptions.py module. The problem
4 * there was that if exceptions.py could not be imported for some reason,
5 * the entire interpreter would abort.
6 *
7 * By moving the exceptions into C and statically linking, we can guarantee
8 * that the standard exceptions will always be available.
9 *
10 * history:
11 * 98-08-19 fl created (for pyexe)
12 * 00-02-08 fl updated for 1.5.2
13 * 26-May-2000 baw vetted for Python 1.6
14 *
15 * written by Fredrik Lundh
16 * modifications, additions, cleanups, and proofreading by Barry Warsaw
17 *
18 * Copyright (c) 1998-2000 by Secret Labs AB. All rights reserved.
19 */
20
21#include "Python.h"
Fred Drake185a29b2000-08-15 16:20:36 +000022#include "osdefs.h"
Barry Warsaw675ac282000-05-26 19:05:16 +000023
Tim Petersbf26e072000-07-12 04:02:10 +000024/* Caution: MS Visual C++ 6 errors if a single string literal exceeds
25 * 2Kb. So the module docstring has been broken roughly in half, using
26 * compile-time literal concatenation.
27 */
Skip Montanaro995895f2002-03-28 20:57:51 +000028
29/* NOTE: If the exception class hierarchy changes, don't forget to update
30 * Doc/lib/libexcs.tex!
31 */
32
Barry Warsaw675ac282000-05-26 19:05:16 +000033static char
Barry Warsaw9667ed22001-01-23 16:08:34 +000034module__doc__[] =
Barry Warsaw675ac282000-05-26 19:05:16 +000035"Python's standard exception class hierarchy.\n\
36\n\
37Before Python 1.5, the standard exceptions were all simple string objects.\n\
38In Python 1.5, the standard exceptions were converted to classes organized\n\
39into a relatively flat hierarchy. String-based standard exceptions were\n\
40optional, or used as a fallback if some problem occurred while importing\n\
41the exception module. With Python 1.6, optional string-based standard\n\
42exceptions were removed (along with the -X command line flag).\n\
43\n\
44The class exceptions were implemented in such a way as to be almost\n\
45completely backward compatible. Some tricky uses of IOError could\n\
46potentially have broken, but by Python 1.6, all of these should have\n\
47been fixed. As of Python 1.6, the class-based standard exceptions are\n\
48now implemented in C, and are guaranteed to exist in the Python\n\
49interpreter.\n\
50\n\
51Here is a rundown of the class hierarchy. The classes found here are\n\
52inserted into both the exceptions module and the `built-in' module. It is\n\
53recommended that user defined class based exceptions be derived from the\n\
Tim Petersbf26e072000-07-12 04:02:10 +000054`Exception' class, although this is currently not enforced.\n"
55 /* keep string pieces "small" */
56"\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000057Exception\n\
58 |\n\
59 +-- SystemExit\n\
Guido van Rossum59d1d2b2001-04-20 19:13:02 +000060 +-- StopIteration\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000061 +-- StandardError\n\
Barry Warsaw9667ed22001-01-23 16:08:34 +000062 | |\n\
63 | +-- KeyboardInterrupt\n\
64 | +-- ImportError\n\
65 | +-- EnvironmentError\n\
66 | | |\n\
67 | | +-- IOError\n\
68 | | +-- OSError\n\
69 | | |\n\
70 | | +-- WindowsError\n\
71 | |\n\
72 | +-- EOFError\n\
73 | +-- RuntimeError\n\
74 | | |\n\
75 | | +-- NotImplementedError\n\
76 | |\n\
77 | +-- NameError\n\
78 | | |\n\
79 | | +-- UnboundLocalError\n\
80 | |\n\
81 | +-- AttributeError\n\
82 | +-- SyntaxError\n\
83 | | |\n\
84 | | +-- IndentationError\n\
85 | | |\n\
86 | | +-- TabError\n\
87 | |\n\
88 | +-- TypeError\n\
89 | +-- AssertionError\n\
90 | +-- LookupError\n\
91 | | |\n\
92 | | +-- IndexError\n\
93 | | +-- KeyError\n\
94 | |\n\
95 | +-- ArithmeticError\n\
96 | | |\n\
97 | | +-- OverflowError\n\
98 | | +-- ZeroDivisionError\n\
99 | | +-- FloatingPointError\n\
100 | |\n\
101 | +-- ValueError\n\
102 | | |\n\
103 | | +-- UnicodeError\n\
104 | |\n\
Fred Drakebb9fa212001-10-05 21:50:08 +0000105 | +-- ReferenceError\n\
Barry Warsaw9667ed22001-01-23 16:08:34 +0000106 | +-- SystemError\n\
107 | +-- MemoryError\n\
108 |\n\
109 +---Warning\n\
Barry Warsaw675ac282000-05-26 19:05:16 +0000110 |\n\
Barry Warsaw9667ed22001-01-23 16:08:34 +0000111 +-- UserWarning\n\
112 +-- DeprecationWarning\n\
113 +-- SyntaxWarning\n\
Guido van Rossumae347b32001-08-23 02:56:07 +0000114 +-- OverflowWarning\n\
Barry Warsaw9667ed22001-01-23 16:08:34 +0000115 +-- RuntimeWarning";
Barry Warsaw675ac282000-05-26 19:05:16 +0000116
117
118/* Helper function for populating a dictionary with method wrappers. */
119static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000120populate_methods(PyObject *klass, PyObject *dict, PyMethodDef *methods)
Barry Warsaw675ac282000-05-26 19:05:16 +0000121{
122 if (!methods)
123 return 0;
124
125 while (methods->ml_name) {
126 /* get a wrapper for the built-in function */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000127 PyObject *func = PyCFunction_New(methods, NULL);
128 PyObject *meth;
Barry Warsaw675ac282000-05-26 19:05:16 +0000129 int status;
130
131 if (!func)
132 return -1;
133
134 /* turn the function into an unbound method */
135 if (!(meth = PyMethod_New(func, NULL, klass))) {
136 Py_DECREF(func);
137 return -1;
138 }
Barry Warsaw9667ed22001-01-23 16:08:34 +0000139
Barry Warsaw675ac282000-05-26 19:05:16 +0000140 /* add method to dictionary */
141 status = PyDict_SetItemString(dict, methods->ml_name, meth);
142 Py_DECREF(meth);
143 Py_DECREF(func);
144
145 /* stop now if an error occurred, otherwise do the next method */
146 if (status)
147 return status;
148
149 methods++;
150 }
151 return 0;
152}
153
Barry Warsaw9667ed22001-01-23 16:08:34 +0000154
Barry Warsaw675ac282000-05-26 19:05:16 +0000155
156/* This function is used to create all subsequent exception classes. */
157static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000158make_class(PyObject **klass, PyObject *base,
159 char *name, PyMethodDef *methods,
160 char *docstr)
Barry Warsaw675ac282000-05-26 19:05:16 +0000161{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000162 PyObject *dict = PyDict_New();
163 PyObject *str = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000164 int status = -1;
165
166 if (!dict)
167 return -1;
168
169 /* If an error occurs from here on, goto finally instead of explicitly
170 * returning NULL.
171 */
172
173 if (docstr) {
174 if (!(str = PyString_FromString(docstr)))
175 goto finally;
176 if (PyDict_SetItemString(dict, "__doc__", str))
177 goto finally;
178 }
179
180 if (!(*klass = PyErr_NewException(name, base, dict)))
181 goto finally;
182
183 if (populate_methods(*klass, dict, methods)) {
184 Py_DECREF(*klass);
185 *klass = NULL;
Barry Warsaw9667ed22001-01-23 16:08:34 +0000186 goto finally;
Barry Warsaw675ac282000-05-26 19:05:16 +0000187 }
188
189 status = 0;
190
191 finally:
192 Py_XDECREF(dict);
193 Py_XDECREF(str);
194 return status;
195}
196
197
198/* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000199static PyObject *
200get_self(PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000201{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000202 PyObject *self = PyTuple_GetItem(args, 0);
Barry Warsaw675ac282000-05-26 19:05:16 +0000203 if (!self) {
Thomas Wouters7e474022000-07-16 12:04:32 +0000204 /* Watch out for being called to early in the bootstrapping process */
Barry Warsaw675ac282000-05-26 19:05:16 +0000205 if (PyExc_TypeError) {
206 PyErr_SetString(PyExc_TypeError,
Fred Drake661ea262000-10-24 19:57:45 +0000207 "unbound method must be called with instance as first argument");
Barry Warsaw675ac282000-05-26 19:05:16 +0000208 }
209 return NULL;
210 }
211 return self;
212}
213
214
215
216/* Notes on bootstrapping the exception classes.
217 *
218 * First thing we create is the base class for all exceptions, called
219 * appropriately enough: Exception. Creation of this class makes no
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000220 * assumptions about the existence of any other exception class -- except
Barry Warsaw675ac282000-05-26 19:05:16 +0000221 * for TypeError, which can conditionally exist.
222 *
223 * Next, StandardError is created (which is quite simple) followed by
224 * TypeError, because the instantiation of other exceptions can potentially
225 * throw a TypeError. Once these exceptions are created, all the others
226 * can be created in any order. See the static exctable below for the
227 * explicit bootstrap order.
228 *
229 * All classes after Exception can be created using PyErr_NewException().
230 */
231
232static char
233Exception__doc__[] = "Common base class for all exceptions.";
234
235
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000236static PyObject *
237Exception__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000238{
239 int status;
240
241 if (!(self = get_self(args)))
242 return NULL;
243
244 /* set args attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000245 /* XXX size is only a hint */
246 args = PySequence_GetSlice(args, 1, PySequence_Size(args));
Barry Warsaw675ac282000-05-26 19:05:16 +0000247 if (!args)
248 return NULL;
249 status = PyObject_SetAttrString(self, "args", args);
250 Py_DECREF(args);
251 if (status < 0)
252 return NULL;
253
254 Py_INCREF(Py_None);
255 return Py_None;
256}
257
258
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000259static PyObject *
260Exception__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000261{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000262 PyObject *out;
Barry Warsaw675ac282000-05-26 19:05:16 +0000263
Fred Drake1aba5772000-08-15 15:46:16 +0000264 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000265 return NULL;
266
267 args = PyObject_GetAttrString(self, "args");
268 if (!args)
269 return NULL;
270
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000271 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000272 case 0:
273 out = PyString_FromString("");
274 break;
275 case 1:
Barry Warsawb7816552000-07-09 22:27:10 +0000276 {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000277 PyObject *tmp = PySequence_GetItem(args, 0);
Barry Warsawb7816552000-07-09 22:27:10 +0000278 if (tmp) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000279 out = PyObject_Str(tmp);
Barry Warsawb7816552000-07-09 22:27:10 +0000280 Py_DECREF(tmp);
281 }
282 else
283 out = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000284 break;
Barry Warsawb7816552000-07-09 22:27:10 +0000285 }
Barry Warsaw675ac282000-05-26 19:05:16 +0000286 default:
287 out = PyObject_Str(args);
288 break;
289 }
290
291 Py_DECREF(args);
292 return out;
293}
294
295
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000296static PyObject *
297Exception__getitem__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000298{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000299 PyObject *out;
300 PyObject *index;
Barry Warsaw675ac282000-05-26 19:05:16 +0000301
Fred Drake1aba5772000-08-15 15:46:16 +0000302 if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index))
Barry Warsaw675ac282000-05-26 19:05:16 +0000303 return NULL;
304
305 args = PyObject_GetAttrString(self, "args");
306 if (!args)
307 return NULL;
308
309 out = PyObject_GetItem(args, index);
310 Py_DECREF(args);
311 return out;
312}
313
314
315static PyMethodDef
316Exception_methods[] = {
317 /* methods for the Exception class */
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000318 { "__getitem__", Exception__getitem__, METH_VARARGS},
319 { "__str__", Exception__str__, METH_VARARGS},
320 { "__init__", Exception__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000321 { NULL, NULL }
322};
323
324
325static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000326make_Exception(char *modulename)
Barry Warsaw675ac282000-05-26 19:05:16 +0000327{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000328 PyObject *dict = PyDict_New();
329 PyObject *str = NULL;
330 PyObject *name = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000331 int status = -1;
332
333 if (!dict)
334 return -1;
335
336 /* If an error occurs from here on, goto finally instead of explicitly
337 * returning NULL.
338 */
339
340 if (!(str = PyString_FromString(modulename)))
341 goto finally;
342 if (PyDict_SetItemString(dict, "__module__", str))
343 goto finally;
344 Py_DECREF(str);
345 if (!(str = PyString_FromString(Exception__doc__)))
346 goto finally;
347 if (PyDict_SetItemString(dict, "__doc__", str))
348 goto finally;
349
350 if (!(name = PyString_FromString("Exception")))
351 goto finally;
Barry Warsaw9667ed22001-01-23 16:08:34 +0000352
Barry Warsaw675ac282000-05-26 19:05:16 +0000353 if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
354 goto finally;
355
356 /* Now populate the dictionary with the method suite */
357 if (populate_methods(PyExc_Exception, dict, Exception_methods))
358 /* Don't need to reclaim PyExc_Exception here because that'll
359 * happen during interpreter shutdown.
360 */
361 goto finally;
362
363 status = 0;
364
365 finally:
366 Py_XDECREF(dict);
367 Py_XDECREF(str);
368 Py_XDECREF(name);
369 return status;
370}
371
372
373
374static char
375StandardError__doc__[] = "Base class for all standard Python exceptions.";
376
377static char
378TypeError__doc__[] = "Inappropriate argument type.";
379
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000380static char
381StopIteration__doc__[] = "Signal the end from iterator.next().";
382
Barry Warsaw675ac282000-05-26 19:05:16 +0000383
384
385static char
386SystemExit__doc__[] = "Request to exit from the interpreter.";
387
388
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000389static PyObject *
390SystemExit__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000391{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000392 PyObject *code;
Barry Warsaw675ac282000-05-26 19:05:16 +0000393 int status;
394
395 if (!(self = get_self(args)))
396 return NULL;
397
398 /* Set args attribute. */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000399 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000400 return NULL;
Barry Warsaw9667ed22001-01-23 16:08:34 +0000401
Barry Warsaw675ac282000-05-26 19:05:16 +0000402 status = PyObject_SetAttrString(self, "args", args);
403 if (status < 0) {
404 Py_DECREF(args);
405 return NULL;
406 }
407
408 /* set code attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000409 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000410 case 0:
411 Py_INCREF(Py_None);
412 code = Py_None;
413 break;
414 case 1:
415 code = PySequence_GetItem(args, 0);
416 break;
417 default:
418 Py_INCREF(args);
419 code = args;
420 break;
421 }
422
423 status = PyObject_SetAttrString(self, "code", code);
424 Py_DECREF(code);
425 Py_DECREF(args);
426 if (status < 0)
427 return NULL;
428
429 Py_INCREF(Py_None);
430 return Py_None;
431}
432
433
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000434static PyMethodDef SystemExit_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000435 { "__init__", SystemExit__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000436 {NULL, NULL}
437};
438
439
440
441static char
442KeyboardInterrupt__doc__[] = "Program interrupted by user.";
443
444static char
445ImportError__doc__[] =
446"Import can't find module, or can't find name in module.";
447
448
449
450static char
451EnvironmentError__doc__[] = "Base class for I/O related errors.";
452
453
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000454static PyObject *
455EnvironmentError__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000456{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000457 PyObject *item0 = NULL;
458 PyObject *item1 = NULL;
459 PyObject *item2 = NULL;
460 PyObject *subslice = NULL;
461 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000462
463 if (!(self = get_self(args)))
464 return NULL;
465
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000466 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000467 return NULL;
468
469 if (PyObject_SetAttrString(self, "args", args) ||
470 PyObject_SetAttrString(self, "errno", Py_None) ||
471 PyObject_SetAttrString(self, "strerror", Py_None) ||
472 PyObject_SetAttrString(self, "filename", Py_None))
473 {
474 goto finally;
475 }
476
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000477 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000478 case 3:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000479 /* Where a function has a single filename, such as open() or some
480 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
481 * called, giving a third argument which is the filename. But, so
482 * that old code using in-place unpacking doesn't break, e.g.:
Barry Warsaw9667ed22001-01-23 16:08:34 +0000483 *
Barry Warsaw675ac282000-05-26 19:05:16 +0000484 * except IOError, (errno, strerror):
Barry Warsaw9667ed22001-01-23 16:08:34 +0000485 *
Barry Warsaw675ac282000-05-26 19:05:16 +0000486 * we hack args so that it only contains two items. This also
487 * means we need our own __str__() which prints out the filename
488 * when it was supplied.
489 */
490 item0 = PySequence_GetItem(args, 0);
491 item1 = PySequence_GetItem(args, 1);
492 item2 = PySequence_GetItem(args, 2);
493 if (!item0 || !item1 || !item2)
494 goto finally;
Barry Warsaw9667ed22001-01-23 16:08:34 +0000495
Barry Warsaw675ac282000-05-26 19:05:16 +0000496 if (PyObject_SetAttrString(self, "errno", item0) ||
497 PyObject_SetAttrString(self, "strerror", item1) ||
498 PyObject_SetAttrString(self, "filename", item2))
499 {
500 goto finally;
501 }
502
503 subslice = PySequence_GetSlice(args, 0, 2);
504 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
505 goto finally;
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000506 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000507
508 case 2:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000509 /* Used when PyErr_SetFromErrno() is called and no filename
510 * argument is given.
511 */
Barry Warsaw675ac282000-05-26 19:05:16 +0000512 item0 = PySequence_GetItem(args, 0);
513 item1 = PySequence_GetItem(args, 1);
514 if (!item0 || !item1)
515 goto finally;
Barry Warsaw9667ed22001-01-23 16:08:34 +0000516
Barry Warsaw675ac282000-05-26 19:05:16 +0000517 if (PyObject_SetAttrString(self, "errno", item0) ||
518 PyObject_SetAttrString(self, "strerror", item1))
519 {
520 goto finally;
521 }
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000522 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000523 }
524
525 Py_INCREF(Py_None);
526 rtnval = Py_None;
527
528 finally:
529 Py_DECREF(args);
530 Py_XDECREF(item0);
531 Py_XDECREF(item1);
532 Py_XDECREF(item2);
533 Py_XDECREF(subslice);
534 return rtnval;
535}
536
537
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000538static PyObject *
539EnvironmentError__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000540{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000541 PyObject *originalself = self;
542 PyObject *filename;
543 PyObject *serrno;
544 PyObject *strerror;
545 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000546
Fred Drake1aba5772000-08-15 15:46:16 +0000547 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000548 return NULL;
Barry Warsaw9667ed22001-01-23 16:08:34 +0000549
Barry Warsaw675ac282000-05-26 19:05:16 +0000550 filename = PyObject_GetAttrString(self, "filename");
551 serrno = PyObject_GetAttrString(self, "errno");
552 strerror = PyObject_GetAttrString(self, "strerror");
553 if (!filename || !serrno || !strerror)
554 goto finally;
555
556 if (filename != Py_None) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000557 PyObject *fmt = PyString_FromString("[Errno %s] %s: %s");
558 PyObject *repr = PyObject_Repr(filename);
559 PyObject *tuple = PyTuple_New(3);
Barry Warsaw675ac282000-05-26 19:05:16 +0000560
561 if (!fmt || !repr || !tuple) {
562 Py_XDECREF(fmt);
563 Py_XDECREF(repr);
564 Py_XDECREF(tuple);
565 goto finally;
566 }
567
568 PyTuple_SET_ITEM(tuple, 0, serrno);
569 PyTuple_SET_ITEM(tuple, 1, strerror);
570 PyTuple_SET_ITEM(tuple, 2, repr);
571
572 rtnval = PyString_Format(fmt, tuple);
573
574 Py_DECREF(fmt);
575 Py_DECREF(tuple);
576 /* already freed because tuple owned only reference */
577 serrno = NULL;
578 strerror = NULL;
579 }
580 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000581 PyObject *fmt = PyString_FromString("[Errno %s] %s");
582 PyObject *tuple = PyTuple_New(2);
Barry Warsaw675ac282000-05-26 19:05:16 +0000583
584 if (!fmt || !tuple) {
585 Py_XDECREF(fmt);
586 Py_XDECREF(tuple);
587 goto finally;
588 }
589
590 PyTuple_SET_ITEM(tuple, 0, serrno);
591 PyTuple_SET_ITEM(tuple, 1, strerror);
Barry Warsaw9667ed22001-01-23 16:08:34 +0000592
Barry Warsaw675ac282000-05-26 19:05:16 +0000593 rtnval = PyString_Format(fmt, tuple);
594
595 Py_DECREF(fmt);
596 Py_DECREF(tuple);
597 /* already freed because tuple owned only reference */
598 serrno = NULL;
599 strerror = NULL;
600 }
601 else
602 /* The original Python code said:
603 *
604 * return StandardError.__str__(self)
605 *
606 * but there is no StandardError__str__() function; we happen to
607 * know that's just a pass through to Exception__str__().
608 */
609 rtnval = Exception__str__(originalself, args);
610
611 finally:
612 Py_XDECREF(filename);
613 Py_XDECREF(serrno);
614 Py_XDECREF(strerror);
615 return rtnval;
616}
617
618
619static
620PyMethodDef EnvironmentError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000621 {"__init__", EnvironmentError__init__, METH_VARARGS},
622 {"__str__", EnvironmentError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000623 {NULL, NULL}
624};
625
626
627
628
629static char
630IOError__doc__[] = "I/O operation failed.";
631
632static char
633OSError__doc__[] = "OS system call failed.";
634
635#ifdef MS_WINDOWS
636static char
637WindowsError__doc__[] = "MS-Windows OS system call failed.";
638#endif /* MS_WINDOWS */
639
640static char
641EOFError__doc__[] = "Read beyond end of file.";
642
643static char
644RuntimeError__doc__[] = "Unspecified run-time error.";
645
646static char
647NotImplementedError__doc__[] =
648"Method or function hasn't been implemented yet.";
649
650static char
651NameError__doc__[] = "Name not found globally.";
652
653static char
654UnboundLocalError__doc__[] =
655"Local name referenced but not bound to a value.";
656
657static char
658AttributeError__doc__[] = "Attribute not found.";
659
660
661
662static char
663SyntaxError__doc__[] = "Invalid syntax.";
664
665
666static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000667SyntaxError__classinit__(PyObject *klass)
Barry Warsaw675ac282000-05-26 19:05:16 +0000668{
Barry Warsaw87bec352000-08-18 05:05:37 +0000669 int retval = 0;
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000670 PyObject *emptystring = PyString_FromString("");
Barry Warsaw675ac282000-05-26 19:05:16 +0000671
672 /* Additional class-creation time initializations */
673 if (!emptystring ||
674 PyObject_SetAttrString(klass, "msg", emptystring) ||
675 PyObject_SetAttrString(klass, "filename", Py_None) ||
676 PyObject_SetAttrString(klass, "lineno", Py_None) ||
677 PyObject_SetAttrString(klass, "offset", Py_None) ||
Martin v. Löwiscfeb3b62002-03-03 21:30:27 +0000678 PyObject_SetAttrString(klass, "text", Py_None) ||
679 PyObject_SetAttrString(klass, "print_file_and_line", Py_None))
Barry Warsaw675ac282000-05-26 19:05:16 +0000680 {
Barry Warsaw87bec352000-08-18 05:05:37 +0000681 retval = -1;
Barry Warsaw675ac282000-05-26 19:05:16 +0000682 }
Barry Warsaw87bec352000-08-18 05:05:37 +0000683 Py_XDECREF(emptystring);
684 return retval;
Barry Warsaw675ac282000-05-26 19:05:16 +0000685}
686
687
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000688static PyObject *
689SyntaxError__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000690{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000691 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000692 int lenargs;
693
694 if (!(self = get_self(args)))
695 return NULL;
696
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000697 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000698 return NULL;
699
700 if (PyObject_SetAttrString(self, "args", args))
701 goto finally;
702
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000703 lenargs = PySequence_Size(args);
Barry Warsaw675ac282000-05-26 19:05:16 +0000704 if (lenargs >= 1) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000705 PyObject *item0 = PySequence_GetItem(args, 0);
Barry Warsaw675ac282000-05-26 19:05:16 +0000706 int status;
707
708 if (!item0)
709 goto finally;
710 status = PyObject_SetAttrString(self, "msg", item0);
711 Py_DECREF(item0);
712 if (status)
713 goto finally;
714 }
715 if (lenargs == 2) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000716 PyObject *info = PySequence_GetItem(args, 1);
Fred Drake9da7f3b2001-02-28 21:52:10 +0000717 PyObject *filename = NULL, *lineno = NULL;
718 PyObject *offset = NULL, *text = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000719 int status = 1;
720
721 if (!info)
722 goto finally;
723
724 filename = PySequence_GetItem(info, 0);
Fred Drake9da7f3b2001-02-28 21:52:10 +0000725 if (filename != NULL) {
726 lineno = PySequence_GetItem(info, 1);
727 if (lineno != NULL) {
728 offset = PySequence_GetItem(info, 2);
729 if (offset != NULL) {
730 text = PySequence_GetItem(info, 3);
731 if (text != NULL) {
732 status =
733 PyObject_SetAttrString(self, "filename", filename)
734 || PyObject_SetAttrString(self, "lineno", lineno)
735 || PyObject_SetAttrString(self, "offset", offset)
736 || PyObject_SetAttrString(self, "text", text);
737 Py_DECREF(text);
738 }
739 Py_DECREF(offset);
740 }
741 Py_DECREF(lineno);
742 }
743 Py_DECREF(filename);
Barry Warsaw675ac282000-05-26 19:05:16 +0000744 }
Fred Drake9da7f3b2001-02-28 21:52:10 +0000745 Py_DECREF(info);
Barry Warsaw675ac282000-05-26 19:05:16 +0000746
747 if (status)
748 goto finally;
749 }
750 Py_INCREF(Py_None);
751 rtnval = Py_None;
752
753 finally:
754 Py_DECREF(args);
755 return rtnval;
756}
757
758
Fred Drake185a29b2000-08-15 16:20:36 +0000759/* This is called "my_basename" instead of just "basename" to avoid name
760 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
761 defined, and Python does define that. */
762static char *
763my_basename(char *name)
764{
765 char *cp = name;
766 char *result = name;
767
768 if (name == NULL)
769 return "???";
770 while (*cp != '\0') {
771 if (*cp == SEP)
772 result = cp + 1;
773 ++cp;
774 }
775 return result;
776}
777
778
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000779static PyObject *
780SyntaxError__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000781{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000782 PyObject *msg;
783 PyObject *str;
Fred Drake1aba5772000-08-15 15:46:16 +0000784 PyObject *filename, *lineno, *result;
Barry Warsaw675ac282000-05-26 19:05:16 +0000785
Fred Drake1aba5772000-08-15 15:46:16 +0000786 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000787 return NULL;
788
789 if (!(msg = PyObject_GetAttrString(self, "msg")))
790 return NULL;
Fred Drake1aba5772000-08-15 15:46:16 +0000791
Barry Warsaw675ac282000-05-26 19:05:16 +0000792 str = PyObject_Str(msg);
793 Py_DECREF(msg);
Fred Drake1aba5772000-08-15 15:46:16 +0000794 result = str;
795
796 /* XXX -- do all the additional formatting with filename and
797 lineno here */
798
799 if (PyString_Check(str)) {
800 int have_filename = 0;
801 int have_lineno = 0;
802 char *buffer = NULL;
803
Barry Warsaw77c9f502000-08-16 19:43:17 +0000804 if ((filename = PyObject_GetAttrString(self, "filename")) != NULL)
Fred Drake1aba5772000-08-15 15:46:16 +0000805 have_filename = PyString_Check(filename);
806 else
807 PyErr_Clear();
Barry Warsaw77c9f502000-08-16 19:43:17 +0000808
809 if ((lineno = PyObject_GetAttrString(self, "lineno")) != NULL)
Fred Drake1aba5772000-08-15 15:46:16 +0000810 have_lineno = PyInt_Check(lineno);
811 else
812 PyErr_Clear();
813
814 if (have_filename || have_lineno) {
Barry Warsaw77c9f502000-08-16 19:43:17 +0000815 int bufsize = PyString_GET_SIZE(str) + 64;
816 if (have_filename)
817 bufsize += PyString_GET_SIZE(filename);
Fred Drake1aba5772000-08-15 15:46:16 +0000818
Jeremy Hylton05bd7872001-11-28 20:24:33 +0000819 buffer = PyMem_MALLOC(bufsize);
Fred Drake1aba5772000-08-15 15:46:16 +0000820 if (buffer != NULL) {
821 if (have_filename && have_lineno)
Jeremy Hylton05bd7872001-11-28 20:24:33 +0000822 PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)",
823 PyString_AS_STRING(str),
824 my_basename(PyString_AS_STRING(filename)),
825 PyInt_AsLong(lineno));
Fred Drake1aba5772000-08-15 15:46:16 +0000826 else if (have_filename)
Jeremy Hylton05bd7872001-11-28 20:24:33 +0000827 PyOS_snprintf(buffer, bufsize, "%s (%s)",
828 PyString_AS_STRING(str),
829 my_basename(PyString_AS_STRING(filename)));
Fred Drake1aba5772000-08-15 15:46:16 +0000830 else if (have_lineno)
Jeremy Hylton05bd7872001-11-28 20:24:33 +0000831 PyOS_snprintf(buffer, bufsize, "%s (line %ld)",
832 PyString_AS_STRING(str),
833 PyInt_AsLong(lineno));
Barry Warsaw77c9f502000-08-16 19:43:17 +0000834
Fred Drake1aba5772000-08-15 15:46:16 +0000835 result = PyString_FromString(buffer);
Barry Warsaw77c9f502000-08-16 19:43:17 +0000836 PyMem_FREE(buffer);
837
Fred Drake1aba5772000-08-15 15:46:16 +0000838 if (result == NULL)
839 result = str;
840 else
841 Py_DECREF(str);
842 }
843 }
844 Py_XDECREF(filename);
845 Py_XDECREF(lineno);
846 }
847 return result;
Barry Warsaw675ac282000-05-26 19:05:16 +0000848}
849
850
Guido van Rossumf68d8e52001-04-14 17:55:09 +0000851static PyMethodDef SyntaxError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000852 {"__init__", SyntaxError__init__, METH_VARARGS},
853 {"__str__", SyntaxError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000854 {NULL, NULL}
855};
856
857
858
Guido van Rossumd0977cd2000-12-15 21:58:29 +0000859/* Exception doc strings */
860
Barry Warsaw675ac282000-05-26 19:05:16 +0000861static char
862AssertionError__doc__[] = "Assertion failed.";
863
864static char
865LookupError__doc__[] = "Base class for lookup errors.";
866
867static char
868IndexError__doc__[] = "Sequence index out of range.";
869
870static char
871KeyError__doc__[] = "Mapping key not found.";
872
873static char
874ArithmeticError__doc__[] = "Base class for arithmetic errors.";
875
876static char
877OverflowError__doc__[] = "Result too large to be represented.";
878
879static char
880ZeroDivisionError__doc__[] =
881"Second argument to a division or modulo operation was zero.";
882
883static char
884FloatingPointError__doc__[] = "Floating point operation failed.";
885
886static char
887ValueError__doc__[] = "Inappropriate argument value (of correct type).";
888
889static char
890UnicodeError__doc__[] = "Unicode related error.";
891
892static char
893SystemError__doc__[] = "Internal error in the Python interpreter.\n\
894\n\
895Please report this to the Python maintainer, along with the traceback,\n\
896the Python version, and the hardware/OS platform and version.";
897
898static char
Fred Drakebb9fa212001-10-05 21:50:08 +0000899ReferenceError__doc__[] = "Weak ref proxy used after referent went away.";
900
901static char
Barry Warsaw675ac282000-05-26 19:05:16 +0000902MemoryError__doc__[] = "Out of memory.";
903
Fred Drake85f36392000-07-11 17:53:00 +0000904static char
905IndentationError__doc__[] = "Improper indentation.";
906
907static char
908TabError__doc__[] = "Improper mixture of spaces and tabs.";
909
Guido van Rossumd0977cd2000-12-15 21:58:29 +0000910/* Warning category docstrings */
911
912static char
913Warning__doc__[] = "Base class for warning categories.";
914
915static char
916UserWarning__doc__[] = "Base class for warnings generated by user code.";
917
918static char
919DeprecationWarning__doc__[] =
920"Base class for warnings about deprecated features.";
921
922static char
923SyntaxWarning__doc__[] = "Base class for warnings about dubious syntax.";
924
925static char
Guido van Rossumae347b32001-08-23 02:56:07 +0000926OverflowWarning__doc__[] = "Base class for warnings about numeric overflow.";
927
928static char
Guido van Rossumd0977cd2000-12-15 21:58:29 +0000929RuntimeWarning__doc__[] =
930"Base class for warnings about dubious runtime behavior.";
931
Barry Warsaw675ac282000-05-26 19:05:16 +0000932
933
934/* module global functions */
935static PyMethodDef functions[] = {
936 /* Sentinel */
937 {NULL, NULL}
938};
939
940
941
942/* Global C API defined exceptions */
943
944PyObject *PyExc_Exception;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +0000945PyObject *PyExc_StopIteration;
Barry Warsaw675ac282000-05-26 19:05:16 +0000946PyObject *PyExc_StandardError;
947PyObject *PyExc_ArithmeticError;
948PyObject *PyExc_LookupError;
949
950PyObject *PyExc_AssertionError;
951PyObject *PyExc_AttributeError;
952PyObject *PyExc_EOFError;
953PyObject *PyExc_FloatingPointError;
954PyObject *PyExc_EnvironmentError;
955PyObject *PyExc_IOError;
956PyObject *PyExc_OSError;
957PyObject *PyExc_ImportError;
958PyObject *PyExc_IndexError;
959PyObject *PyExc_KeyError;
960PyObject *PyExc_KeyboardInterrupt;
961PyObject *PyExc_MemoryError;
962PyObject *PyExc_NameError;
963PyObject *PyExc_OverflowError;
964PyObject *PyExc_RuntimeError;
965PyObject *PyExc_NotImplementedError;
966PyObject *PyExc_SyntaxError;
Fred Drake85f36392000-07-11 17:53:00 +0000967PyObject *PyExc_IndentationError;
968PyObject *PyExc_TabError;
Fred Drakebb9fa212001-10-05 21:50:08 +0000969PyObject *PyExc_ReferenceError;
Barry Warsaw675ac282000-05-26 19:05:16 +0000970PyObject *PyExc_SystemError;
971PyObject *PyExc_SystemExit;
972PyObject *PyExc_UnboundLocalError;
973PyObject *PyExc_UnicodeError;
974PyObject *PyExc_TypeError;
975PyObject *PyExc_ValueError;
976PyObject *PyExc_ZeroDivisionError;
977#ifdef MS_WINDOWS
978PyObject *PyExc_WindowsError;
979#endif
980
981/* Pre-computed MemoryError instance. Best to create this as early as
982 * possibly and not wait until a MemoryError is actually raised!
983 */
984PyObject *PyExc_MemoryErrorInst;
985
Guido van Rossumd0977cd2000-12-15 21:58:29 +0000986/* Predefined warning categories */
987PyObject *PyExc_Warning;
988PyObject *PyExc_UserWarning;
989PyObject *PyExc_DeprecationWarning;
990PyObject *PyExc_SyntaxWarning;
Guido van Rossumae347b32001-08-23 02:56:07 +0000991PyObject *PyExc_OverflowWarning;
Guido van Rossumd0977cd2000-12-15 21:58:29 +0000992PyObject *PyExc_RuntimeWarning;
993
Barry Warsaw675ac282000-05-26 19:05:16 +0000994
995
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000996/* mapping between exception names and their PyObject ** */
997static struct {
998 char *name;
999 PyObject **exc;
1000 PyObject **base; /* NULL == PyExc_StandardError */
1001 char *docstr;
1002 PyMethodDef *methods;
1003 int (*classinit)(PyObject *);
1004} exctable[] = {
Barry Warsaw675ac282000-05-26 19:05:16 +00001005 /*
1006 * The first three classes MUST appear in exactly this order
1007 */
1008 {"Exception", &PyExc_Exception},
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00001009 {"StopIteration", &PyExc_StopIteration, &PyExc_Exception,
1010 StopIteration__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +00001011 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
1012 StandardError__doc__},
1013 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
1014 /*
1015 * The rest appear in depth-first order of the hierarchy
1016 */
1017 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
1018 SystemExit_methods},
1019 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
1020 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
1021 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
1022 EnvironmentError_methods},
1023 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
1024 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
1025#ifdef MS_WINDOWS
Mark Hammond557a0442000-08-15 00:37:32 +00001026 {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
Barry Warsaw675ac282000-05-26 19:05:16 +00001027 WindowsError__doc__},
1028#endif /* MS_WINDOWS */
1029 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
1030 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
1031 {"NotImplementedError", &PyExc_NotImplementedError,
1032 &PyExc_RuntimeError, NotImplementedError__doc__},
1033 {"NameError", &PyExc_NameError, 0, NameError__doc__},
1034 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
1035 UnboundLocalError__doc__},
1036 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
1037 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
1038 SyntaxError_methods, SyntaxError__classinit__},
Fred Drake85f36392000-07-11 17:53:00 +00001039 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
1040 IndentationError__doc__},
1041 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
1042 TabError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +00001043 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
1044 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
1045 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
1046 IndexError__doc__},
1047 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
1048 KeyError__doc__},
1049 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
1050 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
1051 OverflowError__doc__},
1052 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
1053 ZeroDivisionError__doc__},
1054 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
1055 FloatingPointError__doc__},
1056 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
1057 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
Fred Drakebb9fa212001-10-05 21:50:08 +00001058 {"ReferenceError", &PyExc_ReferenceError, 0, ReferenceError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +00001059 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
1060 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
Guido van Rossumd0977cd2000-12-15 21:58:29 +00001061 /* Warning categories */
1062 {"Warning", &PyExc_Warning, &PyExc_Exception, Warning__doc__},
1063 {"UserWarning", &PyExc_UserWarning, &PyExc_Warning, UserWarning__doc__},
1064 {"DeprecationWarning", &PyExc_DeprecationWarning, &PyExc_Warning,
1065 DeprecationWarning__doc__},
1066 {"SyntaxWarning", &PyExc_SyntaxWarning, &PyExc_Warning, SyntaxWarning__doc__},
Guido van Rossumae347b32001-08-23 02:56:07 +00001067 {"OverflowWarning", &PyExc_OverflowWarning, &PyExc_Warning,
1068 OverflowWarning__doc__},
Guido van Rossumd0977cd2000-12-15 21:58:29 +00001069 {"RuntimeWarning", &PyExc_RuntimeWarning, &PyExc_Warning,
1070 RuntimeWarning__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +00001071 /* Sentinel */
1072 {NULL}
1073};
1074
1075
1076
Tim Peters5687ffe2001-02-28 16:44:18 +00001077DL_EXPORT(void)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001078_PyExc_Init(void)
Barry Warsaw675ac282000-05-26 19:05:16 +00001079{
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001080 char *modulename = "exceptions";
Barry Warsaw675ac282000-05-26 19:05:16 +00001081 int modnamesz = strlen(modulename);
1082 int i;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001083 PyObject *me, *mydict, *bltinmod, *bdict, *doc, *args;
Barry Warsaw675ac282000-05-26 19:05:16 +00001084
Tim Peters6d6c1a32001-08-02 04:15:00 +00001085 me = Py_InitModule(modulename, functions);
1086 if (me == NULL)
1087 goto err;
1088 mydict = PyModule_GetDict(me);
1089 if (mydict == NULL)
1090 goto err;
1091 bltinmod = PyImport_ImportModule("__builtin__");
1092 if (bltinmod == NULL)
1093 goto err;
1094 bdict = PyModule_GetDict(bltinmod);
1095 if (bdict == NULL)
1096 goto err;
1097 doc = PyString_FromString(module__doc__);
1098 if (doc == NULL)
1099 goto err;
Barry Warsaw675ac282000-05-26 19:05:16 +00001100
Tim Peters6d6c1a32001-08-02 04:15:00 +00001101 i = PyDict_SetItemString(mydict, "__doc__", doc);
Barry Warsaw8fcaa922000-07-01 04:45:52 +00001102 Py_DECREF(doc);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001103 if (i < 0) {
1104 err:
Barry Warsaw675ac282000-05-26 19:05:16 +00001105 Py_FatalError("exceptions bootstrapping error.");
Tim Peters6d6c1a32001-08-02 04:15:00 +00001106 return;
1107 }
Barry Warsaw675ac282000-05-26 19:05:16 +00001108
1109 /* This is the base class of all exceptions, so make it first. */
1110 if (make_Exception(modulename) ||
1111 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
1112 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
1113 {
1114 Py_FatalError("Base class `Exception' could not be created.");
1115 }
Barry Warsaw9667ed22001-01-23 16:08:34 +00001116
Barry Warsaw675ac282000-05-26 19:05:16 +00001117 /* Now we can programmatically create all the remaining exceptions.
1118 * Remember to start the loop at 1 to skip Exceptions.
1119 */
1120 for (i=1; exctable[i].name; i++) {
1121 int status;
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001122 char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
1123 PyObject *base;
Barry Warsaw675ac282000-05-26 19:05:16 +00001124
1125 (void)strcpy(cname, modulename);
1126 (void)strcat(cname, ".");
1127 (void)strcat(cname, exctable[i].name);
1128
1129 if (exctable[i].base == 0)
1130 base = PyExc_StandardError;
1131 else
1132 base = *exctable[i].base;
1133
1134 status = make_class(exctable[i].exc, base, cname,
1135 exctable[i].methods,
1136 exctable[i].docstr);
1137
1138 PyMem_DEL(cname);
1139
1140 if (status)
1141 Py_FatalError("Standard exception classes could not be created.");
1142
1143 if (exctable[i].classinit) {
1144 status = (*exctable[i].classinit)(*exctable[i].exc);
1145 if (status)
1146 Py_FatalError("An exception class could not be initialized.");
1147 }
1148
1149 /* Now insert the class into both this module and the __builtin__
1150 * module.
1151 */
1152 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
1153 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
1154 {
1155 Py_FatalError("Module dictionary insertion problem.");
1156 }
1157 }
1158
1159 /* Now we need to pre-allocate a MemoryError instance */
1160 args = Py_BuildValue("()");
1161 if (!args ||
1162 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1163 {
1164 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1165 }
1166 Py_DECREF(args);
1167
1168 /* We're done with __builtin__ */
1169 Py_DECREF(bltinmod);
1170}
1171
1172
Tim Peters5687ffe2001-02-28 16:44:18 +00001173DL_EXPORT(void)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001174_PyExc_Fini(void)
Barry Warsaw675ac282000-05-26 19:05:16 +00001175{
1176 int i;
1177
1178 Py_XDECREF(PyExc_MemoryErrorInst);
1179 PyExc_MemoryErrorInst = NULL;
1180
1181 for (i=0; exctable[i].name; i++) {
Barry Warsaw9667ed22001-01-23 16:08:34 +00001182 /* clear the class's dictionary, freeing up circular references
1183 * between the class and its methods.
1184 */
1185 PyObject* cdict = PyObject_GetAttrString(*exctable[i].exc, "__dict__");
1186 PyDict_Clear(cdict);
1187 Py_DECREF(cdict);
1188
1189 /* Now decref the exception class */
Barry Warsaw675ac282000-05-26 19:05:16 +00001190 Py_XDECREF(*exctable[i].exc);
1191 *exctable[i].exc = NULL;
1192 }
1193}