blob: 1d7fac46ce621153d204279c0434462dbfebddb7 [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"
22
Tim Petersbf26e072000-07-12 04:02:10 +000023/* Caution: MS Visual C++ 6 errors if a single string literal exceeds
24 * 2Kb. So the module docstring has been broken roughly in half, using
25 * compile-time literal concatenation.
26 */
Barry Warsaw675ac282000-05-26 19:05:16 +000027static char
28module__doc__[] =
29"Python's standard exception class hierarchy.\n\
30\n\
31Before Python 1.5, the standard exceptions were all simple string objects.\n\
32In Python 1.5, the standard exceptions were converted to classes organized\n\
33into a relatively flat hierarchy. String-based standard exceptions were\n\
34optional, or used as a fallback if some problem occurred while importing\n\
35the exception module. With Python 1.6, optional string-based standard\n\
36exceptions were removed (along with the -X command line flag).\n\
37\n\
38The class exceptions were implemented in such a way as to be almost\n\
39completely backward compatible. Some tricky uses of IOError could\n\
40potentially have broken, but by Python 1.6, all of these should have\n\
41been fixed. As of Python 1.6, the class-based standard exceptions are\n\
42now implemented in C, and are guaranteed to exist in the Python\n\
43interpreter.\n\
44\n\
45Here is a rundown of the class hierarchy. The classes found here are\n\
46inserted into both the exceptions module and the `built-in' module. It is\n\
47recommended that user defined class based exceptions be derived from the\n\
Tim Petersbf26e072000-07-12 04:02:10 +000048`Exception' class, although this is currently not enforced.\n"
49 /* keep string pieces "small" */
50"\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000051Exception\n\
52 |\n\
53 +-- SystemExit\n\
54 +-- StandardError\n\
55 |\n\
56 +-- KeyboardInterrupt\n\
57 +-- ImportError\n\
58 +-- EnvironmentError\n\
59 | |\n\
60 | +-- IOError\n\
61 | +-- OSError\n\
62 | |\n\
63 | +-- WindowsError\n\
64 |\n\
65 +-- EOFError\n\
66 +-- RuntimeError\n\
67 | |\n\
68 | +-- NotImplementedError\n\
69 |\n\
70 +-- NameError\n\
71 | |\n\
72 | +-- UnboundLocalError\n\
73 |\n\
74 +-- AttributeError\n\
75 +-- SyntaxError\n\
Fred Drake85f36392000-07-11 17:53:00 +000076 | |\n\
77 | +-- IndentationError\n\
78 | |\n\
79 | +-- TabError\n\
80 |\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000081 +-- TypeError\n\
82 +-- AssertionError\n\
83 +-- LookupError\n\
84 | |\n\
85 | +-- IndexError\n\
86 | +-- KeyError\n\
87 |\n\
88 +-- ArithmeticError\n\
89 | |\n\
90 | +-- OverflowError\n\
91 | +-- ZeroDivisionError\n\
92 | +-- FloatingPointError\n\
93 |\n\
94 +-- ValueError\n\
95 | |\n\
96 | +-- UnicodeError\n\
97 |\n\
98 +-- SystemError\n\
99 +-- MemoryError";
100
101
102/* Helper function for populating a dictionary with method wrappers. */
103static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000104populate_methods(PyObject *klass, PyObject *dict, PyMethodDef *methods)
Barry Warsaw675ac282000-05-26 19:05:16 +0000105{
106 if (!methods)
107 return 0;
108
109 while (methods->ml_name) {
110 /* get a wrapper for the built-in function */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000111 PyObject *func = PyCFunction_New(methods, NULL);
112 PyObject *meth;
Barry Warsaw675ac282000-05-26 19:05:16 +0000113 int status;
114
115 if (!func)
116 return -1;
117
118 /* turn the function into an unbound method */
119 if (!(meth = PyMethod_New(func, NULL, klass))) {
120 Py_DECREF(func);
121 return -1;
122 }
123
124 /* add method to dictionary */
125 status = PyDict_SetItemString(dict, methods->ml_name, meth);
126 Py_DECREF(meth);
127 Py_DECREF(func);
128
129 /* stop now if an error occurred, otherwise do the next method */
130 if (status)
131 return status;
132
133 methods++;
134 }
135 return 0;
136}
137
138
139
140/* This function is used to create all subsequent exception classes. */
141static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000142make_class(PyObject **klass, PyObject *base,
143 char *name, PyMethodDef *methods,
144 char *docstr)
Barry Warsaw675ac282000-05-26 19:05:16 +0000145{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000146 PyObject *dict = PyDict_New();
147 PyObject *str = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000148 int status = -1;
149
150 if (!dict)
151 return -1;
152
153 /* If an error occurs from here on, goto finally instead of explicitly
154 * returning NULL.
155 */
156
157 if (docstr) {
158 if (!(str = PyString_FromString(docstr)))
159 goto finally;
160 if (PyDict_SetItemString(dict, "__doc__", str))
161 goto finally;
162 }
163
164 if (!(*klass = PyErr_NewException(name, base, dict)))
165 goto finally;
166
167 if (populate_methods(*klass, dict, methods)) {
168 Py_DECREF(*klass);
169 *klass = NULL;
170 }
171
172 status = 0;
173
174 finally:
175 Py_XDECREF(dict);
176 Py_XDECREF(str);
177 return status;
178}
179
180
181/* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000182static PyObject *
183get_self(PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000184{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000185 PyObject *self = PyTuple_GetItem(args, 0);
Barry Warsaw675ac282000-05-26 19:05:16 +0000186 if (!self) {
Thomas Wouters7e474022000-07-16 12:04:32 +0000187 /* Watch out for being called to early in the bootstrapping process */
Barry Warsaw675ac282000-05-26 19:05:16 +0000188 if (PyExc_TypeError) {
189 PyErr_SetString(PyExc_TypeError,
190 "unbound method must be called with class instance 1st argument");
191 }
192 return NULL;
193 }
194 return self;
195}
196
197
198
199/* Notes on bootstrapping the exception classes.
200 *
201 * First thing we create is the base class for all exceptions, called
202 * appropriately enough: Exception. Creation of this class makes no
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000203 * assumptions about the existence of any other exception class -- except
Barry Warsaw675ac282000-05-26 19:05:16 +0000204 * for TypeError, which can conditionally exist.
205 *
206 * Next, StandardError is created (which is quite simple) followed by
207 * TypeError, because the instantiation of other exceptions can potentially
208 * throw a TypeError. Once these exceptions are created, all the others
209 * can be created in any order. See the static exctable below for the
210 * explicit bootstrap order.
211 *
212 * All classes after Exception can be created using PyErr_NewException().
213 */
214
215static char
216Exception__doc__[] = "Common base class for all exceptions.";
217
218
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000219static PyObject *
220Exception__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000221{
222 int status;
223
224 if (!(self = get_self(args)))
225 return NULL;
226
227 /* set args attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000228 /* XXX size is only a hint */
229 args = PySequence_GetSlice(args, 1, PySequence_Size(args));
Barry Warsaw675ac282000-05-26 19:05:16 +0000230 if (!args)
231 return NULL;
232 status = PyObject_SetAttrString(self, "args", args);
233 Py_DECREF(args);
234 if (status < 0)
235 return NULL;
236
237 Py_INCREF(Py_None);
238 return Py_None;
239}
240
241
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000242static PyObject *
243Exception__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000244{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000245 PyObject *out;
Barry Warsaw675ac282000-05-26 19:05:16 +0000246
247 if (!PyArg_ParseTuple(args, "O", &self))
248 return NULL;
249
250 args = PyObject_GetAttrString(self, "args");
251 if (!args)
252 return NULL;
253
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000254 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000255 case 0:
256 out = PyString_FromString("");
257 break;
258 case 1:
Barry Warsawb7816552000-07-09 22:27:10 +0000259 {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000260 PyObject *tmp = PySequence_GetItem(args, 0);
Barry Warsawb7816552000-07-09 22:27:10 +0000261 if (tmp) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000262 out = PyObject_Str(tmp);
Barry Warsawb7816552000-07-09 22:27:10 +0000263 Py_DECREF(tmp);
264 }
265 else
266 out = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000267 break;
Barry Warsawb7816552000-07-09 22:27:10 +0000268 }
Barry Warsaw675ac282000-05-26 19:05:16 +0000269 default:
270 out = PyObject_Str(args);
271 break;
272 }
273
274 Py_DECREF(args);
275 return out;
276}
277
278
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000279static PyObject *
280Exception__getitem__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000281{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000282 PyObject *out;
283 PyObject *index;
Barry Warsaw675ac282000-05-26 19:05:16 +0000284
285 if (!PyArg_ParseTuple(args, "OO", &self, &index))
286 return NULL;
287
288 args = PyObject_GetAttrString(self, "args");
289 if (!args)
290 return NULL;
291
292 out = PyObject_GetItem(args, index);
293 Py_DECREF(args);
294 return out;
295}
296
297
298static PyMethodDef
299Exception_methods[] = {
300 /* methods for the Exception class */
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000301 { "__getitem__", Exception__getitem__, METH_VARARGS},
302 { "__str__", Exception__str__, METH_VARARGS},
303 { "__init__", Exception__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000304 { NULL, NULL }
305};
306
307
308static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000309make_Exception(char *modulename)
Barry Warsaw675ac282000-05-26 19:05:16 +0000310{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000311 PyObject *dict = PyDict_New();
312 PyObject *str = NULL;
313 PyObject *name = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000314 int status = -1;
315
316 if (!dict)
317 return -1;
318
319 /* If an error occurs from here on, goto finally instead of explicitly
320 * returning NULL.
321 */
322
323 if (!(str = PyString_FromString(modulename)))
324 goto finally;
325 if (PyDict_SetItemString(dict, "__module__", str))
326 goto finally;
327 Py_DECREF(str);
328 if (!(str = PyString_FromString(Exception__doc__)))
329 goto finally;
330 if (PyDict_SetItemString(dict, "__doc__", str))
331 goto finally;
332
333 if (!(name = PyString_FromString("Exception")))
334 goto finally;
335
336 if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
337 goto finally;
338
339 /* Now populate the dictionary with the method suite */
340 if (populate_methods(PyExc_Exception, dict, Exception_methods))
341 /* Don't need to reclaim PyExc_Exception here because that'll
342 * happen during interpreter shutdown.
343 */
344 goto finally;
345
346 status = 0;
347
348 finally:
349 Py_XDECREF(dict);
350 Py_XDECREF(str);
351 Py_XDECREF(name);
352 return status;
353}
354
355
356
357static char
358StandardError__doc__[] = "Base class for all standard Python exceptions.";
359
360static char
361TypeError__doc__[] = "Inappropriate argument type.";
362
363
364
365static char
366SystemExit__doc__[] = "Request to exit from the interpreter.";
367
368
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000369static PyObject *
370SystemExit__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000371{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000372 PyObject *code;
Barry Warsaw675ac282000-05-26 19:05:16 +0000373 int status;
374
375 if (!(self = get_self(args)))
376 return NULL;
377
378 /* Set args attribute. */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000379 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000380 return NULL;
381
382 status = PyObject_SetAttrString(self, "args", args);
383 if (status < 0) {
384 Py_DECREF(args);
385 return NULL;
386 }
387
388 /* set code attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000389 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000390 case 0:
391 Py_INCREF(Py_None);
392 code = Py_None;
393 break;
394 case 1:
395 code = PySequence_GetItem(args, 0);
396 break;
397 default:
398 Py_INCREF(args);
399 code = args;
400 break;
401 }
402
403 status = PyObject_SetAttrString(self, "code", code);
404 Py_DECREF(code);
405 Py_DECREF(args);
406 if (status < 0)
407 return NULL;
408
409 Py_INCREF(Py_None);
410 return Py_None;
411}
412
413
414PyMethodDef SystemExit_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000415 { "__init__", SystemExit__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000416 {NULL, NULL}
417};
418
419
420
421static char
422KeyboardInterrupt__doc__[] = "Program interrupted by user.";
423
424static char
425ImportError__doc__[] =
426"Import can't find module, or can't find name in module.";
427
428
429
430static char
431EnvironmentError__doc__[] = "Base class for I/O related errors.";
432
433
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000434static PyObject *
435EnvironmentError__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000436{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000437 PyObject *item0 = NULL;
438 PyObject *item1 = NULL;
439 PyObject *item2 = NULL;
440 PyObject *subslice = NULL;
441 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000442
443 if (!(self = get_self(args)))
444 return NULL;
445
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000446 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000447 return NULL;
448
449 if (PyObject_SetAttrString(self, "args", args) ||
450 PyObject_SetAttrString(self, "errno", Py_None) ||
451 PyObject_SetAttrString(self, "strerror", Py_None) ||
452 PyObject_SetAttrString(self, "filename", Py_None))
453 {
454 goto finally;
455 }
456
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000457 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000458 case 3:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000459 /* Where a function has a single filename, such as open() or some
460 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
461 * called, giving a third argument which is the filename. But, so
462 * that old code using in-place unpacking doesn't break, e.g.:
Barry Warsaw675ac282000-05-26 19:05:16 +0000463 *
464 * except IOError, (errno, strerror):
465 *
466 * we hack args so that it only contains two items. This also
467 * means we need our own __str__() which prints out the filename
468 * when it was supplied.
469 */
470 item0 = PySequence_GetItem(args, 0);
471 item1 = PySequence_GetItem(args, 1);
472 item2 = PySequence_GetItem(args, 2);
473 if (!item0 || !item1 || !item2)
474 goto finally;
475
476 if (PyObject_SetAttrString(self, "errno", item0) ||
477 PyObject_SetAttrString(self, "strerror", item1) ||
478 PyObject_SetAttrString(self, "filename", item2))
479 {
480 goto finally;
481 }
482
483 subslice = PySequence_GetSlice(args, 0, 2);
484 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
485 goto finally;
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000486 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000487
488 case 2:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000489 /* Used when PyErr_SetFromErrno() is called and no filename
490 * argument is given.
491 */
Barry Warsaw675ac282000-05-26 19:05:16 +0000492 item0 = PySequence_GetItem(args, 0);
493 item1 = PySequence_GetItem(args, 1);
494 if (!item0 || !item1)
495 goto finally;
496
497 if (PyObject_SetAttrString(self, "errno", item0) ||
498 PyObject_SetAttrString(self, "strerror", item1))
499 {
500 goto finally;
501 }
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000502 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000503 }
504
505 Py_INCREF(Py_None);
506 rtnval = Py_None;
507
508 finally:
509 Py_DECREF(args);
510 Py_XDECREF(item0);
511 Py_XDECREF(item1);
512 Py_XDECREF(item2);
513 Py_XDECREF(subslice);
514 return rtnval;
515}
516
517
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000518static PyObject *
519EnvironmentError__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000520{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000521 PyObject *originalself = self;
522 PyObject *filename;
523 PyObject *serrno;
524 PyObject *strerror;
525 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000526
527 if (!PyArg_ParseTuple(args, "O", &self))
528 return NULL;
529
530 filename = PyObject_GetAttrString(self, "filename");
531 serrno = PyObject_GetAttrString(self, "errno");
532 strerror = PyObject_GetAttrString(self, "strerror");
533 if (!filename || !serrno || !strerror)
534 goto finally;
535
536 if (filename != Py_None) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000537 PyObject *fmt = PyString_FromString("[Errno %s] %s: %s");
538 PyObject *repr = PyObject_Repr(filename);
539 PyObject *tuple = PyTuple_New(3);
Barry Warsaw675ac282000-05-26 19:05:16 +0000540
541 if (!fmt || !repr || !tuple) {
542 Py_XDECREF(fmt);
543 Py_XDECREF(repr);
544 Py_XDECREF(tuple);
545 goto finally;
546 }
547
548 PyTuple_SET_ITEM(tuple, 0, serrno);
549 PyTuple_SET_ITEM(tuple, 1, strerror);
550 PyTuple_SET_ITEM(tuple, 2, repr);
551
552 rtnval = PyString_Format(fmt, tuple);
553
554 Py_DECREF(fmt);
555 Py_DECREF(tuple);
556 /* already freed because tuple owned only reference */
557 serrno = NULL;
558 strerror = NULL;
559 }
560 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000561 PyObject *fmt = PyString_FromString("[Errno %s] %s");
562 PyObject *tuple = PyTuple_New(2);
Barry Warsaw675ac282000-05-26 19:05:16 +0000563
564 if (!fmt || !tuple) {
565 Py_XDECREF(fmt);
566 Py_XDECREF(tuple);
567 goto finally;
568 }
569
570 PyTuple_SET_ITEM(tuple, 0, serrno);
571 PyTuple_SET_ITEM(tuple, 1, strerror);
572
573 rtnval = PyString_Format(fmt, tuple);
574
575 Py_DECREF(fmt);
576 Py_DECREF(tuple);
577 /* already freed because tuple owned only reference */
578 serrno = NULL;
579 strerror = NULL;
580 }
581 else
582 /* The original Python code said:
583 *
584 * return StandardError.__str__(self)
585 *
586 * but there is no StandardError__str__() function; we happen to
587 * know that's just a pass through to Exception__str__().
588 */
589 rtnval = Exception__str__(originalself, args);
590
591 finally:
592 Py_XDECREF(filename);
593 Py_XDECREF(serrno);
594 Py_XDECREF(strerror);
595 return rtnval;
596}
597
598
599static
600PyMethodDef EnvironmentError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000601 {"__init__", EnvironmentError__init__, METH_VARARGS},
602 {"__str__", EnvironmentError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000603 {NULL, NULL}
604};
605
606
607
608
609static char
610IOError__doc__[] = "I/O operation failed.";
611
612static char
613OSError__doc__[] = "OS system call failed.";
614
615#ifdef MS_WINDOWS
616static char
617WindowsError__doc__[] = "MS-Windows OS system call failed.";
618#endif /* MS_WINDOWS */
619
620static char
621EOFError__doc__[] = "Read beyond end of file.";
622
623static char
624RuntimeError__doc__[] = "Unspecified run-time error.";
625
626static char
627NotImplementedError__doc__[] =
628"Method or function hasn't been implemented yet.";
629
630static char
631NameError__doc__[] = "Name not found globally.";
632
633static char
634UnboundLocalError__doc__[] =
635"Local name referenced but not bound to a value.";
636
637static char
638AttributeError__doc__[] = "Attribute not found.";
639
640
641
642static char
643SyntaxError__doc__[] = "Invalid syntax.";
644
645
646static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000647SyntaxError__classinit__(PyObject *klass)
Barry Warsaw675ac282000-05-26 19:05:16 +0000648{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000649 PyObject *emptystring = PyString_FromString("");
Barry Warsaw675ac282000-05-26 19:05:16 +0000650
651 /* Additional class-creation time initializations */
652 if (!emptystring ||
653 PyObject_SetAttrString(klass, "msg", emptystring) ||
654 PyObject_SetAttrString(klass, "filename", Py_None) ||
655 PyObject_SetAttrString(klass, "lineno", Py_None) ||
656 PyObject_SetAttrString(klass, "offset", Py_None) ||
657 PyObject_SetAttrString(klass, "text", Py_None))
658 {
659 Py_XDECREF(emptystring);
660 return -1;
661 }
662 Py_DECREF(emptystring);
663 return 0;
664}
665
666
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000667static PyObject *
668SyntaxError__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000669{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000670 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000671 int lenargs;
672
673 if (!(self = get_self(args)))
674 return NULL;
675
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000676 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000677 return NULL;
678
679 if (PyObject_SetAttrString(self, "args", args))
680 goto finally;
681
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000682 lenargs = PySequence_Size(args);
Barry Warsaw675ac282000-05-26 19:05:16 +0000683 if (lenargs >= 1) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000684 PyObject *item0 = PySequence_GetItem(args, 0);
Barry Warsaw675ac282000-05-26 19:05:16 +0000685 int status;
686
687 if (!item0)
688 goto finally;
689 status = PyObject_SetAttrString(self, "msg", item0);
690 Py_DECREF(item0);
691 if (status)
692 goto finally;
693 }
694 if (lenargs == 2) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000695 PyObject *info = PySequence_GetItem(args, 1);
Barry Warsaw675ac282000-05-26 19:05:16 +0000696 PyObject *filename, *lineno, *offset, *text;
697 int status = 1;
698
699 if (!info)
700 goto finally;
701
702 filename = PySequence_GetItem(info, 0);
703 lineno = PySequence_GetItem(info, 1);
704 offset = PySequence_GetItem(info, 2);
705 text = PySequence_GetItem(info, 3);
706
707 Py_DECREF(info);
708
709 if (filename && lineno && offset && text) {
710 status = PyObject_SetAttrString(self, "filename", filename) ||
711 PyObject_SetAttrString(self, "lineno", lineno) ||
712 PyObject_SetAttrString(self, "offset", offset) ||
713 PyObject_SetAttrString(self, "text", text);
714 }
715 Py_XDECREF(filename);
716 Py_XDECREF(lineno);
717 Py_XDECREF(offset);
718 Py_XDECREF(text);
719
720 if (status)
721 goto finally;
722 }
723 Py_INCREF(Py_None);
724 rtnval = Py_None;
725
726 finally:
727 Py_DECREF(args);
728 return rtnval;
729}
730
731
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000732static PyObject *
733SyntaxError__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000734{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000735 PyObject *msg;
736 PyObject *str;
Barry Warsaw675ac282000-05-26 19:05:16 +0000737
738 if (!PyArg_ParseTuple(args, "O", &self))
739 return NULL;
740
741 if (!(msg = PyObject_GetAttrString(self, "msg")))
742 return NULL;
743
744 str = PyObject_Str(msg);
745 Py_DECREF(msg);
746 return str;
747}
748
749
750PyMethodDef SyntaxError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000751 {"__init__", SyntaxError__init__, METH_VARARGS},
752 {"__str__", SyntaxError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000753 {NULL, NULL}
754};
755
756
757
758static char
759AssertionError__doc__[] = "Assertion failed.";
760
761static char
762LookupError__doc__[] = "Base class for lookup errors.";
763
764static char
765IndexError__doc__[] = "Sequence index out of range.";
766
767static char
768KeyError__doc__[] = "Mapping key not found.";
769
770static char
771ArithmeticError__doc__[] = "Base class for arithmetic errors.";
772
773static char
774OverflowError__doc__[] = "Result too large to be represented.";
775
776static char
777ZeroDivisionError__doc__[] =
778"Second argument to a division or modulo operation was zero.";
779
780static char
781FloatingPointError__doc__[] = "Floating point operation failed.";
782
783static char
784ValueError__doc__[] = "Inappropriate argument value (of correct type).";
785
786static char
787UnicodeError__doc__[] = "Unicode related error.";
788
789static char
790SystemError__doc__[] = "Internal error in the Python interpreter.\n\
791\n\
792Please report this to the Python maintainer, along with the traceback,\n\
793the Python version, and the hardware/OS platform and version.";
794
795static char
796MemoryError__doc__[] = "Out of memory.";
797
Fred Drake85f36392000-07-11 17:53:00 +0000798static char
799IndentationError__doc__[] = "Improper indentation.";
800
801static char
802TabError__doc__[] = "Improper mixture of spaces and tabs.";
803
Barry Warsaw675ac282000-05-26 19:05:16 +0000804
805
806/* module global functions */
807static PyMethodDef functions[] = {
808 /* Sentinel */
809 {NULL, NULL}
810};
811
812
813
814/* Global C API defined exceptions */
815
816PyObject *PyExc_Exception;
817PyObject *PyExc_StandardError;
818PyObject *PyExc_ArithmeticError;
819PyObject *PyExc_LookupError;
820
821PyObject *PyExc_AssertionError;
822PyObject *PyExc_AttributeError;
823PyObject *PyExc_EOFError;
824PyObject *PyExc_FloatingPointError;
825PyObject *PyExc_EnvironmentError;
826PyObject *PyExc_IOError;
827PyObject *PyExc_OSError;
828PyObject *PyExc_ImportError;
829PyObject *PyExc_IndexError;
830PyObject *PyExc_KeyError;
831PyObject *PyExc_KeyboardInterrupt;
832PyObject *PyExc_MemoryError;
833PyObject *PyExc_NameError;
834PyObject *PyExc_OverflowError;
835PyObject *PyExc_RuntimeError;
836PyObject *PyExc_NotImplementedError;
837PyObject *PyExc_SyntaxError;
Fred Drake85f36392000-07-11 17:53:00 +0000838PyObject *PyExc_IndentationError;
839PyObject *PyExc_TabError;
Barry Warsaw675ac282000-05-26 19:05:16 +0000840PyObject *PyExc_SystemError;
841PyObject *PyExc_SystemExit;
842PyObject *PyExc_UnboundLocalError;
843PyObject *PyExc_UnicodeError;
844PyObject *PyExc_TypeError;
845PyObject *PyExc_ValueError;
846PyObject *PyExc_ZeroDivisionError;
847#ifdef MS_WINDOWS
848PyObject *PyExc_WindowsError;
849#endif
850
851/* Pre-computed MemoryError instance. Best to create this as early as
852 * possibly and not wait until a MemoryError is actually raised!
853 */
854PyObject *PyExc_MemoryErrorInst;
855
856
857
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000858/* mapping between exception names and their PyObject ** */
859static struct {
860 char *name;
861 PyObject **exc;
862 PyObject **base; /* NULL == PyExc_StandardError */
863 char *docstr;
864 PyMethodDef *methods;
865 int (*classinit)(PyObject *);
866} exctable[] = {
Barry Warsaw675ac282000-05-26 19:05:16 +0000867 /*
868 * The first three classes MUST appear in exactly this order
869 */
870 {"Exception", &PyExc_Exception},
871 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
872 StandardError__doc__},
873 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
874 /*
875 * The rest appear in depth-first order of the hierarchy
876 */
877 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
878 SystemExit_methods},
879 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
880 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
881 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
882 EnvironmentError_methods},
883 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
884 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
885#ifdef MS_WINDOWS
Mark Hammond557a0442000-08-15 00:37:32 +0000886 {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
Barry Warsaw675ac282000-05-26 19:05:16 +0000887 WindowsError__doc__},
888#endif /* MS_WINDOWS */
889 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
890 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
891 {"NotImplementedError", &PyExc_NotImplementedError,
892 &PyExc_RuntimeError, NotImplementedError__doc__},
893 {"NameError", &PyExc_NameError, 0, NameError__doc__},
894 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
895 UnboundLocalError__doc__},
896 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
897 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
898 SyntaxError_methods, SyntaxError__classinit__},
Fred Drake85f36392000-07-11 17:53:00 +0000899 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
900 IndentationError__doc__},
901 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
902 TabError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +0000903 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
904 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
905 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
906 IndexError__doc__},
907 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
908 KeyError__doc__},
909 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
910 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
911 OverflowError__doc__},
912 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
913 ZeroDivisionError__doc__},
914 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
915 FloatingPointError__doc__},
916 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
917 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
918 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
919 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
920 /* Sentinel */
921 {NULL}
922};
923
924
925
926void
927#ifdef WIN32
928__declspec(dllexport)
929#endif /* WIN32 */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000930init_exceptions(void)
Barry Warsaw675ac282000-05-26 19:05:16 +0000931{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000932 char *modulename = "exceptions";
Barry Warsaw675ac282000-05-26 19:05:16 +0000933 int modnamesz = strlen(modulename);
934 int i;
935
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000936 PyObject *me = Py_InitModule(modulename, functions);
937 PyObject *mydict = PyModule_GetDict(me);
938 PyObject *bltinmod = PyImport_ImportModule("__builtin__");
939 PyObject *bdict = PyModule_GetDict(bltinmod);
940 PyObject *doc = PyString_FromString(module__doc__);
941 PyObject *args;
Barry Warsaw675ac282000-05-26 19:05:16 +0000942
943 PyDict_SetItemString(mydict, "__doc__", doc);
Barry Warsaw8fcaa922000-07-01 04:45:52 +0000944 Py_DECREF(doc);
Barry Warsaw675ac282000-05-26 19:05:16 +0000945 if (PyErr_Occurred())
946 Py_FatalError("exceptions bootstrapping error.");
947
948 /* This is the base class of all exceptions, so make it first. */
949 if (make_Exception(modulename) ||
950 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
951 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
952 {
953 Py_FatalError("Base class `Exception' could not be created.");
954 }
955
956 /* Now we can programmatically create all the remaining exceptions.
957 * Remember to start the loop at 1 to skip Exceptions.
958 */
959 for (i=1; exctable[i].name; i++) {
960 int status;
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000961 char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
962 PyObject *base;
Barry Warsaw675ac282000-05-26 19:05:16 +0000963
964 (void)strcpy(cname, modulename);
965 (void)strcat(cname, ".");
966 (void)strcat(cname, exctable[i].name);
967
968 if (exctable[i].base == 0)
969 base = PyExc_StandardError;
970 else
971 base = *exctable[i].base;
972
973 status = make_class(exctable[i].exc, base, cname,
974 exctable[i].methods,
975 exctable[i].docstr);
976
977 PyMem_DEL(cname);
978
979 if (status)
980 Py_FatalError("Standard exception classes could not be created.");
981
982 if (exctable[i].classinit) {
983 status = (*exctable[i].classinit)(*exctable[i].exc);
984 if (status)
985 Py_FatalError("An exception class could not be initialized.");
986 }
987
988 /* Now insert the class into both this module and the __builtin__
989 * module.
990 */
991 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
992 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
993 {
994 Py_FatalError("Module dictionary insertion problem.");
995 }
996 }
997
998 /* Now we need to pre-allocate a MemoryError instance */
999 args = Py_BuildValue("()");
1000 if (!args ||
1001 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1002 {
1003 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1004 }
1005 Py_DECREF(args);
1006
1007 /* We're done with __builtin__ */
1008 Py_DECREF(bltinmod);
1009}
1010
1011
1012void
1013#ifdef WIN32
1014__declspec(dllexport)
1015#endif /* WIN32 */
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001016fini_exceptions(void)
Barry Warsaw675ac282000-05-26 19:05:16 +00001017{
1018 int i;
1019
1020 Py_XDECREF(PyExc_MemoryErrorInst);
1021 PyExc_MemoryErrorInst = NULL;
1022
1023 for (i=0; exctable[i].name; i++) {
1024 Py_XDECREF(*exctable[i].exc);
1025 *exctable[i].exc = NULL;
1026 }
1027}