PageRenderTime 96ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 1ms

/xbmc/lib/libPython/Python/Python/exceptions.c

https://github.com/tmacreturns/XBMC_wireless_setup
C | 1859 lines | 1392 code | 329 blank | 138 comment | 206 complexity | c550c6f89e17911ca5c7da96a37d7b3e MD5 | raw file
  1. /* 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. #include "Python.h"
  21. #include "osdefs.h"
  22. /* Caution: MS Visual C++ 6 errors if a single string literal exceeds
  23. * 2Kb. So the module docstring has been broken roughly in half, using
  24. * compile-time literal concatenation.
  25. */
  26. /* NOTE: If the exception class hierarchy changes, don't forget to update
  27. * Doc/lib/libexcs.tex!
  28. */
  29. PyDoc_STRVAR(module__doc__,
  30. "Python's standard exception class hierarchy.\n\
  31. \n\
  32. Before Python 1.5, the standard exceptions were all simple string objects.\n\
  33. In Python 1.5, the standard exceptions were converted to classes organized\n\
  34. into a relatively flat hierarchy. String-based standard exceptions were\n\
  35. optional, or used as a fallback if some problem occurred while importing\n\
  36. the exception module. With Python 1.6, optional string-based standard\n\
  37. exceptions were removed (along with the -X command line flag).\n\
  38. \n\
  39. The class exceptions were implemented in such a way as to be almost\n\
  40. completely backward compatible. Some tricky uses of IOError could\n\
  41. potentially have broken, but by Python 1.6, all of these should have\n\
  42. been fixed. As of Python 1.6, the class-based standard exceptions are\n\
  43. now implemented in C, and are guaranteed to exist in the Python\n\
  44. interpreter.\n\
  45. \n\
  46. Here is a rundown of the class hierarchy. The classes found here are\n\
  47. inserted into both the exceptions module and the `built-in' module. It is\n\
  48. recommended that user defined class based exceptions be derived from the\n\
  49. `Exception' class, although this is currently not enforced.\n"
  50. /* keep string pieces "small" */
  51. "\n\
  52. Exception\n\
  53. |\n\
  54. +-- SystemExit\n\
  55. +-- StopIteration\n\
  56. +-- StandardError\n\
  57. | |\n\
  58. | +-- KeyboardInterrupt\n\
  59. | +-- ImportError\n\
  60. | +-- EnvironmentError\n\
  61. | | |\n\
  62. | | +-- IOError\n\
  63. | | +-- OSError\n\
  64. | | |\n\
  65. | | +-- WindowsError\n\
  66. | | +-- VMSError\n\
  67. | |\n\
  68. | +-- EOFError\n\
  69. | +-- RuntimeError\n\
  70. | | |\n\
  71. | | +-- NotImplementedError\n\
  72. | |\n\
  73. | +-- NameError\n\
  74. | | |\n\
  75. | | +-- UnboundLocalError\n\
  76. | |\n\
  77. | +-- AttributeError\n\
  78. | +-- SyntaxError\n\
  79. | | |\n\
  80. | | +-- IndentationError\n\
  81. | | |\n\
  82. | | +-- TabError\n\
  83. | |\n\
  84. | +-- TypeError\n\
  85. | +-- AssertionError\n\
  86. | +-- LookupError\n\
  87. | | |\n\
  88. | | +-- IndexError\n\
  89. | | +-- KeyError\n\
  90. | |\n\
  91. | +-- ArithmeticError\n\
  92. | | |\n\
  93. | | +-- OverflowError\n\
  94. | | +-- ZeroDivisionError\n\
  95. | | +-- FloatingPointError\n\
  96. | |\n\
  97. | +-- ValueError\n\
  98. | | |\n\
  99. | | +-- UnicodeError\n\
  100. | | |\n\
  101. | | +-- UnicodeEncodeError\n\
  102. | | +-- UnicodeDecodeError\n\
  103. | | +-- UnicodeTranslateError\n\
  104. | |\n\
  105. | +-- ReferenceError\n\
  106. | +-- SystemError\n\
  107. | +-- MemoryError\n\
  108. |\n\
  109. +---Warning\n\
  110. |\n\
  111. +-- UserWarning\n\
  112. +-- DeprecationWarning\n\
  113. +-- PendingDeprecationWarning\n\
  114. +-- SyntaxWarning\n\
  115. +-- OverflowWarning\n\
  116. +-- RuntimeWarning\n\
  117. +-- FutureWarning"
  118. );
  119. /* Helper function for populating a dictionary with method wrappers. */
  120. static int
  121. populate_methods(PyObject *klass, PyObject *dict, PyMethodDef *methods)
  122. {
  123. PyObject *module;
  124. int status = -1;
  125. if (!methods)
  126. return 0;
  127. module = PyString_FromString("exceptions");
  128. if (!module)
  129. return 0;
  130. while (methods->ml_name) {
  131. /* get a wrapper for the built-in function */
  132. PyObject *func = PyCFunction_NewEx(methods, NULL, module);
  133. PyObject *meth;
  134. if (!func)
  135. goto status;
  136. /* turn the function into an unbound method */
  137. if (!(meth = PyMethod_New(func, NULL, klass))) {
  138. Py_DECREF(func);
  139. goto status;
  140. }
  141. /* add method to dictionary */
  142. status = PyDict_SetItemString(dict, methods->ml_name, meth);
  143. Py_DECREF(meth);
  144. Py_DECREF(func);
  145. /* stop now if an error occurred, otherwise do the next method */
  146. if (status)
  147. goto status;
  148. methods++;
  149. }
  150. status = 0;
  151. status:
  152. Py_DECREF(module);
  153. return status;
  154. }
  155. /* This function is used to create all subsequent exception classes. */
  156. static int
  157. make_class(PyObject **klass, PyObject *base,
  158. char *name, PyMethodDef *methods,
  159. char *docstr)
  160. {
  161. PyObject *dict = PyDict_New();
  162. PyObject *str = NULL;
  163. int status = -1;
  164. if (!dict)
  165. return -1;
  166. /* If an error occurs from here on, goto finally instead of explicitly
  167. * returning NULL.
  168. */
  169. if (docstr) {
  170. if (!(str = PyString_FromString(docstr)))
  171. goto finally;
  172. if (PyDict_SetItemString(dict, "__doc__", str))
  173. goto finally;
  174. }
  175. if (!(*klass = PyErr_NewException(name, base, dict)))
  176. goto finally;
  177. if (populate_methods(*klass, dict, methods)) {
  178. Py_DECREF(*klass);
  179. *klass = NULL;
  180. goto finally;
  181. }
  182. status = 0;
  183. finally:
  184. Py_XDECREF(dict);
  185. Py_XDECREF(str);
  186. return status;
  187. }
  188. /* Use this for *args signatures, otherwise just use PyArg_ParseTuple() */
  189. static PyObject *
  190. get_self(PyObject *args)
  191. {
  192. PyObject *self = PyTuple_GetItem(args, 0);
  193. if (!self) {
  194. /* Watch out for being called to early in the bootstrapping process */
  195. if (PyExc_TypeError) {
  196. PyErr_SetString(PyExc_TypeError,
  197. "unbound method must be called with instance as first argument");
  198. }
  199. return NULL;
  200. }
  201. return self;
  202. }
  203. /* Notes on bootstrapping the exception classes.
  204. *
  205. * First thing we create is the base class for all exceptions, called
  206. * appropriately enough: Exception. Creation of this class makes no
  207. * assumptions about the existence of any other exception class -- except
  208. * for TypeError, which can conditionally exist.
  209. *
  210. * Next, StandardError is created (which is quite simple) followed by
  211. * TypeError, because the instantiation of other exceptions can potentially
  212. * throw a TypeError. Once these exceptions are created, all the others
  213. * can be created in any order. See the static exctable below for the
  214. * explicit bootstrap order.
  215. *
  216. * All classes after Exception can be created using PyErr_NewException().
  217. */
  218. PyDoc_STRVAR(Exception__doc__, "Common base class for all exceptions.");
  219. static PyObject *
  220. Exception__init__(PyObject *self, PyObject *args)
  221. {
  222. int status;
  223. if (!(self = get_self(args)))
  224. return NULL;
  225. /* set args attribute */
  226. /* XXX size is only a hint */
  227. args = PySequence_GetSlice(args, 1, PySequence_Size(args));
  228. if (!args)
  229. return NULL;
  230. status = PyObject_SetAttrString(self, "args", args);
  231. Py_DECREF(args);
  232. if (status < 0)
  233. return NULL;
  234. Py_INCREF(Py_None);
  235. return Py_None;
  236. }
  237. static PyObject *
  238. Exception__str__(PyObject *self, PyObject *args)
  239. {
  240. PyObject *out;
  241. if (!PyArg_ParseTuple(args, "O:__str__", &self))
  242. return NULL;
  243. args = PyObject_GetAttrString(self, "args");
  244. if (!args)
  245. return NULL;
  246. switch (PySequence_Size(args)) {
  247. case 0:
  248. out = PyString_FromString("");
  249. break;
  250. case 1:
  251. {
  252. PyObject *tmp = PySequence_GetItem(args, 0);
  253. if (tmp) {
  254. out = PyObject_Str(tmp);
  255. Py_DECREF(tmp);
  256. }
  257. else
  258. out = NULL;
  259. break;
  260. }
  261. case -1:
  262. PyErr_Clear();
  263. /* Fall through */
  264. default:
  265. out = PyObject_Str(args);
  266. break;
  267. }
  268. Py_DECREF(args);
  269. return out;
  270. }
  271. static PyObject *
  272. Exception__getitem__(PyObject *self, PyObject *args)
  273. {
  274. PyObject *out;
  275. PyObject *index;
  276. if (!PyArg_ParseTuple(args, "OO:__getitem__", &self, &index))
  277. return NULL;
  278. args = PyObject_GetAttrString(self, "args");
  279. if (!args)
  280. return NULL;
  281. out = PyObject_GetItem(args, index);
  282. Py_DECREF(args);
  283. return out;
  284. }
  285. static PyMethodDef
  286. Exception_methods[] = {
  287. /* methods for the Exception class */
  288. { "__getitem__", Exception__getitem__, METH_VARARGS},
  289. { "__str__", Exception__str__, METH_VARARGS},
  290. { "__init__", Exception__init__, METH_VARARGS},
  291. { NULL, NULL }
  292. };
  293. static int
  294. make_Exception(char *modulename)
  295. {
  296. PyObject *dict = PyDict_New();
  297. PyObject *str = NULL;
  298. PyObject *name = NULL;
  299. int status = -1;
  300. if (!dict)
  301. return -1;
  302. /* If an error occurs from here on, goto finally instead of explicitly
  303. * returning NULL.
  304. */
  305. if (!(str = PyString_FromString(modulename)))
  306. goto finally;
  307. if (PyDict_SetItemString(dict, "__module__", str))
  308. goto finally;
  309. Py_DECREF(str);
  310. if (!(str = PyString_FromString(Exception__doc__)))
  311. goto finally;
  312. if (PyDict_SetItemString(dict, "__doc__", str))
  313. goto finally;
  314. if (!(name = PyString_FromString("Exception")))
  315. goto finally;
  316. if (!(PyExc_Exception = PyClass_New(NULL, dict, name)))
  317. goto finally;
  318. /* Now populate the dictionary with the method suite */
  319. if (populate_methods(PyExc_Exception, dict, Exception_methods))
  320. /* Don't need to reclaim PyExc_Exception here because that'll
  321. * happen during interpreter shutdown.
  322. */
  323. goto finally;
  324. status = 0;
  325. finally:
  326. Py_XDECREF(dict);
  327. Py_XDECREF(str);
  328. Py_XDECREF(name);
  329. return status;
  330. }
  331. PyDoc_STRVAR(StandardError__doc__,
  332. "Base class for all standard Python exceptions.");
  333. PyDoc_STRVAR(TypeError__doc__, "Inappropriate argument type.");
  334. PyDoc_STRVAR(StopIteration__doc__, "Signal the end from iterator.next().");
  335. PyDoc_STRVAR(SystemExit__doc__, "Request to exit from the interpreter.");
  336. static PyObject *
  337. SystemExit__init__(PyObject *self, PyObject *args)
  338. {
  339. PyObject *code;
  340. int status;
  341. if (!(self = get_self(args)))
  342. return NULL;
  343. /* Set args attribute. */
  344. if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
  345. return NULL;
  346. status = PyObject_SetAttrString(self, "args", args);
  347. if (status < 0) {
  348. Py_DECREF(args);
  349. return NULL;
  350. }
  351. /* set code attribute */
  352. switch (PySequence_Size(args)) {
  353. case 0:
  354. Py_INCREF(Py_None);
  355. code = Py_None;
  356. break;
  357. case 1:
  358. code = PySequence_GetItem(args, 0);
  359. break;
  360. case -1:
  361. PyErr_Clear();
  362. /* Fall through */
  363. default:
  364. Py_INCREF(args);
  365. code = args;
  366. break;
  367. }
  368. status = PyObject_SetAttrString(self, "code", code);
  369. Py_DECREF(code);
  370. Py_DECREF(args);
  371. if (status < 0)
  372. return NULL;
  373. Py_INCREF(Py_None);
  374. return Py_None;
  375. }
  376. static PyMethodDef SystemExit_methods[] = {
  377. { "__init__", SystemExit__init__, METH_VARARGS},
  378. {NULL, NULL}
  379. };
  380. PyDoc_STRVAR(KeyboardInterrupt__doc__, "Program interrupted by user.");
  381. PyDoc_STRVAR(ImportError__doc__,
  382. "Import can't find module, or can't find name in module.");
  383. PyDoc_STRVAR(EnvironmentError__doc__, "Base class for I/O related errors.");
  384. static PyObject *
  385. EnvironmentError__init__(PyObject *self, PyObject *args)
  386. {
  387. PyObject *item0 = NULL;
  388. PyObject *item1 = NULL;
  389. PyObject *item2 = NULL;
  390. PyObject *subslice = NULL;
  391. PyObject *rtnval = NULL;
  392. if (!(self = get_self(args)))
  393. return NULL;
  394. if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
  395. return NULL;
  396. if (PyObject_SetAttrString(self, "args", args) ||
  397. PyObject_SetAttrString(self, "errno", Py_None) ||
  398. PyObject_SetAttrString(self, "strerror", Py_None) ||
  399. PyObject_SetAttrString(self, "filename", Py_None))
  400. {
  401. goto finally;
  402. }
  403. switch (PySequence_Size(args)) {
  404. case 3:
  405. /* Where a function has a single filename, such as open() or some
  406. * of the os module functions, PyErr_SetFromErrnoWithFilename() is
  407. * called, giving a third argument which is the filename. But, so
  408. * that old code using in-place unpacking doesn't break, e.g.:
  409. *
  410. * except IOError, (errno, strerror):
  411. *
  412. * we hack args so that it only contains two items. This also
  413. * means we need our own __str__() which prints out the filename
  414. * when it was supplied.
  415. */
  416. item0 = PySequence_GetItem(args, 0);
  417. item1 = PySequence_GetItem(args, 1);
  418. item2 = PySequence_GetItem(args, 2);
  419. if (!item0 || !item1 || !item2)
  420. goto finally;
  421. if (PyObject_SetAttrString(self, "errno", item0) ||
  422. PyObject_SetAttrString(self, "strerror", item1) ||
  423. PyObject_SetAttrString(self, "filename", item2))
  424. {
  425. goto finally;
  426. }
  427. subslice = PySequence_GetSlice(args, 0, 2);
  428. if (!subslice || PyObject_SetAttrString(self, "args", subslice))
  429. goto finally;
  430. break;
  431. case 2:
  432. /* Used when PyErr_SetFromErrno() is called and no filename
  433. * argument is given.
  434. */
  435. item0 = PySequence_GetItem(args, 0);
  436. item1 = PySequence_GetItem(args, 1);
  437. if (!item0 || !item1)
  438. goto finally;
  439. if (PyObject_SetAttrString(self, "errno", item0) ||
  440. PyObject_SetAttrString(self, "strerror", item1))
  441. {
  442. goto finally;
  443. }
  444. break;
  445. case -1:
  446. PyErr_Clear();
  447. break;
  448. }
  449. Py_INCREF(Py_None);
  450. rtnval = Py_None;
  451. finally:
  452. Py_DECREF(args);
  453. Py_XDECREF(item0);
  454. Py_XDECREF(item1);
  455. Py_XDECREF(item2);
  456. Py_XDECREF(subslice);
  457. return rtnval;
  458. }
  459. static PyObject *
  460. EnvironmentError__str__(PyObject *self, PyObject *args)
  461. {
  462. PyObject *originalself = self;
  463. PyObject *filename;
  464. PyObject *serrno;
  465. PyObject *strerror;
  466. PyObject *rtnval = NULL;
  467. if (!PyArg_ParseTuple(args, "O:__str__", &self))
  468. return NULL;
  469. filename = PyObject_GetAttrString(self, "filename");
  470. serrno = PyObject_GetAttrString(self, "errno");
  471. strerror = PyObject_GetAttrString(self, "strerror");
  472. if (!filename || !serrno || !strerror)
  473. goto finally;
  474. if (filename != Py_None) {
  475. PyObject *fmt = PyString_FromString("[Errno %s] %s: %s");
  476. PyObject *repr = PyObject_Repr(filename);
  477. PyObject *tuple = PyTuple_New(3);
  478. if (!fmt || !repr || !tuple) {
  479. Py_XDECREF(fmt);
  480. Py_XDECREF(repr);
  481. Py_XDECREF(tuple);
  482. goto finally;
  483. }
  484. PyTuple_SET_ITEM(tuple, 0, serrno);
  485. PyTuple_SET_ITEM(tuple, 1, strerror);
  486. PyTuple_SET_ITEM(tuple, 2, repr);
  487. rtnval = PyString_Format(fmt, tuple);
  488. Py_DECREF(fmt);
  489. Py_DECREF(tuple);
  490. /* already freed because tuple owned only reference */
  491. serrno = NULL;
  492. strerror = NULL;
  493. }
  494. else if (PyObject_IsTrue(serrno) && PyObject_IsTrue(strerror)) {
  495. PyObject *fmt = PyString_FromString("[Errno %s] %s");
  496. PyObject *tuple = PyTuple_New(2);
  497. if (!fmt || !tuple) {
  498. Py_XDECREF(fmt);
  499. Py_XDECREF(tuple);
  500. goto finally;
  501. }
  502. PyTuple_SET_ITEM(tuple, 0, serrno);
  503. PyTuple_SET_ITEM(tuple, 1, strerror);
  504. rtnval = PyString_Format(fmt, tuple);
  505. Py_DECREF(fmt);
  506. Py_DECREF(tuple);
  507. /* already freed because tuple owned only reference */
  508. serrno = NULL;
  509. strerror = NULL;
  510. }
  511. else
  512. /* The original Python code said:
  513. *
  514. * return StandardError.__str__(self)
  515. *
  516. * but there is no StandardError__str__() function; we happen to
  517. * know that's just a pass through to Exception__str__().
  518. */
  519. rtnval = Exception__str__(originalself, args);
  520. finally:
  521. Py_XDECREF(filename);
  522. Py_XDECREF(serrno);
  523. Py_XDECREF(strerror);
  524. return rtnval;
  525. }
  526. static
  527. PyMethodDef EnvironmentError_methods[] = {
  528. {"__init__", EnvironmentError__init__, METH_VARARGS},
  529. {"__str__", EnvironmentError__str__, METH_VARARGS},
  530. {NULL, NULL}
  531. };
  532. PyDoc_STRVAR(IOError__doc__, "I/O operation failed.");
  533. PyDoc_STRVAR(OSError__doc__, "OS system call failed.");
  534. #ifdef MS_WINDOWS
  535. PyDoc_STRVAR(WindowsError__doc__, "MS-Windows OS system call failed.");
  536. #endif /* MS_WINDOWS */
  537. #ifdef __VMS
  538. static char
  539. VMSError__doc__[] = "OpenVMS OS system call failed.";
  540. #endif
  541. PyDoc_STRVAR(EOFError__doc__, "Read beyond end of file.");
  542. PyDoc_STRVAR(RuntimeError__doc__, "Unspecified run-time error.");
  543. PyDoc_STRVAR(NotImplementedError__doc__,
  544. "Method or function hasn't been implemented yet.");
  545. PyDoc_STRVAR(NameError__doc__, "Name not found globally.");
  546. PyDoc_STRVAR(UnboundLocalError__doc__,
  547. "Local name referenced but not bound to a value.");
  548. PyDoc_STRVAR(AttributeError__doc__, "Attribute not found.");
  549. PyDoc_STRVAR(SyntaxError__doc__, "Invalid syntax.");
  550. static int
  551. SyntaxError__classinit__(PyObject *klass)
  552. {
  553. int retval = 0;
  554. PyObject *emptystring = PyString_FromString("");
  555. /* Additional class-creation time initializations */
  556. if (!emptystring ||
  557. PyObject_SetAttrString(klass, "msg", emptystring) ||
  558. PyObject_SetAttrString(klass, "filename", Py_None) ||
  559. PyObject_SetAttrString(klass, "lineno", Py_None) ||
  560. PyObject_SetAttrString(klass, "offset", Py_None) ||
  561. PyObject_SetAttrString(klass, "text", Py_None) ||
  562. PyObject_SetAttrString(klass, "print_file_and_line", Py_None))
  563. {
  564. retval = -1;
  565. }
  566. Py_XDECREF(emptystring);
  567. return retval;
  568. }
  569. static PyObject *
  570. SyntaxError__init__(PyObject *self, PyObject *args)
  571. {
  572. PyObject *rtnval = NULL;
  573. int lenargs;
  574. if (!(self = get_self(args)))
  575. return NULL;
  576. if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
  577. return NULL;
  578. if (PyObject_SetAttrString(self, "args", args))
  579. goto finally;
  580. lenargs = PySequence_Size(args);
  581. if (lenargs >= 1) {
  582. PyObject *item0 = PySequence_GetItem(args, 0);
  583. int status;
  584. if (!item0)
  585. goto finally;
  586. status = PyObject_SetAttrString(self, "msg", item0);
  587. Py_DECREF(item0);
  588. if (status)
  589. goto finally;
  590. }
  591. if (lenargs == 2) {
  592. PyObject *info = PySequence_GetItem(args, 1);
  593. PyObject *filename = NULL, *lineno = NULL;
  594. PyObject *offset = NULL, *text = NULL;
  595. int status = 1;
  596. if (!info)
  597. goto finally;
  598. filename = PySequence_GetItem(info, 0);
  599. if (filename != NULL) {
  600. lineno = PySequence_GetItem(info, 1);
  601. if (lineno != NULL) {
  602. offset = PySequence_GetItem(info, 2);
  603. if (offset != NULL) {
  604. text = PySequence_GetItem(info, 3);
  605. if (text != NULL) {
  606. status =
  607. PyObject_SetAttrString(self, "filename", filename)
  608. || PyObject_SetAttrString(self, "lineno", lineno)
  609. || PyObject_SetAttrString(self, "offset", offset)
  610. || PyObject_SetAttrString(self, "text", text);
  611. Py_DECREF(text);
  612. }
  613. Py_DECREF(offset);
  614. }
  615. Py_DECREF(lineno);
  616. }
  617. Py_DECREF(filename);
  618. }
  619. Py_DECREF(info);
  620. if (status)
  621. goto finally;
  622. }
  623. Py_INCREF(Py_None);
  624. rtnval = Py_None;
  625. finally:
  626. Py_DECREF(args);
  627. return rtnval;
  628. }
  629. /* This is called "my_basename" instead of just "basename" to avoid name
  630. conflicts with glibc; basename is already prototyped if _GNU_SOURCE is
  631. defined, and Python does define that. */
  632. static char *
  633. my_basename(char *name)
  634. {
  635. char *cp = name;
  636. char *result = name;
  637. if (name == NULL)
  638. return "???";
  639. while (*cp != '\0') {
  640. if (*cp == SEP)
  641. result = cp + 1;
  642. ++cp;
  643. }
  644. return result;
  645. }
  646. static PyObject *
  647. SyntaxError__str__(PyObject *self, PyObject *args)
  648. {
  649. PyObject *msg;
  650. PyObject *str;
  651. PyObject *filename, *lineno, *result;
  652. if (!PyArg_ParseTuple(args, "O:__str__", &self))
  653. return NULL;
  654. if (!(msg = PyObject_GetAttrString(self, "msg")))
  655. return NULL;
  656. str = PyObject_Str(msg);
  657. Py_DECREF(msg);
  658. result = str;
  659. /* XXX -- do all the additional formatting with filename and
  660. lineno here */
  661. if (str != NULL && PyString_Check(str)) {
  662. int have_filename = 0;
  663. int have_lineno = 0;
  664. char *buffer = NULL;
  665. if ((filename = PyObject_GetAttrString(self, "filename")) != NULL)
  666. have_filename = PyString_Check(filename);
  667. else
  668. PyErr_Clear();
  669. if ((lineno = PyObject_GetAttrString(self, "lineno")) != NULL)
  670. have_lineno = PyInt_Check(lineno);
  671. else
  672. PyErr_Clear();
  673. if (have_filename || have_lineno) {
  674. int bufsize = PyString_GET_SIZE(str) + 64;
  675. if (have_filename)
  676. bufsize += PyString_GET_SIZE(filename);
  677. buffer = PyMem_MALLOC(bufsize);
  678. if (buffer != NULL) {
  679. if (have_filename && have_lineno)
  680. PyOS_snprintf(buffer, bufsize, "%s (%s, line %ld)",
  681. PyString_AS_STRING(str),
  682. my_basename(PyString_AS_STRING(filename)),
  683. PyInt_AsLong(lineno));
  684. else if (have_filename)
  685. PyOS_snprintf(buffer, bufsize, "%s (%s)",
  686. PyString_AS_STRING(str),
  687. my_basename(PyString_AS_STRING(filename)));
  688. else if (have_lineno)
  689. PyOS_snprintf(buffer, bufsize, "%s (line %ld)",
  690. PyString_AS_STRING(str),
  691. PyInt_AsLong(lineno));
  692. result = PyString_FromString(buffer);
  693. PyMem_FREE(buffer);
  694. if (result == NULL)
  695. result = str;
  696. else
  697. Py_DECREF(str);
  698. }
  699. }
  700. Py_XDECREF(filename);
  701. Py_XDECREF(lineno);
  702. }
  703. return result;
  704. }
  705. static PyMethodDef SyntaxError_methods[] = {
  706. {"__init__", SyntaxError__init__, METH_VARARGS},
  707. {"__str__", SyntaxError__str__, METH_VARARGS},
  708. {NULL, NULL}
  709. };
  710. static PyObject *
  711. KeyError__str__(PyObject *self, PyObject *args)
  712. {
  713. PyObject *argsattr;
  714. PyObject *result;
  715. if (!PyArg_ParseTuple(args, "O:__str__", &self))
  716. return NULL;
  717. if (!(argsattr = PyObject_GetAttrString(self, "args")))
  718. return NULL;
  719. /* If args is a tuple of exactly one item, apply repr to args[0].
  720. This is done so that e.g. the exception raised by {}[''] prints
  721. KeyError: ''
  722. rather than the confusing
  723. KeyError
  724. alone. The downside is that if KeyError is raised with an explanatory
  725. string, that string will be displayed in quotes. Too bad.
  726. If args is anything else, use the default Exception__str__().
  727. */
  728. if (PyTuple_Check(argsattr) && PyTuple_GET_SIZE(argsattr) == 1) {
  729. PyObject *key = PyTuple_GET_ITEM(argsattr, 0);
  730. result = PyObject_Repr(key);
  731. }
  732. else
  733. result = Exception__str__(self, args);
  734. Py_DECREF(argsattr);
  735. return result;
  736. }
  737. static PyMethodDef KeyError_methods[] = {
  738. {"__str__", KeyError__str__, METH_VARARGS},
  739. {NULL, NULL}
  740. };
  741. #ifdef Py_USING_UNICODE
  742. static
  743. int get_int(PyObject *exc, const char *name, int *value)
  744. {
  745. PyObject *attr = PyObject_GetAttrString(exc, (char *)name);
  746. if (!attr)
  747. return -1;
  748. if (!PyInt_Check(attr)) {
  749. PyErr_Format(PyExc_TypeError, "%.200s attribute must be int", name);
  750. Py_DECREF(attr);
  751. return -1;
  752. }
  753. *value = PyInt_AS_LONG(attr);
  754. Py_DECREF(attr);
  755. return 0;
  756. }
  757. static
  758. int set_int(PyObject *exc, const char *name, int value)
  759. {
  760. PyObject *obj = PyInt_FromLong(value);
  761. int result;
  762. if (!obj)
  763. return -1;
  764. result = PyObject_SetAttrString(exc, (char *)name, obj);
  765. Py_DECREF(obj);
  766. return result;
  767. }
  768. static
  769. PyObject *get_string(PyObject *exc, const char *name)
  770. {
  771. PyObject *attr = PyObject_GetAttrString(exc, (char *)name);
  772. if (!attr)
  773. return NULL;
  774. if (!PyString_Check(attr)) {
  775. PyErr_Format(PyExc_TypeError, "%.200s attribute must be str", name);
  776. Py_DECREF(attr);
  777. return NULL;
  778. }
  779. return attr;
  780. }
  781. static
  782. int set_string(PyObject *exc, const char *name, const char *value)
  783. {
  784. PyObject *obj = PyString_FromString(value);
  785. int result;
  786. if (!obj)
  787. return -1;
  788. result = PyObject_SetAttrString(exc, (char *)name, obj);
  789. Py_DECREF(obj);
  790. return result;
  791. }
  792. static
  793. PyObject *get_unicode(PyObject *exc, const char *name)
  794. {
  795. PyObject *attr = PyObject_GetAttrString(exc, (char *)name);
  796. if (!attr)
  797. return NULL;
  798. if (!PyUnicode_Check(attr)) {
  799. PyErr_Format(PyExc_TypeError, "%.200s attribute must be unicode", name);
  800. Py_DECREF(attr);
  801. return NULL;
  802. }
  803. return attr;
  804. }
  805. PyObject * PyUnicodeEncodeError_GetEncoding(PyObject *exc)
  806. {
  807. return get_string(exc, "encoding");
  808. }
  809. PyObject * PyUnicodeDecodeError_GetEncoding(PyObject *exc)
  810. {
  811. return get_string(exc, "encoding");
  812. }
  813. PyObject *PyUnicodeEncodeError_GetObject(PyObject *exc)
  814. {
  815. return get_unicode(exc, "object");
  816. }
  817. PyObject *PyUnicodeDecodeError_GetObject(PyObject *exc)
  818. {
  819. return get_string(exc, "object");
  820. }
  821. PyObject *PyUnicodeTranslateError_GetObject(PyObject *exc)
  822. {
  823. return get_unicode(exc, "object");
  824. }
  825. int PyUnicodeEncodeError_GetStart(PyObject *exc, int *start)
  826. {
  827. if (!get_int(exc, "start", start)) {
  828. PyObject *object = PyUnicodeEncodeError_GetObject(exc);
  829. int size;
  830. if (!object)
  831. return -1;
  832. size = PyUnicode_GET_SIZE(object);
  833. if (*start<0)
  834. *start = 0;
  835. if (*start>=size)
  836. *start = size-1;
  837. Py_DECREF(object);
  838. return 0;
  839. }
  840. return -1;
  841. }
  842. int PyUnicodeDecodeError_GetStart(PyObject *exc, int *start)
  843. {
  844. if (!get_int(exc, "start", start)) {
  845. PyObject *object = PyUnicodeDecodeError_GetObject(exc);
  846. int size;
  847. if (!object)
  848. return -1;
  849. size = PyString_GET_SIZE(object);
  850. if (*start<0)
  851. *start = 0;
  852. if (*start>=size)
  853. *start = size-1;
  854. Py_DECREF(object);
  855. return 0;
  856. }
  857. return -1;
  858. }
  859. int PyUnicodeTranslateError_GetStart(PyObject *exc, int *start)
  860. {
  861. return PyUnicodeEncodeError_GetStart(exc, start);
  862. }
  863. int PyUnicodeEncodeError_SetStart(PyObject *exc, int start)
  864. {
  865. return set_int(exc, "start", start);
  866. }
  867. int PyUnicodeDecodeError_SetStart(PyObject *exc, int start)
  868. {
  869. return set_int(exc, "start", start);
  870. }
  871. int PyUnicodeTranslateError_SetStart(PyObject *exc, int start)
  872. {
  873. return set_int(exc, "start", start);
  874. }
  875. int PyUnicodeEncodeError_GetEnd(PyObject *exc, int *end)
  876. {
  877. if (!get_int(exc, "end", end)) {
  878. PyObject *object = PyUnicodeEncodeError_GetObject(exc);
  879. int size;
  880. if (!object)
  881. return -1;
  882. size = PyUnicode_GET_SIZE(object);
  883. if (*end<1)
  884. *end = 1;
  885. if (*end>size)
  886. *end = size;
  887. Py_DECREF(object);
  888. return 0;
  889. }
  890. return -1;
  891. }
  892. int PyUnicodeDecodeError_GetEnd(PyObject *exc, int *end)
  893. {
  894. if (!get_int(exc, "end", end)) {
  895. PyObject *object = PyUnicodeDecodeError_GetObject(exc);
  896. int size;
  897. if (!object)
  898. return -1;
  899. size = PyString_GET_SIZE(object);
  900. if (*end<1)
  901. *end = 1;
  902. if (*end>size)
  903. *end = size;
  904. Py_DECREF(object);
  905. return 0;
  906. }
  907. return -1;
  908. }
  909. int PyUnicodeTranslateError_GetEnd(PyObject *exc, int *start)
  910. {
  911. return PyUnicodeEncodeError_GetEnd(exc, start);
  912. }
  913. int PyUnicodeEncodeError_SetEnd(PyObject *exc, int end)
  914. {
  915. return set_int(exc, "end", end);
  916. }
  917. int PyUnicodeDecodeError_SetEnd(PyObject *exc, int end)
  918. {
  919. return set_int(exc, "end", end);
  920. }
  921. int PyUnicodeTranslateError_SetEnd(PyObject *exc, int end)
  922. {
  923. return set_int(exc, "end", end);
  924. }
  925. PyObject *PyUnicodeEncodeError_GetReason(PyObject *exc)
  926. {
  927. return get_string(exc, "reason");
  928. }
  929. PyObject *PyUnicodeDecodeError_GetReason(PyObject *exc)
  930. {
  931. return get_string(exc, "reason");
  932. }
  933. PyObject *PyUnicodeTranslateError_GetReason(PyObject *exc)
  934. {
  935. return get_string(exc, "reason");
  936. }
  937. int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
  938. {
  939. return set_string(exc, "reason", reason);
  940. }
  941. int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
  942. {
  943. return set_string(exc, "reason", reason);
  944. }
  945. int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
  946. {
  947. return set_string(exc, "reason", reason);
  948. }
  949. static PyObject *
  950. UnicodeError__init__(PyObject *self, PyObject *args, PyTypeObject *objecttype)
  951. {
  952. PyObject *rtnval = NULL;
  953. PyObject *encoding;
  954. PyObject *object;
  955. PyObject *start;
  956. PyObject *end;
  957. PyObject *reason;
  958. if (!(self = get_self(args)))
  959. return NULL;
  960. if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
  961. return NULL;
  962. if (!PyArg_ParseTuple(args, "O!O!O!O!O!",
  963. &PyString_Type, &encoding,
  964. objecttype, &object,
  965. &PyInt_Type, &start,
  966. &PyInt_Type, &end,
  967. &PyString_Type, &reason))
  968. goto finally;
  969. if (PyObject_SetAttrString(self, "args", args))
  970. goto finally;
  971. if (PyObject_SetAttrString(self, "encoding", encoding))
  972. goto finally;
  973. if (PyObject_SetAttrString(self, "object", object))
  974. goto finally;
  975. if (PyObject_SetAttrString(self, "start", start))
  976. goto finally;
  977. if (PyObject_SetAttrString(self, "end", end))
  978. goto finally;
  979. if (PyObject_SetAttrString(self, "reason", reason))
  980. goto finally;
  981. Py_INCREF(Py_None);
  982. rtnval = Py_None;
  983. finally:
  984. Py_DECREF(args);
  985. return rtnval;
  986. }
  987. static PyObject *
  988. UnicodeEncodeError__init__(PyObject *self, PyObject *args)
  989. {
  990. return UnicodeError__init__(self, args, &PyUnicode_Type);
  991. }
  992. static PyObject *
  993. UnicodeEncodeError__str__(PyObject *self, PyObject *arg)
  994. {
  995. PyObject *encodingObj = NULL;
  996. PyObject *objectObj = NULL;
  997. int start;
  998. int end;
  999. PyObject *reasonObj = NULL;
  1000. char buffer[1000];
  1001. PyObject *result = NULL;
  1002. self = arg;
  1003. if (!(encodingObj = PyUnicodeEncodeError_GetEncoding(self)))
  1004. goto error;
  1005. if (!(objectObj = PyUnicodeEncodeError_GetObject(self)))
  1006. goto error;
  1007. if (PyUnicodeEncodeError_GetStart(self, &start))
  1008. goto error;
  1009. if (PyUnicodeEncodeError_GetEnd(self, &end))
  1010. goto error;
  1011. if (!(reasonObj = PyUnicodeEncodeError_GetReason(self)))
  1012. goto error;
  1013. if (end==start+1) {
  1014. int badchar = (int)PyUnicode_AS_UNICODE(objectObj)[start];
  1015. char *format;
  1016. if (badchar <= 0xff)
  1017. format = "'%.400s' codec can't encode character u'\\x%02x' in position %d: %.400s";
  1018. else if (badchar <= 0xffff)
  1019. format = "'%.400s' codec can't encode character u'\\u%04x' in position %d: %.400s";
  1020. else
  1021. format = "'%.400s' codec can't encode character u'\\U%08x' in position %d: %.400s";
  1022. PyOS_snprintf(buffer, sizeof(buffer),
  1023. format,
  1024. PyString_AS_STRING(encodingObj),
  1025. badchar,
  1026. start,
  1027. PyString_AS_STRING(reasonObj)
  1028. );
  1029. }
  1030. else {
  1031. PyOS_snprintf(buffer, sizeof(buffer),
  1032. "'%.400s' codec can't encode characters in position %d-%d: %.400s",
  1033. PyString_AS_STRING(encodingObj),
  1034. start,
  1035. end-1,
  1036. PyString_AS_STRING(reasonObj)
  1037. );
  1038. }
  1039. result = PyString_FromString(buffer);
  1040. error:
  1041. Py_XDECREF(reasonObj);
  1042. Py_XDECREF(objectObj);
  1043. Py_XDECREF(encodingObj);
  1044. return result;
  1045. }
  1046. static PyMethodDef UnicodeEncodeError_methods[] = {
  1047. {"__init__", UnicodeEncodeError__init__, METH_VARARGS},
  1048. {"__str__", UnicodeEncodeError__str__, METH_O},
  1049. {NULL, NULL}
  1050. };
  1051. PyObject * PyUnicodeEncodeError_Create(
  1052. const char *encoding, const Py_UNICODE *object, int length,
  1053. int start, int end, const char *reason)
  1054. {
  1055. return PyObject_CallFunction(PyExc_UnicodeEncodeError, "su#iis",
  1056. encoding, object, length, start, end, reason);
  1057. }
  1058. static PyObject *
  1059. UnicodeDecodeError__init__(PyObject *self, PyObject *args)
  1060. {
  1061. return UnicodeError__init__(self, args, &PyString_Type);
  1062. }
  1063. static PyObject *
  1064. UnicodeDecodeError__str__(PyObject *self, PyObject *arg)
  1065. {
  1066. PyObject *encodingObj = NULL;
  1067. PyObject *objectObj = NULL;
  1068. int start;
  1069. int end;
  1070. PyObject *reasonObj = NULL;
  1071. char buffer[1000];
  1072. PyObject *result = NULL;
  1073. self = arg;
  1074. if (!(encodingObj = PyUnicodeDecodeError_GetEncoding(self)))
  1075. goto error;
  1076. if (!(objectObj = PyUnicodeDecodeError_GetObject(self)))
  1077. goto error;
  1078. if (PyUnicodeDecodeError_GetStart(self, &start))
  1079. goto error;
  1080. if (PyUnicodeDecodeError_GetEnd(self, &end))
  1081. goto error;
  1082. if (!(reasonObj = PyUnicodeDecodeError_GetReason(self)))
  1083. goto error;
  1084. if (end==start+1) {
  1085. PyOS_snprintf(buffer, sizeof(buffer),
  1086. "'%.400s' codec can't decode byte 0x%02x in position %d: %.400s",
  1087. PyString_AS_STRING(encodingObj),
  1088. ((int)PyString_AS_STRING(objectObj)[start])&0xff,
  1089. start,
  1090. PyString_AS_STRING(reasonObj)
  1091. );
  1092. }
  1093. else {
  1094. PyOS_snprintf(buffer, sizeof(buffer),
  1095. "'%.400s' codec can't decode bytes in position %d-%d: %.400s",
  1096. PyString_AS_STRING(encodingObj),
  1097. start,
  1098. end-1,
  1099. PyString_AS_STRING(reasonObj)
  1100. );
  1101. }
  1102. result = PyString_FromString(buffer);
  1103. error:
  1104. Py_XDECREF(reasonObj);
  1105. Py_XDECREF(objectObj);
  1106. Py_XDECREF(encodingObj);
  1107. return result;
  1108. }
  1109. static PyMethodDef UnicodeDecodeError_methods[] = {
  1110. {"__init__", UnicodeDecodeError__init__, METH_VARARGS},
  1111. {"__str__", UnicodeDecodeError__str__, METH_O},
  1112. {NULL, NULL}
  1113. };
  1114. PyObject * PyUnicodeDecodeError_Create(
  1115. const char *encoding, const char *object, int length,
  1116. int start, int end, const char *reason)
  1117. {
  1118. return PyObject_CallFunction(PyExc_UnicodeDecodeError, "ss#iis",
  1119. encoding, object, length, start, end, reason);
  1120. }
  1121. static PyObject *
  1122. UnicodeTranslateError__init__(PyObject *self, PyObject *args)
  1123. {
  1124. PyObject *rtnval = NULL;
  1125. PyObject *object;
  1126. PyObject *start;
  1127. PyObject *end;
  1128. PyObject *reason;
  1129. if (!(self = get_self(args)))
  1130. return NULL;
  1131. if (!(args = PySequence_GetSlice(args, 1, PySequence_Size(args))))
  1132. return NULL;
  1133. if (!PyArg_ParseTuple(args, "O!O!O!O!",
  1134. &PyUnicode_Type, &object,
  1135. &PyInt_Type, &start,
  1136. &PyInt_Type, &end,
  1137. &PyString_Type, &reason))
  1138. goto finally;
  1139. if (PyObject_SetAttrString(self, "args", args))
  1140. goto finally;
  1141. if (PyObject_SetAttrString(self, "object", object))
  1142. goto finally;
  1143. if (PyObject_SetAttrString(self, "start", start))
  1144. goto finally;
  1145. if (PyObject_SetAttrString(self, "end", end))
  1146. goto finally;
  1147. if (PyObject_SetAttrString(self, "reason", reason))
  1148. goto finally;
  1149. Py_INCREF(Py_None);
  1150. rtnval = Py_None;
  1151. finally:
  1152. Py_DECREF(args);
  1153. return rtnval;
  1154. }
  1155. static PyObject *
  1156. UnicodeTranslateError__str__(PyObject *self, PyObject *arg)
  1157. {
  1158. PyObject *objectObj = NULL;
  1159. int start;
  1160. int end;
  1161. PyObject *reasonObj = NULL;
  1162. char buffer[1000];
  1163. PyObject *result = NULL;
  1164. self = arg;
  1165. if (!(objectObj = PyUnicodeTranslateError_GetObject(self)))
  1166. goto error;
  1167. if (PyUnicodeTranslateError_GetStart(self, &start))
  1168. goto error;
  1169. if (PyUnicodeTranslateError_GetEnd(self, &end))
  1170. goto error;
  1171. if (!(reasonObj = PyUnicodeTranslateError_GetReason(self)))
  1172. goto error;
  1173. if (end==start+1) {
  1174. int badchar = (int)PyUnicode_AS_UNICODE(objectObj)[start];
  1175. char *format;
  1176. if (badchar <= 0xff)
  1177. format = "can't translate character u'\\x%02x' in position %d: %.400s";
  1178. else if (badchar <= 0xffff)
  1179. format = "can't translate character u'\\u%04x' in position %d: %.400s";
  1180. else
  1181. format = "can't translate character u'\\U%08x' in position %d: %.400s";
  1182. PyOS_snprintf(buffer, sizeof(buffer),
  1183. format,
  1184. badchar,
  1185. start,
  1186. PyString_AS_STRING(reasonObj)
  1187. );
  1188. }
  1189. else {
  1190. PyOS_snprintf(buffer, sizeof(buffer),
  1191. "can't translate characters in position %d-%d: %.400s",
  1192. start,
  1193. end-1,
  1194. PyString_AS_STRING(reasonObj)
  1195. );
  1196. }
  1197. result = PyString_FromString(buffer);
  1198. error:
  1199. Py_XDECREF(reasonObj);
  1200. Py_XDECREF(objectObj);
  1201. return result;
  1202. }
  1203. static PyMethodDef UnicodeTranslateError_methods[] = {
  1204. {"__init__", UnicodeTranslateError__init__, METH_VARARGS},
  1205. {"__str__", UnicodeTranslateError__str__, METH_O},
  1206. {NULL, NULL}
  1207. };
  1208. PyObject * PyUnicodeTranslateError_Create(
  1209. const Py_UNICODE *object, int length,
  1210. int start, int end, const char *reason)
  1211. {
  1212. return PyObject_CallFunction(PyExc_UnicodeTranslateError, "u#iis",
  1213. object, length, start, end, reason);
  1214. }
  1215. #endif
  1216. /* Exception doc strings */
  1217. PyDoc_STRVAR(AssertionError__doc__, "Assertion failed.");
  1218. PyDoc_STRVAR(LookupError__doc__, "Base class for lookup errors.");
  1219. PyDoc_STRVAR(IndexError__doc__, "Sequence index out of range.");
  1220. PyDoc_STRVAR(KeyError__doc__, "Mapping key not found.");
  1221. PyDoc_STRVAR(ArithmeticError__doc__, "Base class for arithmetic errors.");
  1222. PyDoc_STRVAR(OverflowError__doc__, "Result too large to be represented.");
  1223. PyDoc_STRVAR(ZeroDivisionError__doc__,
  1224. "Second argument to a division or modulo operation was zero.");
  1225. PyDoc_STRVAR(FloatingPointError__doc__, "Floating point operation failed.");
  1226. PyDoc_STRVAR(ValueError__doc__,
  1227. "Inappropriate argument value (of correct type).");
  1228. PyDoc_STRVAR(UnicodeError__doc__, "Unicode related error.");
  1229. #ifdef Py_USING_UNICODE
  1230. PyDoc_STRVAR(UnicodeEncodeError__doc__, "Unicode encoding error.");
  1231. PyDoc_STRVAR(UnicodeDecodeError__doc__, "Unicode decoding error.");
  1232. PyDoc_STRVAR(UnicodeTranslateError__doc__, "Unicode translation error.");
  1233. #endif
  1234. PyDoc_STRVAR(SystemError__doc__,
  1235. "Internal error in the Python interpreter.\n\
  1236. \n\
  1237. Please report this to the Python maintainer, along with the traceback,\n\
  1238. the Python version, and the hardware/OS platform and version.");
  1239. PyDoc_STRVAR(ReferenceError__doc__,
  1240. "Weak ref proxy used after referent went away.");
  1241. PyDoc_STRVAR(MemoryError__doc__, "Out of memory.");
  1242. PyDoc_STRVAR(IndentationError__doc__, "Improper indentation.");
  1243. PyDoc_STRVAR(TabError__doc__, "Improper mixture of spaces and tabs.");
  1244. /* Warning category docstrings */
  1245. PyDoc_STRVAR(Warning__doc__, "Base class for warning categories.");
  1246. PyDoc_STRVAR(UserWarning__doc__,
  1247. "Base class for warnings generated by user code.");
  1248. PyDoc_STRVAR(DeprecationWarning__doc__,
  1249. "Base class for warnings about deprecated features.");
  1250. PyDoc_STRVAR(PendingDeprecationWarning__doc__,
  1251. "Base class for warnings about features which will be deprecated "
  1252. "in the future.");
  1253. PyDoc_STRVAR(SyntaxWarning__doc__,
  1254. "Base class for warnings about dubious syntax.");
  1255. PyDoc_STRVAR(OverflowWarning__doc__,
  1256. "Base class for warnings about numeric overflow. Won't exist in Python 2.5.");
  1257. PyDoc_STRVAR(RuntimeWarning__doc__,
  1258. "Base class for warnings about dubious runtime behavior.");
  1259. PyDoc_STRVAR(FutureWarning__doc__,
  1260. "Base class for warnings about constructs that will change semantically "
  1261. "in the future.");
  1262. /* module global functions */
  1263. static PyMethodDef functions[] = {
  1264. /* Sentinel */
  1265. {NULL, NULL}
  1266. };
  1267. /* Global C API defined exceptions */
  1268. PyObject *PyExc_Exception;
  1269. PyObject *PyExc_StopIteration;
  1270. PyObject *PyExc_StandardError;
  1271. PyObject *PyExc_ArithmeticError;
  1272. PyObject *PyExc_LookupError;
  1273. PyObject *PyExc_AssertionError;
  1274. PyObject *PyExc_AttributeError;
  1275. PyObject *PyExc_EOFError;
  1276. PyObject *PyExc_FloatingPointError;
  1277. PyObject *PyExc_EnvironmentError;
  1278. PyObject *PyExc_IOError;
  1279. PyObject *PyExc_OSError;
  1280. PyObject *PyExc_ImportError;
  1281. PyObject *PyExc_IndexError;
  1282. PyObject *PyExc_KeyError;
  1283. PyObject *PyExc_KeyboardInterrupt;
  1284. PyObject *PyExc_MemoryError;
  1285. PyObject *PyExc_NameError;
  1286. PyObject *PyExc_OverflowError;
  1287. PyObject *PyExc_RuntimeError;
  1288. PyObject *PyExc_NotImplementedError;
  1289. PyObject *PyExc_SyntaxError;
  1290. PyObject *PyExc_IndentationError;
  1291. PyObject *PyExc_TabError;
  1292. PyObject *PyExc_ReferenceError;
  1293. PyObject *PyExc_SystemError;
  1294. PyObject *PyExc_SystemExit;
  1295. PyObject *PyExc_UnboundLocalError;
  1296. PyObject *PyExc_UnicodeError;
  1297. PyObject *PyExc_UnicodeEncodeError;
  1298. PyObject *PyExc_UnicodeDecodeError;
  1299. PyObject *PyExc_UnicodeTranslateError;
  1300. PyObject *PyExc_TypeError;
  1301. PyObject *PyExc_ValueError;
  1302. PyObject *PyExc_ZeroDivisionError;
  1303. #ifdef MS_WINDOWS
  1304. PyObject *PyExc_WindowsError;
  1305. #endif
  1306. #ifdef __VMS
  1307. PyObject *PyExc_VMSError;
  1308. #endif
  1309. /* Pre-computed MemoryError instance. Best to create this as early as
  1310. * possibly and not wait until a MemoryError is actually raised!
  1311. */
  1312. PyObject *PyExc_MemoryErrorInst;
  1313. /* Predefined warning categories */
  1314. PyObject *PyExc_Warning;
  1315. PyObject *PyExc_UserWarning;
  1316. PyObject *PyExc_DeprecationWarning;
  1317. PyObject *PyExc_PendingDeprecationWarning;
  1318. PyObject *PyExc_SyntaxWarning;
  1319. /* PyExc_OverflowWarning should be removed for Python 2.5 */
  1320. PyObject *PyExc_OverflowWarning;
  1321. PyObject *PyExc_RuntimeWarning;
  1322. PyObject *PyExc_FutureWarning;
  1323. /* mapping between exception names and their PyObject ** */
  1324. static struct {
  1325. char *name;
  1326. PyObject **exc;
  1327. PyObject **base; /* NULL == PyExc_StandardError */
  1328. char *docstr;
  1329. PyMethodDef *methods;
  1330. int (*classinit)(PyObject *);
  1331. } exctable[] = {
  1332. /*
  1333. * The first three classes MUST appear in exactly this order
  1334. */
  1335. {"Exception", &PyExc_Exception},
  1336. {"StopIteration", &PyExc_StopIteration, &PyExc_Exception,
  1337. StopIteration__doc__},
  1338. {"StandardError", &PyExc_StandardError, &PyExc_Exception,
  1339. StandardError__doc__},
  1340. {"TypeError", &PyExc_TypeError, 0, TypeError__doc__},
  1341. /*
  1342. * The rest appear in depth-first order of the hierarchy
  1343. */
  1344. {"SystemExit", &PyExc_SystemExit, &PyExc_Exception, SystemExit__doc__,
  1345. SystemExit_methods},
  1346. {"KeyboardInterrupt", &PyExc_KeyboardInterrupt, 0, KeyboardInterrupt__doc__},
  1347. {"ImportError", &PyExc_ImportError, 0, ImportError__doc__},
  1348. {"EnvironmentError", &PyExc_EnvironmentError, 0, EnvironmentError__doc__,
  1349. EnvironmentError_methods},
  1350. {"IOError", &PyExc_IOError, &PyExc_EnvironmentError, IOError__doc__},
  1351. {"OSError", &PyExc_OSError, &PyExc_EnvironmentError, OSError__doc__},
  1352. #ifdef MS_WINDOWS
  1353. {"WindowsError", &PyExc_WindowsError, &PyExc_OSError,
  1354. WindowsError__doc__},
  1355. #endif /* MS_WINDOWS */
  1356. #ifdef __VMS
  1357. {"VMSError", &PyExc_VMSError, &PyExc_OSError,
  1358. VMSError__doc__},
  1359. #endif
  1360. {"EOFError", &PyExc_EOFError, 0, EOFError__doc__},
  1361. {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__},
  1362. {"NotImplementedError", &PyExc_NotImplementedError,
  1363. &PyExc_RuntimeError, NotImplementedError__doc__},
  1364. {"NameError", &PyExc_NameError, 0, NameError__doc__},
  1365. {"UnboundLocalError", &PyExc_UnboundLocalError, &PyExc_NameError,
  1366. UnboundLocalError__doc__},
  1367. {"AttributeError", &PyExc_AttributeError, 0, AttributeError__doc__},
  1368. {"SyntaxError", &PyExc_SyntaxError, 0, SyntaxError__doc__,
  1369. SyntaxError_methods, SyntaxError__classinit__},
  1370. {"IndentationError", &PyExc_IndentationError, &PyExc_SyntaxError,
  1371. IndentationError__doc__},
  1372. {"TabError", &PyExc_TabError, &PyExc_IndentationError,
  1373. TabError__doc__},
  1374. {"AssertionError", &PyExc_AssertionError, 0, AssertionError__doc__},
  1375. {"LookupError", &PyExc_LookupError, 0, LookupError__doc__},
  1376. {"IndexError", &PyExc_IndexError, &PyExc_LookupError,
  1377. IndexError__doc__},
  1378. {"KeyError", &PyExc_KeyError, &PyExc_LookupError,
  1379. KeyError__doc__, KeyError_methods},
  1380. {"ArithmeticError", &PyExc_ArithmeticError, 0, ArithmeticError__doc__},
  1381. {"OverflowError", &PyExc_OverflowError, &PyExc_ArithmeticError,
  1382. OverflowError__doc__},
  1383. {"ZeroDivisionError", &PyExc_ZeroDivisionError, &PyExc_ArithmeticError,
  1384. ZeroDivisionError__doc__},
  1385. {"FloatingPointError", &PyExc_FloatingPointError, &PyExc_ArithmeticError,
  1386. FloatingPointError__doc__},
  1387. {"ValueError", &PyExc_ValueError, 0, ValueError__doc__},
  1388. {"UnicodeError", &PyExc_UnicodeError, &PyExc_ValueError, UnicodeError__doc__},
  1389. #ifdef Py_USING_UNICODE
  1390. {"UnicodeEncodeError", &PyExc_UnicodeEncodeError, &PyExc_UnicodeError,
  1391. UnicodeEncodeError__doc__, UnicodeEncodeError_methods},
  1392. {"UnicodeDecodeError", &PyExc_UnicodeDecodeError, &PyExc_UnicodeError,
  1393. UnicodeDecodeError__doc__, UnicodeDecodeError_methods},
  1394. {"UnicodeTranslateError", &PyExc_UnicodeTranslateError, &PyExc_UnicodeError,
  1395. UnicodeTranslateError__doc__, UnicodeTranslateError_methods},
  1396. #endif
  1397. {"ReferenceError", &PyExc_ReferenceError, 0, ReferenceError__doc__},
  1398. {"SystemError", &PyExc_SystemError, 0, SystemError__doc__},
  1399. {"MemoryError", &PyExc_MemoryError, 0, MemoryError__doc__},
  1400. /* Warning categories */
  1401. {"Warning", &PyExc_Warning, &PyExc_Exception, Warning__doc__},
  1402. {"UserWarning", &PyExc_UserWarning, &PyExc_Warning, UserWarning__doc__},
  1403. {"DeprecationWarning", &PyExc_DeprecationWarning, &PyExc_Warning,
  1404. DeprecationWarning__doc__},
  1405. {"PendingDeprecationWarning", &PyExc_PendingDeprecationWarning, &PyExc_Warning,
  1406. PendingDeprecationWarning__doc__},
  1407. {"SyntaxWarning", &PyExc_SyntaxWarning, &PyExc_Warning, SyntaxWarning__doc__},
  1408. /* OverflowWarning should be removed for Python 2.5 */
  1409. {"OverflowWarning", &PyExc_OverflowWarning, &PyExc_Warning,
  1410. OverflowWarning__doc__},
  1411. {"RuntimeWarning", &PyExc_RuntimeWarning, &PyExc_Warning,
  1412. RuntimeWarning__doc__},
  1413. {"FutureWarning", &PyExc_FutureWarning, &PyExc_Warning,
  1414. FutureWarning__doc__},
  1415. /* Sentinel */
  1416. {NULL}
  1417. };
  1418. void
  1419. _PyExc_Init(void)
  1420. {
  1421. char *modulename = "exceptions";
  1422. int modnamesz = strlen(modulename);
  1423. int i;
  1424. PyObject *me, *mydict, *bltinmod, *bdict, *doc, *args;
  1425. me = Py_InitModule(modulename, functions);
  1426. if (me == NULL)
  1427. goto err;
  1428. mydict = PyModule_GetDict(me);
  1429. if (mydict == NULL)
  1430. goto err;
  1431. bltinmod = PyImport_ImportModule("__builtin__");
  1432. if (bltinmod == NULL)
  1433. goto err;
  1434. bdict = PyModule_GetDict(bltinmod);
  1435. if (bdict == NULL)
  1436. goto err;
  1437. doc = PyString_FromString(module__doc__);
  1438. if (doc == NULL)
  1439. goto err;
  1440. i = PyDict_SetItemString(mydict, "__doc__", doc);
  1441. Py_DECREF(doc);
  1442. if (i < 0) {
  1443. err:
  1444. Py_FatalError("exceptions bootstrapping error.");
  1445. return;
  1446. }
  1447. /* This is the base class of all exceptions, so make it first. */
  1448. if (make_Exception(modulename) ||
  1449. PyDict_SetItemString(mydict, "Exception", PyExc_Exception) ||
  1450. PyDict_SetItemString(bdict, "Exception", PyExc_Exception))
  1451. {
  1452. Py_FatalError("Base class `Exception' could not be created.");
  1453. }
  1454. /* Now we can programmatically create all the remaining exceptions.
  1455. * Remember to start the loop at 1 to skip Exceptions.
  1456. */
  1457. for (i=1; exctable[i].name; i++) {
  1458. int status;
  1459. char *cname = PyMem_NEW(char, modnamesz+strlen(exctable[i].name)+2);
  1460. PyObject *base;
  1461. (void)strcpy(cname, modulename);
  1462. (void)strcat(cname, ".");
  1463. (void)strcat(cname, exctable[i].name);
  1464. if (exctable[i].base == 0)
  1465. base = PyExc_StandardError;
  1466. else
  1467. base = *exctable[i].base;
  1468. status = make_class(exctable[i].exc, base, cname,
  1469. exctable[i].methods,
  1470. exctable[i].docstr);
  1471. PyMem_DEL(cname);
  1472. if (status)
  1473. Py_FatalError("Standard exception classes could not be created.");
  1474. if (exctable[i].classinit) {
  1475. status = (*exctable[i].classinit)(*exctable[i].exc);
  1476. if (status)
  1477. Py_FatalError("An exception class could not be initialized.");
  1478. }
  1479. /* Now insert the class into both this module and the __builtin__
  1480. * module.
  1481. */
  1482. if (PyDict_SetItemString(mydict, exctable[i].name, *exctable[i].exc) ||
  1483. PyDict_SetItemString(bdict, exctable[i].name, *exctable[i].exc))
  1484. {
  1485. Py_FatalError("Module dictionary insertion problem.");
  1486. }
  1487. }
  1488. /* Now we need to pre-allocate a MemoryError instance */
  1489. args = PyTuple_New(0);
  1490. if (!args ||
  1491. !(PyExc_MemoryErrorInst = PyEval_CallObject(PyExc_MemoryError, args)))
  1492. {
  1493. Py_FatalError("Cannot pre-allocate MemoryError instance\n");
  1494. }
  1495. Py_DECREF(args);
  1496. /* We're done with __builtin__ */
  1497. Py_DECREF(bltinmod);
  1498. }
  1499. void
  1500. _PyExc_Fini(void)
  1501. {
  1502. int i;
  1503. Py_XDECREF(PyExc_MemoryErrorInst);
  1504. PyExc_MemoryErrorInst = NULL;
  1505. for (i=0; exctable[i].name; i++) {
  1506. /* clear the class's dictionary, freeing up circular references
  1507. * between the class and its methods.
  1508. */
  1509. PyObject* cdict = PyObject_GetAttrString(*exctable[i].exc, "__dict__");
  1510. PyDict_Clear(cdict);
  1511. Py_DECREF(cdict);
  1512. /* Now decref the exception class */
  1513. Py_XDECREF(*exctable[i].exc);
  1514. *exctable[i].exc = NULL;
  1515. }
  1516. }