blob: abacda4d995fa61cf47f0c26650fed0f502b3f70 [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 */
Barry Warsaw675ac282000-05-26 19:05:16 +000028static char
29module__doc__[] =
30"Python's standard exception class hierarchy.\n\
31\n\
32Before Python 1.5, the standard exceptions were all simple string objects.\n\
33In Python 1.5, the standard exceptions were converted to classes organized\n\
34into a relatively flat hierarchy. String-based standard exceptions were\n\
35optional, or used as a fallback if some problem occurred while importing\n\
36the exception module. With Python 1.6, optional string-based standard\n\
37exceptions were removed (along with the -X command line flag).\n\
38\n\
39The class exceptions were implemented in such a way as to be almost\n\
40completely backward compatible. Some tricky uses of IOError could\n\
41potentially have broken, but by Python 1.6, all of these should have\n\
42been fixed. As of Python 1.6, the class-based standard exceptions are\n\
43now implemented in C, and are guaranteed to exist in the Python\n\
44interpreter.\n\
45\n\
46Here is a rundown of the class hierarchy. The classes found here are\n\
47inserted into both the exceptions module and the `built-in' module. It is\n\
48recommended that user defined class based exceptions be derived from the\n\
Tim Petersbf26e072000-07-12 04:02:10 +000049`Exception' class, although this is currently not enforced.\n"
50 /* keep string pieces "small" */
51"\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000052Exception\n\
53 |\n\
54 +-- SystemExit\n\
55 +-- StandardError\n\
56 |\n\
57 +-- KeyboardInterrupt\n\
58 +-- ImportError\n\
59 +-- EnvironmentError\n\
60 | |\n\
61 | +-- IOError\n\
62 | +-- OSError\n\
63 | |\n\
64 | +-- WindowsError\n\
65 |\n\
66 +-- EOFError\n\
67 +-- RuntimeError\n\
68 | |\n\
69 | +-- NotImplementedError\n\
70 |\n\
71 +-- NameError\n\
72 | |\n\
73 | +-- UnboundLocalError\n\
74 |\n\
75 +-- AttributeError\n\
76 +-- SyntaxError\n\
Fred Drake85f36392000-07-11 17:53:00 +000077 | |\n\
78 | +-- IndentationError\n\
79 | |\n\
80 | +-- TabError\n\
81 |\n\
Barry Warsaw675ac282000-05-26 19:05:16 +000082 +-- TypeError\n\
83 +-- AssertionError\n\
84 +-- LookupError\n\
85 | |\n\
86 | +-- IndexError\n\
87 | +-- KeyError\n\
88 |\n\
89 +-- ArithmeticError\n\
90 | |\n\
91 | +-- OverflowError\n\
92 | +-- ZeroDivisionError\n\
93 | +-- FloatingPointError\n\
94 |\n\
95 +-- ValueError\n\
96 | |\n\
97 | +-- UnicodeError\n\
98 |\n\
99 +-- SystemError\n\
100 +-- MemoryError";
101
102
103/* Helper function for populating a dictionary with method wrappers. */
104static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000105populate_methods(PyObject *klass, PyObject *dict, PyMethodDef *methods)
Barry Warsaw675ac282000-05-26 19:05:16 +0000106{
107 if (!methods)
108 return 0;
109
110 while (methods->ml_name) {
111 /* get a wrapper for the built-in function */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000112 PyObject *func = PyCFunction_New(methods, NULL);
113 PyObject *meth;
Barry Warsaw675ac282000-05-26 19:05:16 +0000114 int status;
115
116 if (!func)
117 return -1;
118
119 /* turn the function into an unbound method */
120 if (!(meth = PyMethod_New(func, NULL, klass))) {
121 Py_DECREF(func);
122 return -1;
123 }
124
125 /* add method to dictionary */
126 status = PyDict_SetItemString(dict, methods->ml_name, meth);
127 Py_DECREF(meth);
128 Py_DECREF(func);
129
130 /* stop now if an error occurred, otherwise do the next method */
131 if (status)
132 return status;
133
134 methods++;
135 }
136 return 0;
137}
138
139
140
141/* This function is used to create all subsequent exception classes. */
142static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000143make_class(PyObject **klass, PyObject *base,
144 char *name, PyMethodDef *methods,
145 char *docstr)
Barry Warsaw675ac282000-05-26 19:05:16 +0000146{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000147 PyObject *dict = PyDict_New();
148 PyObject *str = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000149 int status = -1;
150
151 if (!dict)
152 return -1;
153
154 /* If an error occurs from here on, goto finally instead of explicitly
155 * returning NULL.
156 */
157
158 if (docstr) {
159 if (!(str = PyString_FromString(docstr)))
160 goto finally;
161 if (PyDict_SetItemString(dict, "__doc__", str))
162 goto finally;
163 }
164
165 if (!(*klass = PyErr_NewException(name, base, dict)))
166 goto finally;
167
168 if (populate_methods(*klass, dict, methods)) {
169 Py_DECREF(*klass);
170 *klass = NULL;
171 }
172
173 status = 0;
174
175 finally:
176 Py_XDECREF(dict);
177 Py_XDECREF(str);
178 return status;
179}
180
181
182/* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000183static PyObject *
184get_self(PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000185{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000186 PyObject *self = PyTuple_GetItem(args, 0);
Barry Warsaw675ac282000-05-26 19:05:16 +0000187 if (!self) {
Thomas Wouters7e474022000-07-16 12:04:32 +0000188 /* Watch out for being called to early in the bootstrapping process */
Barry Warsaw675ac282000-05-26 19:05:16 +0000189 if (PyExc_TypeError) {
190 PyErr_SetString(PyExc_TypeError,
191 "unbound method must be called with class instance 1st argument");
192 }
193 return NULL;
194 }
195 return self;
196}
197
198
199
200/* Notes on bootstrapping the exception classes.
201 *
202 * First thing we create is the base class for all exceptions, called
203 * appropriately enough: Exception. Creation of this class makes no
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000204 * assumptions about the existence of any other exception class -- except
Barry Warsaw675ac282000-05-26 19:05:16 +0000205 * for TypeError, which can conditionally exist.
206 *
207 * Next, StandardError is created (which is quite simple) followed by
208 * TypeError, because the instantiation of other exceptions can potentially
209 * throw a TypeError. Once these exceptions are created, all the others
210 * can be created in any order. See the static exctable below for the
211 * explicit bootstrap order.
212 *
213 * All classes after Exception can be created using PyErr_NewException().
214 */
215
216static char
217Exception__doc__[] = "Common base class for all exceptions.";
218
219
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000220static PyObject *
221Exception__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000222{
223 int status;
224
225 if (!(self = get_self(args)))
226 return NULL;
227
228 /* set args attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000229 /* XXX size is only a hint */
230 args = PySequence_GetSlice(args, 1, PySequence_Size(args));
Barry Warsaw675ac282000-05-26 19:05:16 +0000231 if (!args)
232 return NULL;
233 status = PyObject_SetAttrString(self, "args", args);
234 Py_DECREF(args);
235 if (status < 0)
236 return NULL;
237
238 Py_INCREF(Py_None);
239 return Py_None;
240}
241
242
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000243static PyObject *
244Exception__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000245{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000246 PyObject *out;
Barry Warsaw675ac282000-05-26 19:05:16 +0000247
Fred Drake1aba5772000-08-15 15:46:16 +0000248 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000249 return NULL;
250
251 args = PyObject_GetAttrString(self, "args");
252 if (!args)
253 return NULL;
254
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000255 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000256 case 0:
257 out = PyString_FromString("");
258 break;
259 case 1:
Barry Warsawb7816552000-07-09 22:27:10 +0000260 {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000261 PyObject *tmp = PySequence_GetItem(args, 0);
Barry Warsawb7816552000-07-09 22:27:10 +0000262 if (tmp) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000263 out = PyObject_Str(tmp);
Barry Warsawb7816552000-07-09 22:27:10 +0000264 Py_DECREF(tmp);
265 }
266 else
267 out = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000268 break;
Barry Warsawb7816552000-07-09 22:27:10 +0000269 }
Barry Warsaw675ac282000-05-26 19:05:16 +0000270 default:
271 out = PyObject_Str(args);
272 break;
273 }
274
275 Py_DECREF(args);
276 return out;
277}
278
279
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000280static PyObject *
281Exception__getitem__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000282{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000283 PyObject *out;
284 PyObject *index;
Barry Warsaw675ac282000-05-26 19:05:16 +0000285
Fred Drake1aba5772000-08-15 15:46:16 +0000286 if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index))
Barry Warsaw675ac282000-05-26 19:05:16 +0000287 return NULL;
288
289 args = PyObject_GetAttrString(self, "args");
290 if (!args)
291 return NULL;
292
293 out = PyObject_GetItem(args, index);
294 Py_DECREF(args);
295 return out;
296}
297
298
299static PyMethodDef
300Exception_methods[] = {
301 /* methods for the Exception class */
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000302 { "__getitem__", Exception__getitem__, METH_VARARGS},
303 { "__str__", Exception__str__, METH_VARARGS},
304 { "__init__", Exception__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000305 { NULL, NULL }
306};
307
308
309static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000310make_Exception(char *modulename)
Barry Warsaw675ac282000-05-26 19:05:16 +0000311{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000312 PyObject *dict = PyDict_New();
313 PyObject *str = NULL;
314 PyObject *name = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000315 int status = -1;
316
317 if (!dict)
318 return -1;
319
320 /* If an error occurs from here on, goto finally instead of explicitly
321 * returning NULL.
322 */
323
324 if (!(str = PyString_FromString(modulename)))
325 goto finally;
326 if (PyDict_SetItemString(dict, "__module__", str))
327 goto finally;
328 Py_DECREF(str);
329 if (!(str = PyString_FromString(Exception__doc__)))
330 goto finally;
331 if (PyDict_SetItemString(dict, "__doc__", str))
332 goto finally;
333
334 if (!(name = PyString_FromString("Exception")))
335 goto finally;
336
337 if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
338 goto finally;
339
340 /* Now populate the dictionary with the method suite */
341 if (populate_methods(PyExc_Exception, dict, Exception_methods))
342 /* Don't need to reclaim PyExc_Exception here because that'll
343 * happen during interpreter shutdown.
344 */
345 goto finally;
346
347 status = 0;
348
349 finally:
350 Py_XDECREF(dict);
351 Py_XDECREF(str);
352 Py_XDECREF(name);
353 return status;
354}
355
356
357
358static char
359StandardError__doc__[] = "Base class for all standard Python exceptions.";
360
361static char
362TypeError__doc__[] = "Inappropriate argument type.";
363
364
365
366static char
367SystemExit__doc__[] = "Request to exit from the interpreter.";
368
369
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000370static PyObject *
371SystemExit__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000372{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000373 PyObject *code;
Barry Warsaw675ac282000-05-26 19:05:16 +0000374 int status;
375
376 if (!(self = get_self(args)))
377 return NULL;
378
379 /* Set args attribute. */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000380 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000381 return NULL;
382
383 status = PyObject_SetAttrString(self, "args", args);
384 if (status < 0) {
385 Py_DECREF(args);
386 return NULL;
387 }
388
389 /* set code attribute */
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000390 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000391 case 0:
392 Py_INCREF(Py_None);
393 code = Py_None;
394 break;
395 case 1:
396 code = PySequence_GetItem(args, 0);
397 break;
398 default:
399 Py_INCREF(args);
400 code = args;
401 break;
402 }
403
404 status = PyObject_SetAttrString(self, "code", code);
405 Py_DECREF(code);
406 Py_DECREF(args);
407 if (status < 0)
408 return NULL;
409
410 Py_INCREF(Py_None);
411 return Py_None;
412}
413
414
415PyMethodDef SystemExit_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000416 { "__init__", SystemExit__init__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000417 {NULL, NULL}
418};
419
420
421
422static char
423KeyboardInterrupt__doc__[] = "Program interrupted by user.";
424
425static char
426ImportError__doc__[] =
427"Import can't find module, or can't find name in module.";
428
429
430
431static char
432EnvironmentError__doc__[] = "Base class for I/O related errors.";
433
434
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000435static PyObject *
436EnvironmentError__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000437{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000438 PyObject *item0 = NULL;
439 PyObject *item1 = NULL;
440 PyObject *item2 = NULL;
441 PyObject *subslice = NULL;
442 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000443
444 if (!(self = get_self(args)))
445 return NULL;
446
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000447 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000448 return NULL;
449
450 if (PyObject_SetAttrString(self, "args", args) ||
451 PyObject_SetAttrString(self, "errno", Py_None) ||
452 PyObject_SetAttrString(self, "strerror", Py_None) ||
453 PyObject_SetAttrString(self, "filename", Py_None))
454 {
455 goto finally;
456 }
457
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000458 switch (PySequence_Size(args)) {
Barry Warsaw675ac282000-05-26 19:05:16 +0000459 case 3:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000460 /* Where a function has a single filename, such as open() or some
461 * of the os module functions, PyErr_SetFromErrnoWithFilename() is
462 * called, giving a third argument which is the filename. But, so
463 * that old code using in-place unpacking doesn't break, e.g.:
Barry Warsaw675ac282000-05-26 19:05:16 +0000464 *
465 * except IOError, (errno, strerror):
466 *
467 * we hack args so that it only contains two items. This also
468 * means we need our own __str__() which prints out the filename
469 * when it was supplied.
470 */
471 item0 = PySequence_GetItem(args, 0);
472 item1 = PySequence_GetItem(args, 1);
473 item2 = PySequence_GetItem(args, 2);
474 if (!item0 || !item1 || !item2)
475 goto finally;
476
477 if (PyObject_SetAttrString(self, "errno", item0) ||
478 PyObject_SetAttrString(self, "strerror", item1) ||
479 PyObject_SetAttrString(self, "filename", item2))
480 {
481 goto finally;
482 }
483
484 subslice = PySequence_GetSlice(args, 0, 2);
485 if (!subslice || PyObject_SetAttrString(self, "args", subslice))
486 goto finally;
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000487 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000488
489 case 2:
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000490 /* Used when PyErr_SetFromErrno() is called and no filename
491 * argument is given.
492 */
Barry Warsaw675ac282000-05-26 19:05:16 +0000493 item0 = PySequence_GetItem(args, 0);
494 item1 = PySequence_GetItem(args, 1);
495 if (!item0 || !item1)
496 goto finally;
497
498 if (PyObject_SetAttrString(self, "errno", item0) ||
499 PyObject_SetAttrString(self, "strerror", item1))
500 {
501 goto finally;
502 }
Barry Warsaw7dfeb422000-07-09 04:56:25 +0000503 break;
Barry Warsaw675ac282000-05-26 19:05:16 +0000504 }
505
506 Py_INCREF(Py_None);
507 rtnval = Py_None;
508
509 finally:
510 Py_DECREF(args);
511 Py_XDECREF(item0);
512 Py_XDECREF(item1);
513 Py_XDECREF(item2);
514 Py_XDECREF(subslice);
515 return rtnval;
516}
517
518
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000519static PyObject *
520EnvironmentError__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000521{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000522 PyObject *originalself = self;
523 PyObject *filename;
524 PyObject *serrno;
525 PyObject *strerror;
526 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000527
Fred Drake1aba5772000-08-15 15:46:16 +0000528 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000529 return NULL;
530
531 filename = PyObject_GetAttrString(self, "filename");
532 serrno = PyObject_GetAttrString(self, "errno");
533 strerror = PyObject_GetAttrString(self, "strerror");
534 if (!filename || !serrno || !strerror)
535 goto finally;
536
537 if (filename != Py_None) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000538 PyObject *fmt = PyString_FromString("[Errno %s] %s: %s");
539 PyObject *repr = PyObject_Repr(filename);
540 PyObject *tuple = PyTuple_New(3);
Barry Warsaw675ac282000-05-26 19:05:16 +0000541
542 if (!fmt || !repr || !tuple) {
543 Py_XDECREF(fmt);
544 Py_XDECREF(repr);
545 Py_XDECREF(tuple);
546 goto finally;
547 }
548
549 PyTuple_SET_ITEM(tuple, 0, serrno);
550 PyTuple_SET_ITEM(tuple, 1, strerror);
551 PyTuple_SET_ITEM(tuple, 2, repr);
552
553 rtnval = PyString_Format(fmt, tuple);
554
555 Py_DECREF(fmt);
556 Py_DECREF(tuple);
557 /* already freed because tuple owned only reference */
558 serrno = NULL;
559 strerror = NULL;
560 }
561 else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000562 PyObject *fmt = PyString_FromString("[Errno %s] %s");
563 PyObject *tuple = PyTuple_New(2);
Barry Warsaw675ac282000-05-26 19:05:16 +0000564
565 if (!fmt || !tuple) {
566 Py_XDECREF(fmt);
567 Py_XDECREF(tuple);
568 goto finally;
569 }
570
571 PyTuple_SET_ITEM(tuple, 0, serrno);
572 PyTuple_SET_ITEM(tuple, 1, strerror);
573
574 rtnval = PyString_Format(fmt, tuple);
575
576 Py_DECREF(fmt);
577 Py_DECREF(tuple);
578 /* already freed because tuple owned only reference */
579 serrno = NULL;
580 strerror = NULL;
581 }
582 else
583 /* The original Python code said:
584 *
585 * return StandardError.__str__(self)
586 *
587 * but there is no StandardError__str__() function; we happen to
588 * know that's just a pass through to Exception__str__().
589 */
590 rtnval = Exception__str__(originalself, args);
591
592 finally:
593 Py_XDECREF(filename);
594 Py_XDECREF(serrno);
595 Py_XDECREF(strerror);
596 return rtnval;
597}
598
599
600static
601PyMethodDef EnvironmentError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000602 {"__init__", EnvironmentError__init__, METH_VARARGS},
603 {"__str__", EnvironmentError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000604 {NULL, NULL}
605};
606
607
608
609
610static char
611IOError__doc__[] = "I/O operation failed.";
612
613static char
614OSError__doc__[] = "OS system call failed.";
615
616#ifdef MS_WINDOWS
617static char
618WindowsError__doc__[] = "MS-Windows OS system call failed.";
619#endif /* MS_WINDOWS */
620
621static char
622EOFError__doc__[] = "Read beyond end of file.";
623
624static char
625RuntimeError__doc__[] = "Unspecified run-time error.";
626
627static char
628NotImplementedError__doc__[] =
629"Method or function hasn't been implemented yet.";
630
631static char
632NameError__doc__[] = "Name not found globally.";
633
634static char
635UnboundLocalError__doc__[] =
636"Local name referenced but not bound to a value.";
637
638static char
639AttributeError__doc__[] = "Attribute not found.";
640
641
642
643static char
644SyntaxError__doc__[] = "Invalid syntax.";
645
646
647static int
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000648SyntaxError__classinit__(PyObject *klass)
Barry Warsaw675ac282000-05-26 19:05:16 +0000649{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000650 PyObject *emptystring = PyString_FromString("");
Barry Warsaw675ac282000-05-26 19:05:16 +0000651
652 /* Additional class-creation time initializations */
653 if (!emptystring ||
654 PyObject_SetAttrString(klass, "msg", emptystring) ||
655 PyObject_SetAttrString(klass, "filename", Py_None) ||
656 PyObject_SetAttrString(klass, "lineno", Py_None) ||
657 PyObject_SetAttrString(klass, "offset", Py_None) ||
658 PyObject_SetAttrString(klass, "text", Py_None))
659 {
660 Py_XDECREF(emptystring);
661 return -1;
662 }
663 Py_DECREF(emptystring);
664 return 0;
665}
666
667
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000668static PyObject *
669SyntaxError__init__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000670{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000671 PyObject *rtnval = NULL;
Barry Warsaw675ac282000-05-26 19:05:16 +0000672 int lenargs;
673
674 if (!(self = get_self(args)))
675 return NULL;
676
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000677 if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
Barry Warsaw675ac282000-05-26 19:05:16 +0000678 return NULL;
679
680 if (PyObject_SetAttrString(self, "args", args))
681 goto finally;
682
Jeremy Hylton03657cf2000-07-12 13:05:33 +0000683 lenargs = PySequence_Size(args);
Barry Warsaw675ac282000-05-26 19:05:16 +0000684 if (lenargs >= 1) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000685 PyObject *item0 = PySequence_GetItem(args, 0);
Barry Warsaw675ac282000-05-26 19:05:16 +0000686 int status;
687
688 if (!item0)
689 goto finally;
690 status = PyObject_SetAttrString(self, "msg", item0);
691 Py_DECREF(item0);
692 if (status)
693 goto finally;
694 }
695 if (lenargs == 2) {
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000696 PyObject *info = PySequence_GetItem(args, 1);
Barry Warsaw675ac282000-05-26 19:05:16 +0000697 PyObject *filename, *lineno, *offset, *text;
698 int status = 1;
699
700 if (!info)
701 goto finally;
702
703 filename = PySequence_GetItem(info, 0);
704 lineno = PySequence_GetItem(info, 1);
705 offset = PySequence_GetItem(info, 2);
706 text = PySequence_GetItem(info, 3);
707
708 Py_DECREF(info);
709
710 if (filename && lineno && offset && text) {
711 status = PyObject_SetAttrString(self, "filename", filename) ||
712 PyObject_SetAttrString(self, "lineno", lineno) ||
713 PyObject_SetAttrString(self, "offset", offset) ||
714 PyObject_SetAttrString(self, "text", text);
715 }
716 Py_XDECREF(filename);
717 Py_XDECREF(lineno);
718 Py_XDECREF(offset);
719 Py_XDECREF(text);
720
721 if (status)
722 goto finally;
723 }
724 Py_INCREF(Py_None);
725 rtnval = Py_None;
726
727 finally:
728 Py_DECREF(args);
729 return rtnval;
730}
731
732
Fred Drake185a29b2000-08-15 16:20:36 +0000733/* This is called "my_basename" instead of just "basename" to avoid name
734 conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
735 defined, and Python does define that. */
736static char *
737my_basename(char *name)
738{
739 char *cp = name;
740 char *result = name;
741
742 if (name == NULL)
743 return "???";
744 while (*cp != '\0') {
745 if (*cp == SEP)
746 result = cp + 1;
747 ++cp;
748 }
749 return result;
750}
751
752
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000753static PyObject *
754SyntaxError__str__(PyObject *self, PyObject *args)
Barry Warsaw675ac282000-05-26 19:05:16 +0000755{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000756 PyObject *msg;
757 PyObject *str;
Fred Drake1aba5772000-08-15 15:46:16 +0000758 PyObject *filename, *lineno, *result;
Barry Warsaw675ac282000-05-26 19:05:16 +0000759
Fred Drake1aba5772000-08-15 15:46:16 +0000760 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000761 return NULL;
762
763 if (!(msg = PyObject_GetAttrString(self, "msg")))
764 return NULL;
Fred Drake1aba5772000-08-15 15:46:16 +0000765
Barry Warsaw675ac282000-05-26 19:05:16 +0000766 str = PyObject_Str(msg);
767 Py_DECREF(msg);
Fred Drake1aba5772000-08-15 15:46:16 +0000768 result = str;
769
770 /* XXX -- do all the additional formatting with filename and
771 lineno here */
772
773 if (PyString_Check(str)) {
774 int have_filename = 0;
775 int have_lineno = 0;
776 char *buffer = NULL;
777
778 if (filename = PyObject_GetAttrString(self, "filename"))
779 have_filename = PyString_Check(filename);
780 else
781 PyErr_Clear();
782 if (lineno = PyObject_GetAttrString(self, "lineno"))
783 have_lineno = PyInt_Check(lineno);
784 else
785 PyErr_Clear();
786
787 if (have_filename || have_lineno) {
788 int bufsize = (PyString_GET_SIZE(str) + 64 +
789 PyString_GET_SIZE(filename));
790
791 buffer = PyMem_Malloc(bufsize);
792 if (buffer != NULL) {
793 if (have_filename && have_lineno)
794 sprintf(buffer, "%s (%s, line %d)",
795 PyString_AS_STRING(str),
Fred Drake185a29b2000-08-15 16:20:36 +0000796 my_basename(PyString_AS_STRING(filename)),
Fred Drake1aba5772000-08-15 15:46:16 +0000797 PyInt_AsLong(lineno));
798 else if (have_filename)
799 sprintf(buffer, "%s (%s)",
800 PyString_AS_STRING(str),
Fred Drake185a29b2000-08-15 16:20:36 +0000801 my_basename(PyString_AS_STRING(filename)));
Fred Drake1aba5772000-08-15 15:46:16 +0000802 else if (have_lineno)
803 sprintf(buffer, "%s (line %d)",
804 PyString_AS_STRING(str),
805 PyInt_AsLong(lineno));
806 result = PyString_FromString(buffer);
807 if (result == NULL)
808 result = str;
809 else
810 Py_DECREF(str);
811 }
812 }
813 Py_XDECREF(filename);
814 Py_XDECREF(lineno);
815 }
816 return result;
Barry Warsaw675ac282000-05-26 19:05:16 +0000817}
818
819
820PyMethodDef SyntaxError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000821 {"__init__", SyntaxError__init__, METH_VARARGS},
822 {"__str__", SyntaxError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000823 {NULL, NULL}
824};
825
826
827
828static char
829AssertionError__doc__[] = "Assertion failed.";
830
831static char
832LookupError__doc__[] = "Base class for lookup errors.";
833
834static char
835IndexError__doc__[] = "Sequence index out of range.";
836
837static char
838KeyError__doc__[] = "Mapping key not found.";
839
840static char
841ArithmeticError__doc__[] = "Base class for arithmetic errors.";
842
843static char
844OverflowError__doc__[] = "Result too large to be represented.";
845
846static char
847ZeroDivisionError__doc__[] =
848"Second argument to a division or modulo operation was zero.";
849
850static char
851FloatingPointError__doc__[] = "Floating point operation failed.";
852
853static char
854ValueError__doc__[] = "Inappropriate argument value (of correct type).";
855
856static char
857UnicodeError__doc__[] = "Unicode related error.";
858
859static char
860SystemError__doc__[] = "Internal error in the Python interpreter.\n\
861\n\
862Please report this to the Python maintainer, along with the traceback,\n\
863the Python version, and the hardware/OS platform and version.";
864
865static char
866MemoryError__doc__[] = "Out of memory.";
867
Fred Drake85f36392000-07-11 17:53:00 +0000868static char
869IndentationError__doc__[] = "Improper indentation.";
870
871static char
872TabError__doc__[] = "Improper mixture of spaces and tabs.";
873
Barry Warsaw675ac282000-05-26 19:05:16 +0000874
875
876/* module global functions */
877static PyMethodDef functions[] = {
878 /* Sentinel */
879 {NULL, NULL}
880};
881
882
883
884/* Global C API defined exceptions */
885
886PyObject *PyExc_Exception;
887PyObject *PyExc_StandardError;
888PyObject *PyExc_ArithmeticError;
889PyObject *PyExc_LookupError;
890
891PyObject *PyExc_AssertionError;
892PyObject *PyExc_AttributeError;
893PyObject *PyExc_EOFError;
894PyObject *PyExc_FloatingPointError;
895PyObject *PyExc_EnvironmentError;
896PyObject *PyExc_IOError;
897PyObject *PyExc_OSError;
898PyObject *PyExc_ImportError;
899PyObject *PyExc_IndexError;
900PyObject *PyExc_KeyError;
901PyObject *PyExc_KeyboardInterrupt;
902PyObject *PyExc_MemoryError;
903PyObject *PyExc_NameError;
904PyObject *PyExc_OverflowError;
905PyObject *PyExc_RuntimeError;
906PyObject *PyExc_NotImplementedError;
907PyObject *PyExc_SyntaxError;
Fred Drake85f36392000-07-11 17:53:00 +0000908PyObject *PyExc_IndentationError;
909PyObject *PyExc_TabError;
Barry Warsaw675ac282000-05-26 19:05:16 +0000910PyObject *PyExc_SystemError;
911PyObject *PyExc_SystemExit;
912PyObject *PyExc_UnboundLocalError;
913PyObject *PyExc_UnicodeError;
914PyObject *PyExc_TypeError;
915PyObject *PyExc_ValueError;
916PyObject *PyExc_ZeroDivisionError;
917#ifdef MS_WINDOWS
918PyObject *PyExc_WindowsError;
919#endif
920
921/* Pre-computed MemoryError instance. Best to create this as early as
922 * possibly and not wait until a MemoryError is actually raised!
923 */
924PyObject *PyExc_MemoryErrorInst;
925
926
927
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000928/* mapping between exception names and their PyObject ** */
929static struct {
930 char *name;
931 PyObject **exc;
932 PyObject **base; /* NULL == PyExc_StandardError */
933 char *docstr;
934 PyMethodDef *methods;
935 int (*classinit)(PyObject *);
936} exctable[] = {
Barry Warsaw675ac282000-05-26 19:05:16 +0000937 /*
938 * The first three classes MUST appear in exactly this order
939 */
940 {"Exception", &PyExc_Exception},
941 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
942 StandardError__doc__},
943 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
944 /*
945 * The rest appear in depth-first order of the hierarchy
946 */
947 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
948 SystemExit_methods},
949 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
950 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
951 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
952 EnvironmentError_methods},
953 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
954 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
955#ifdef MS_WINDOWS
Mark Hammond557a0442000-08-15 00:37:32 +0000956 {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
Barry Warsaw675ac282000-05-26 19:05:16 +0000957 WindowsError__doc__},
958#endif /* MS_WINDOWS */
959 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
960 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
961 {"NotImplementedError", &PyExc_NotImplementedError,
962 &PyExc_RuntimeError, NotImplementedError__doc__},
963 {"NameError", &PyExc_NameError, 0, NameError__doc__},
964 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
965 UnboundLocalError__doc__},
966 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
967 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
968 SyntaxError_methods, SyntaxError__classinit__},
Fred Drake85f36392000-07-11 17:53:00 +0000969 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
970 IndentationError__doc__},
971 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
972 TabError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +0000973 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
974 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
975 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
976 IndexError__doc__},
977 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
978 KeyError__doc__},
979 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
980 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
981 OverflowError__doc__},
982 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
983 ZeroDivisionError__doc__},
984 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
985 FloatingPointError__doc__},
986 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
987 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
988 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
989 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
990 /* Sentinel */
991 {NULL}
992};
993
994
995
996void
997#ifdef WIN32
998__declspec(dllexport)
999#endif /* WIN32 */
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001000init_exceptions(void)
Barry Warsaw675ac282000-05-26 19:05:16 +00001001{
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001002 char *modulename = "exceptions";
Barry Warsaw675ac282000-05-26 19:05:16 +00001003 int modnamesz = strlen(modulename);
1004 int i;
1005
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001006 PyObject *me = Py_InitModule(modulename, functions);
1007 PyObject *mydict = PyModule_GetDict(me);
1008 PyObject *bltinmod = PyImport_ImportModule("__builtin__");
1009 PyObject *bdict = PyModule_GetDict(bltinmod);
1010 PyObject *doc = PyString_FromString(module__doc__);
1011 PyObject *args;
Barry Warsaw675ac282000-05-26 19:05:16 +00001012
1013 PyDict_SetItemString(mydict, "__doc__", doc);
Barry Warsaw8fcaa922000-07-01 04:45:52 +00001014 Py_DECREF(doc);
Barry Warsaw675ac282000-05-26 19:05:16 +00001015 if (PyErr_Occurred())
1016 Py_FatalError("exceptions bootstrapping error.");
1017
1018 /* This is the base class of all exceptions, so make it first. */
1019 if (make_Exception(modulename) ||
1020 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
1021 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
1022 {
1023 Py_FatalError("Base class `Exception' could not be created.");
1024 }
1025
1026 /* Now we can programmatically create all the remaining exceptions.
1027 * Remember to start the loop at 1 to skip Exceptions.
1028 */
1029 for (i=1; exctable[i].name; i++) {
1030 int status;
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001031 char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
1032 PyObject *base;
Barry Warsaw675ac282000-05-26 19:05:16 +00001033
1034 (void)strcpy(cname, modulename);
1035 (void)strcat(cname, ".");
1036 (void)strcat(cname, exctable[i].name);
1037
1038 if (exctable[i].base == 0)
1039 base = PyExc_StandardError;
1040 else
1041 base = *exctable[i].base;
1042
1043 status = make_class(exctable[i].exc, base, cname,
1044 exctable[i].methods,
1045 exctable[i].docstr);
1046
1047 PyMem_DEL(cname);
1048
1049 if (status)
1050 Py_FatalError("Standard exception classes could not be created.");
1051
1052 if (exctable[i].classinit) {
1053 status = (*exctable[i].classinit)(*exctable[i].exc);
1054 if (status)
1055 Py_FatalError("An exception class could not be initialized.");
1056 }
1057
1058 /* Now insert the class into both this module and the __builtin__
1059 * module.
1060 */
1061 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
1062 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
1063 {
1064 Py_FatalError("Module dictionary insertion problem.");
1065 }
1066 }
1067
1068 /* Now we need to pre-allocate a MemoryError instance */
1069 args = Py_BuildValue("()");
1070 if (!args ||
1071 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1072 {
1073 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1074 }
1075 Py_DECREF(args);
1076
1077 /* We're done with __builtin__ */
1078 Py_DECREF(bltinmod);
1079}
1080
1081
1082void
1083#ifdef WIN32
1084__declspec(dllexport)
1085#endif /* WIN32 */
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001086fini_exceptions(void)
Barry Warsaw675ac282000-05-26 19:05:16 +00001087{
1088 int i;
1089
1090 Py_XDECREF(PyExc_MemoryErrorInst);
1091 PyExc_MemoryErrorInst = NULL;
1092
1093 for (i=0; exctable[i].name; i++) {
1094 Py_XDECREF(*exctable[i].exc);
1095 *exctable[i].exc = NULL;
1096 }
1097}