blob: 4d279791e8ce972f651d4c1b4ec0c2829a2419ce [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
Fred Drake1aba5772000-08-15 15:46:16 +0000247 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000248 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
Fred Drake1aba5772000-08-15 15:46:16 +0000285 if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index))
Barry Warsaw675ac282000-05-26 19:05:16 +0000286 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
Fred Drake1aba5772000-08-15 15:46:16 +0000527 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000528 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;
Fred Drake1aba5772000-08-15 15:46:16 +0000737 PyObject *filename, *lineno, *result;
Barry Warsaw675ac282000-05-26 19:05:16 +0000738
Fred Drake1aba5772000-08-15 15:46:16 +0000739 if (!PyArg_ParseTuple(args, "O:__str__", &self))
Barry Warsaw675ac282000-05-26 19:05:16 +0000740 return NULL;
741
742 if (!(msg = PyObject_GetAttrString(self, "msg")))
743 return NULL;
Fred Drake1aba5772000-08-15 15:46:16 +0000744
Barry Warsaw675ac282000-05-26 19:05:16 +0000745 str = PyObject_Str(msg);
746 Py_DECREF(msg);
Fred Drake1aba5772000-08-15 15:46:16 +0000747 result = str;
748
749 /* XXX -- do all the additional formatting with filename and
750 lineno here */
751
752 if (PyString_Check(str)) {
753 int have_filename = 0;
754 int have_lineno = 0;
755 char *buffer = NULL;
756
757 if (filename = PyObject_GetAttrString(self, "filename"))
758 have_filename = PyString_Check(filename);
759 else
760 PyErr_Clear();
761 if (lineno = PyObject_GetAttrString(self, "lineno"))
762 have_lineno = PyInt_Check(lineno);
763 else
764 PyErr_Clear();
765
766 if (have_filename || have_lineno) {
767 int bufsize = (PyString_GET_SIZE(str) + 64 +
768 PyString_GET_SIZE(filename));
769
770 buffer = PyMem_Malloc(bufsize);
771 if (buffer != NULL) {
772 if (have_filename && have_lineno)
773 sprintf(buffer, "%s (%s, line %d)",
774 PyString_AS_STRING(str),
775 PyString_AS_STRING(filename),
776 PyInt_AsLong(lineno));
777 else if (have_filename)
778 sprintf(buffer, "%s (%s)",
779 PyString_AS_STRING(str),
780 PyString_AS_STRING(filename));
781 else if (have_lineno)
782 sprintf(buffer, "%s (line %d)",
783 PyString_AS_STRING(str),
784 PyInt_AsLong(lineno));
785 result = PyString_FromString(buffer);
786 if (result == NULL)
787 result = str;
788 else
789 Py_DECREF(str);
790 }
791 }
792 Py_XDECREF(filename);
793 Py_XDECREF(lineno);
794 }
795 return result;
Barry Warsaw675ac282000-05-26 19:05:16 +0000796}
797
798
799PyMethodDef SyntaxError_methods[] = {
Jeremy Hylton4e542a32000-06-30 04:59:59 +0000800 {"__init__", SyntaxError__init__, METH_VARARGS},
801 {"__str__", SyntaxError__str__, METH_VARARGS},
Barry Warsaw675ac282000-05-26 19:05:16 +0000802 {NULL, NULL}
803};
804
805
806
807static char
808AssertionError__doc__[] = "Assertion failed.";
809
810static char
811LookupError__doc__[] = "Base class for lookup errors.";
812
813static char
814IndexError__doc__[] = "Sequence index out of range.";
815
816static char
817KeyError__doc__[] = "Mapping key not found.";
818
819static char
820ArithmeticError__doc__[] = "Base class for arithmetic errors.";
821
822static char
823OverflowError__doc__[] = "Result too large to be represented.";
824
825static char
826ZeroDivisionError__doc__[] =
827"Second argument to a division or modulo operation was zero.";
828
829static char
830FloatingPointError__doc__[] = "Floating point operation failed.";
831
832static char
833ValueError__doc__[] = "Inappropriate argument value (of correct type).";
834
835static char
836UnicodeError__doc__[] = "Unicode related error.";
837
838static char
839SystemError__doc__[] = "Internal error in the Python interpreter.\n\
840\n\
841Please report this to the Python maintainer, along with the traceback,\n\
842the Python version, and the hardware/OS platform and version.";
843
844static char
845MemoryError__doc__[] = "Out of memory.";
846
Fred Drake85f36392000-07-11 17:53:00 +0000847static char
848IndentationError__doc__[] = "Improper indentation.";
849
850static char
851TabError__doc__[] = "Improper mixture of spaces and tabs.";
852
Barry Warsaw675ac282000-05-26 19:05:16 +0000853
854
855/* module global functions */
856static PyMethodDef functions[] = {
857 /* Sentinel */
858 {NULL, NULL}
859};
860
861
862
863/* Global C API defined exceptions */
864
865PyObject *PyExc_Exception;
866PyObject *PyExc_StandardError;
867PyObject *PyExc_ArithmeticError;
868PyObject *PyExc_LookupError;
869
870PyObject *PyExc_AssertionError;
871PyObject *PyExc_AttributeError;
872PyObject *PyExc_EOFError;
873PyObject *PyExc_FloatingPointError;
874PyObject *PyExc_EnvironmentError;
875PyObject *PyExc_IOError;
876PyObject *PyExc_OSError;
877PyObject *PyExc_ImportError;
878PyObject *PyExc_IndexError;
879PyObject *PyExc_KeyError;
880PyObject *PyExc_KeyboardInterrupt;
881PyObject *PyExc_MemoryError;
882PyObject *PyExc_NameError;
883PyObject *PyExc_OverflowError;
884PyObject *PyExc_RuntimeError;
885PyObject *PyExc_NotImplementedError;
886PyObject *PyExc_SyntaxError;
Fred Drake85f36392000-07-11 17:53:00 +0000887PyObject *PyExc_IndentationError;
888PyObject *PyExc_TabError;
Barry Warsaw675ac282000-05-26 19:05:16 +0000889PyObject *PyExc_SystemError;
890PyObject *PyExc_SystemExit;
891PyObject *PyExc_UnboundLocalError;
892PyObject *PyExc_UnicodeError;
893PyObject *PyExc_TypeError;
894PyObject *PyExc_ValueError;
895PyObject *PyExc_ZeroDivisionError;
896#ifdef MS_WINDOWS
897PyObject *PyExc_WindowsError;
898#endif
899
900/* Pre-computed MemoryError instance. Best to create this as early as
901 * possibly and not wait until a MemoryError is actually raised!
902 */
903PyObject *PyExc_MemoryErrorInst;
904
905
906
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000907/* mapping between exception names and their PyObject ** */
908static struct {
909 char *name;
910 PyObject **exc;
911 PyObject **base; /* NULL == PyExc_StandardError */
912 char *docstr;
913 PyMethodDef *methods;
914 int (*classinit)(PyObject *);
915} exctable[] = {
Barry Warsaw675ac282000-05-26 19:05:16 +0000916 /*
917 * The first three classes MUST appear in exactly this order
918 */
919 {"Exception", &PyExc_Exception},
920 {"StandardError", &PyExc_StandardError, &PyExc_Exception,
921 StandardError__doc__},
922 {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
923 /*
924 * The rest appear in depth-first order of the hierarchy
925 */
926 {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
927 SystemExit_methods},
928 {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
929 {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
930 {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
931 EnvironmentError_methods},
932 {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
933 {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
934#ifdef MS_WINDOWS
Mark Hammond557a0442000-08-15 00:37:32 +0000935 {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
Barry Warsaw675ac282000-05-26 19:05:16 +0000936 WindowsError__doc__},
937#endif /* MS_WINDOWS */
938 {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
939 {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
940 {"NotImplementedError", &PyExc_NotImplementedError,
941 &PyExc_RuntimeError, NotImplementedError__doc__},
942 {"NameError", &PyExc_NameError, 0, NameError__doc__},
943 {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
944 UnboundLocalError__doc__},
945 {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
946 {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
947 SyntaxError_methods, SyntaxError__classinit__},
Fred Drake85f36392000-07-11 17:53:00 +0000948 {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
949 IndentationError__doc__},
950 {"TabError", &PyExc_TabError, &PyExc_IndentationError,
951 TabError__doc__},
Barry Warsaw675ac282000-05-26 19:05:16 +0000952 {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
953 {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
954 {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
955 IndexError__doc__},
956 {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
957 KeyError__doc__},
958 {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
959 {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
960 OverflowError__doc__},
961 {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
962 ZeroDivisionError__doc__},
963 {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
964 FloatingPointError__doc__},
965 {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
966 {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
967 {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
968 {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
969 /* Sentinel */
970 {NULL}
971};
972
973
974
975void
976#ifdef WIN32
977__declspec(dllexport)
978#endif /* WIN32 */
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000979init_exceptions(void)
Barry Warsaw675ac282000-05-26 19:05:16 +0000980{
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000981 char *modulename = "exceptions";
Barry Warsaw675ac282000-05-26 19:05:16 +0000982 int modnamesz = strlen(modulename);
983 int i;
984
Thomas Wouters0452d1f2000-07-22 18:45:06 +0000985 PyObject *me = Py_InitModule(modulename, functions);
986 PyObject *mydict = PyModule_GetDict(me);
987 PyObject *bltinmod = PyImport_ImportModule("__builtin__");
988 PyObject *bdict = PyModule_GetDict(bltinmod);
989 PyObject *doc = PyString_FromString(module__doc__);
990 PyObject *args;
Barry Warsaw675ac282000-05-26 19:05:16 +0000991
992 PyDict_SetItemString(mydict, "__doc__", doc);
Barry Warsaw8fcaa922000-07-01 04:45:52 +0000993 Py_DECREF(doc);
Barry Warsaw675ac282000-05-26 19:05:16 +0000994 if (PyErr_Occurred())
995 Py_FatalError("exceptions bootstrapping error.");
996
997 /* This is the base class of all exceptions, so make it first. */
998 if (make_Exception(modulename) ||
999 PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
1000 PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
1001 {
1002 Py_FatalError("Base class `Exception' could not be created.");
1003 }
1004
1005 /* Now we can programmatically create all the remaining exceptions.
1006 * Remember to start the loop at 1 to skip Exceptions.
1007 */
1008 for (i=1; exctable[i].name; i++) {
1009 int status;
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001010 char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
1011 PyObject *base;
Barry Warsaw675ac282000-05-26 19:05:16 +00001012
1013 (void)strcpy(cname, modulename);
1014 (void)strcat(cname, ".");
1015 (void)strcat(cname, exctable[i].name);
1016
1017 if (exctable[i].base == 0)
1018 base = PyExc_StandardError;
1019 else
1020 base = *exctable[i].base;
1021
1022 status = make_class(exctable[i].exc, base, cname,
1023 exctable[i].methods,
1024 exctable[i].docstr);
1025
1026 PyMem_DEL(cname);
1027
1028 if (status)
1029 Py_FatalError("Standard exception classes could not be created.");
1030
1031 if (exctable[i].classinit) {
1032 status = (*exctable[i].classinit)(*exctable[i].exc);
1033 if (status)
1034 Py_FatalError("An exception class could not be initialized.");
1035 }
1036
1037 /* Now insert the class into both this module and the __builtin__
1038 * module.
1039 */
1040 if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
1041 PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
1042 {
1043 Py_FatalError("Module dictionary insertion problem.");
1044 }
1045 }
1046
1047 /* Now we need to pre-allocate a MemoryError instance */
1048 args = Py_BuildValue("()");
1049 if (!args ||
1050 !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
1051 {
1052 Py_FatalError("Cannot pre-allocate MemoryError instance\n");
1053 }
1054 Py_DECREF(args);
1055
1056 /* We're done with __builtin__ */
1057 Py_DECREF(bltinmod);
1058}
1059
1060
1061void
1062#ifdef WIN32
1063__declspec(dllexport)
1064#endif /* WIN32 */
Thomas Wouters0452d1f2000-07-22 18:45:06 +00001065fini_exceptions(void)
Barry Warsaw675ac282000-05-26 19:05:16 +00001066{
1067 int i;
1068
1069 Py_XDECREF(PyExc_MemoryErrorInst);
1070 PyExc_MemoryErrorInst = NULL;
1071
1072 for (i=0; exctable[i].name; i++) {
1073 Py_XDECREF(*exctable[i].exc);
1074 *exctable[i].exc = NULL;
1075 }
1076}