PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/module/cpyext/pyerrors.py

https://bitbucket.org/dac_io/pypy
Python | 380 lines | 377 code | 2 blank | 1 comment | 1 complexity | 4247f03e170354f64e437adc674db57f MD5 | raw file
  1. import os
  2. from pypy.rpython.lltypesystem import rffi, lltype
  3. from pypy.interpreter.error import OperationError
  4. from pypy.interpreter import pytraceback
  5. from pypy.module.cpyext.api import cpython_api, CANNOT_FAIL, CONST_STRING
  6. from pypy.module.exceptions.interp_exceptions import W_RuntimeWarning
  7. from pypy.module.cpyext.pyobject import (
  8. PyObject, PyObjectP, make_ref, from_ref, Py_DecRef, borrow_from)
  9. from pypy.module.cpyext.state import State
  10. from pypy.module.cpyext.import_ import PyImport_Import
  11. from pypy.rlib.rposix import get_errno
  12. @cpython_api([PyObject, PyObject], lltype.Void)
  13. def PyErr_SetObject(space, w_type, w_value):
  14. """This function is similar to PyErr_SetString() but lets you specify an
  15. arbitrary Python object for the "value" of the exception."""
  16. state = space.fromcache(State)
  17. state.set_exception(OperationError(w_type, w_value))
  18. @cpython_api([PyObject, CONST_STRING], lltype.Void)
  19. def PyErr_SetString(space, w_type, message_ptr):
  20. message = rffi.charp2str(message_ptr)
  21. PyErr_SetObject(space, w_type, space.wrap(message))
  22. @cpython_api([PyObject], lltype.Void, error=CANNOT_FAIL)
  23. def PyErr_SetNone(space, w_type):
  24. """This is a shorthand for PyErr_SetObject(type, Py_None)."""
  25. PyErr_SetObject(space, w_type, space.w_None)
  26. @cpython_api([], PyObject)
  27. def PyErr_Occurred(space):
  28. state = space.fromcache(State)
  29. if state.operror is None:
  30. return None
  31. return borrow_from(None, state.operror.w_type)
  32. @cpython_api([], lltype.Void)
  33. def PyErr_Clear(space):
  34. state = space.fromcache(State)
  35. state.clear_exception()
  36. @cpython_api([PyObject], PyObject)
  37. def PyExceptionInstance_Class(space, w_obj):
  38. return space.type(w_obj)
  39. @cpython_api([PyObjectP, PyObjectP, PyObjectP], lltype.Void)
  40. def PyErr_Fetch(space, ptype, pvalue, ptraceback):
  41. """Retrieve the error indicator into three variables whose addresses are passed.
  42. If the error indicator is not set, set all three variables to NULL. If it is
  43. set, it will be cleared and you own a reference to each object retrieved. The
  44. value and traceback object may be NULL even when the type object is not.
  45. This function is normally only used by code that needs to handle exceptions or
  46. by code that needs to save and restore the error indicator temporarily."""
  47. state = space.fromcache(State)
  48. operror = state.clear_exception()
  49. if operror:
  50. ptype[0] = make_ref(space, operror.w_type)
  51. pvalue[0] = make_ref(space, operror.get_w_value(space))
  52. ptraceback[0] = make_ref(space, space.wrap(operror.get_traceback()))
  53. else:
  54. ptype[0] = lltype.nullptr(PyObject.TO)
  55. pvalue[0] = lltype.nullptr(PyObject.TO)
  56. ptraceback[0] = lltype.nullptr(PyObject.TO)
  57. @cpython_api([PyObject, PyObject, PyObject], lltype.Void)
  58. def PyErr_Restore(space, w_type, w_value, w_traceback):
  59. """Set the error indicator from the three objects. If the error indicator is
  60. already set, it is cleared first. If the objects are NULL, the error
  61. indicator is cleared. Do not pass a NULL type and non-NULL value or
  62. traceback. The exception type should be a class. Do not pass an invalid
  63. exception type or value. (Violating these rules will cause subtle problems
  64. later.) This call takes away a reference to each object: you must own a
  65. reference to each object before the call and after the call you no longer own
  66. these references. (If you don't understand this, don't use this function. I
  67. warned you.)
  68. This function is normally only used by code that needs to save and restore the
  69. error indicator temporarily; use PyErr_Fetch() to save the current
  70. exception state."""
  71. state = space.fromcache(State)
  72. if w_type is None:
  73. state.clear_exception()
  74. return
  75. state.set_exception(OperationError(w_type, w_value))
  76. Py_DecRef(space, w_type)
  77. Py_DecRef(space, w_value)
  78. Py_DecRef(space, w_traceback)
  79. @cpython_api([PyObjectP, PyObjectP, PyObjectP], lltype.Void)
  80. def PyErr_NormalizeException(space, exc_p, val_p, tb_p):
  81. """Under certain circumstances, the values returned by PyErr_Fetch() below
  82. can be "unnormalized", meaning that *exc is a class object but *val is
  83. not an instance of the same class. This function can be used to instantiate
  84. the class in that case. If the values are already normalized, nothing happens.
  85. The delayed normalization is implemented to improve performance."""
  86. operr = OperationError(from_ref(space, exc_p[0]),
  87. from_ref(space, val_p[0]))
  88. operr.normalize_exception(space)
  89. Py_DecRef(space, exc_p[0])
  90. Py_DecRef(space, val_p[0])
  91. exc_p[0] = make_ref(space, operr.w_type)
  92. val_p[0] = make_ref(space, operr.get_w_value(space))
  93. @cpython_api([], lltype.Void)
  94. def PyErr_BadArgument(space):
  95. """This is a shorthand for PyErr_SetString(PyExc_TypeError, message), where
  96. message indicates that a built-in operation was invoked with an illegal
  97. argument. It is mostly for internal use."""
  98. raise OperationError(space.w_TypeError,
  99. space.wrap("bad argument type for built-in operation"))
  100. @cpython_api([], lltype.Void)
  101. def PyErr_BadInternalCall(space):
  102. raise OperationError(space.w_SystemError, space.wrap("Bad internal call!"))
  103. @cpython_api([], PyObject, error=CANNOT_FAIL)
  104. def PyErr_NoMemory(space):
  105. """This is a shorthand for PyErr_SetNone(PyExc_MemoryError); it returns NULL
  106. so an object allocation function can write return PyErr_NoMemory(); when it
  107. runs out of memory.
  108. Return value: always NULL."""
  109. PyErr_SetNone(space, space.w_MemoryError)
  110. @cpython_api([PyObject], PyObject)
  111. def PyErr_SetFromErrno(space, w_type):
  112. """
  113. This is a convenience function to raise an exception when a C library function
  114. has returned an error and set the C variable errno. It constructs a
  115. tuple object whose first item is the integer errno value and whose
  116. second item is the corresponding error message (gotten from strerror()),
  117. and then calls PyErr_SetObject(type, object). On Unix, when the
  118. errno value is EINTR, indicating an interrupted system call,
  119. this calls PyErr_CheckSignals(), and if that set the error indicator,
  120. leaves it set to that. The function always returns NULL, so a wrapper
  121. function around a system call can write return PyErr_SetFromErrno(type);
  122. when the system call returns an error.
  123. Return value: always NULL."""
  124. PyErr_SetFromErrnoWithFilename(space, w_type,
  125. lltype.nullptr(rffi.CCHARP.TO))
  126. @cpython_api([PyObject, rffi.CCHARP], PyObject)
  127. def PyErr_SetFromErrnoWithFilename(space, w_type, llfilename):
  128. """Similar to PyErr_SetFromErrno(), with the additional behavior that if
  129. filename is not NULL, it is passed to the constructor of type as a third
  130. parameter. In the case of exceptions such as IOError and OSError,
  131. this is used to define the filename attribute of the exception instance.
  132. Return value: always NULL."""
  133. # XXX Doesn't actually do anything with PyErr_CheckSignals.
  134. errno = get_errno()
  135. msg = os.strerror(errno)
  136. if llfilename:
  137. w_filename = rffi.charp2str(llfilename)
  138. w_error = space.call_function(w_type,
  139. space.wrap(errno),
  140. space.wrap(msg),
  141. space.wrap(w_filename))
  142. else:
  143. w_error = space.call_function(w_type,
  144. space.wrap(errno),
  145. space.wrap(msg))
  146. raise OperationError(w_type, w_error)
  147. @cpython_api([], rffi.INT_real, error=-1)
  148. def PyErr_CheckSignals(space):
  149. """
  150. This function interacts with Python's signal handling. It checks whether a
  151. signal has been sent to the processes and if so, invokes the corresponding
  152. signal handler. If the signal module is supported, this can invoke a
  153. signal handler written in Python. In all cases, the default effect for
  154. SIGINT is to raise the KeyboardInterrupt exception. If an
  155. exception is raised the error indicator is set and the function returns -1;
  156. otherwise the function returns 0. The error indicator may or may not be
  157. cleared if it was previously set."""
  158. # XXX implement me
  159. return 0
  160. @cpython_api([PyObject, PyObject], rffi.INT_real, error=CANNOT_FAIL)
  161. def PyErr_GivenExceptionMatches(space, w_given, w_exc):
  162. """Return true if the given exception matches the exception in exc. If
  163. exc is a class object, this also returns true when given is an instance
  164. of a subclass. If exc is a tuple, all exceptions in the tuple (and
  165. recursively in subtuples) are searched for a match."""
  166. if (space.is_true(space.isinstance(w_given, space.w_BaseException)) or
  167. space.is_oldstyle_instance(w_given)):
  168. w_given_type = space.exception_getclass(w_given)
  169. else:
  170. w_given_type = w_given
  171. return space.exception_match(w_given_type, w_exc)
  172. @cpython_api([PyObject], rffi.INT_real, error=CANNOT_FAIL)
  173. def PyErr_ExceptionMatches(space, w_exc):
  174. """Equivalent to PyErr_GivenExceptionMatches(PyErr_Occurred(), exc). This
  175. should only be called when an exception is actually set; a memory access
  176. violation will occur if no exception has been raised."""
  177. w_type = PyErr_Occurred(space)
  178. return PyErr_GivenExceptionMatches(space, w_type, w_exc)
  179. @cpython_api([PyObject, CONST_STRING, rffi.INT_real], rffi.INT_real, error=-1)
  180. def PyErr_WarnEx(space, w_category, message_ptr, stacklevel):
  181. """Issue a warning message. The category argument is a warning category (see
  182. below) or NULL; the message argument is a message string. stacklevel is a
  183. positive number giving a number of stack frames; the warning will be issued from
  184. the currently executing line of code in that stack frame. A stacklevel of 1
  185. is the function calling PyErr_WarnEx(), 2 is the function above that,
  186. and so forth.
  187. This function normally prints a warning message to sys.stderr; however, it is
  188. also possible that the user has specified that warnings are to be turned into
  189. errors, and in that case this will raise an exception. It is also possible that
  190. the function raises an exception because of a problem with the warning machinery
  191. (the implementation imports the warnings module to do the heavy lifting).
  192. The return value is 0 if no exception is raised, or -1 if an exception
  193. is raised. (It is not possible to determine whether a warning message is
  194. actually printed, nor what the reason is for the exception; this is
  195. intentional.) If an exception is raised, the caller should do its normal
  196. exception handling (for example, Py_DECREF() owned references and return
  197. an error value).
  198. Warning categories must be subclasses of Warning; the default warning
  199. category is RuntimeWarning. The standard Python warning categories are
  200. available as global variables whose names are PyExc_ followed by the Python
  201. exception name. These have the type PyObject*; they are all class
  202. objects. Their names are PyExc_Warning, PyExc_UserWarning,
  203. PyExc_UnicodeWarning, PyExc_DeprecationWarning,
  204. PyExc_SyntaxWarning, PyExc_RuntimeWarning, and
  205. PyExc_FutureWarning. PyExc_Warning is a subclass of
  206. PyExc_Exception; the other warning categories are subclasses of
  207. PyExc_Warning.
  208. For information about warning control, see the documentation for the
  209. warnings module and the -W option in the command line
  210. documentation. There is no C API for warning control."""
  211. if w_category is None:
  212. w_category = space.w_None
  213. w_message = space.wrap(rffi.charp2str(message_ptr))
  214. w_stacklevel = space.wrap(rffi.cast(lltype.Signed, stacklevel))
  215. w_module = PyImport_Import(space, space.wrap("warnings"))
  216. w_warn = space.getattr(w_module, space.wrap("warn"))
  217. space.call_function(w_warn, w_message, w_category, w_stacklevel)
  218. return 0
  219. @cpython_api([PyObject, CONST_STRING], rffi.INT_real, error=-1)
  220. def PyErr_Warn(space, w_category, message):
  221. """Issue a warning message. The category argument is a warning category (see
  222. below) or NULL; the message argument is a message string. The warning will
  223. appear to be issued from the function calling PyErr_Warn(), equivalent to
  224. calling PyErr_WarnEx() with a stacklevel of 1.
  225. Deprecated; use PyErr_WarnEx() instead."""
  226. return PyErr_WarnEx(space, w_category, message, 1)
  227. @cpython_api([rffi.INT_real], lltype.Void)
  228. def PyErr_PrintEx(space, set_sys_last_vars):
  229. """Print a standard traceback to sys.stderr and clear the error indicator.
  230. Call this function only when the error indicator is set. (Otherwise it will
  231. cause a fatal error!)
  232. If set_sys_last_vars is nonzero, the variables sys.last_type,
  233. sys.last_value and sys.last_traceback will be set to the
  234. type, value and traceback of the printed exception, respectively."""
  235. if not PyErr_Occurred(space):
  236. PyErr_BadInternalCall(space)
  237. state = space.fromcache(State)
  238. operror = state.clear_exception()
  239. w_type = operror.w_type
  240. w_value = operror.get_w_value(space)
  241. w_tb = space.wrap(operror.get_traceback())
  242. if rffi.cast(lltype.Signed, set_sys_last_vars):
  243. space.sys.setdictvalue(space, "last_type", w_type)
  244. space.sys.setdictvalue(space, "last_value", w_value)
  245. space.sys.setdictvalue(space, "last_traceback", w_tb)
  246. space.call_function(space.sys.get("excepthook"),
  247. w_type, w_value, w_tb)
  248. @cpython_api([], lltype.Void)
  249. def PyErr_Print(space):
  250. """Alias for PyErr_PrintEx(1)."""
  251. PyErr_PrintEx(space, 1)
  252. @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
  253. def PyTraceBack_Print(space, w_tb, w_file):
  254. space.call_method(w_file, "write", space.wrap(
  255. 'Traceback (most recent call last):\n'))
  256. w_traceback = space.call_method(space.builtin, '__import__',
  257. space.wrap("traceback"))
  258. space.call_method(w_traceback, "print_tb", w_tb, space.w_None, w_file)
  259. return 0
  260. @cpython_api([PyObject], lltype.Void)
  261. def PyErr_WriteUnraisable(space, w_where):
  262. """This utility function prints a warning message to sys.stderr when an
  263. exception has been set but it is impossible for the interpreter to actually
  264. raise the exception. It is used, for example, when an exception occurs in
  265. an __del__() method.
  266. The function is called with a single argument obj that identifies the
  267. context in which the unraisable exception occurred. The repr of obj will be
  268. printed in the warning message."""
  269. state = space.fromcache(State)
  270. operror = state.clear_exception()
  271. if operror:
  272. operror.write_unraisable(space, space.str_w(space.repr(w_where)))
  273. @cpython_api([], lltype.Void)
  274. def PyErr_SetInterrupt(space):
  275. """This function simulates the effect of a SIGINT signal arriving --- the
  276. next time PyErr_CheckSignals() is called, KeyboardInterrupt will be raised.
  277. It may be called without holding the interpreter lock."""
  278. space.check_signal_action.set_interrupt()
  279. @cpython_api([PyObjectP, PyObjectP, PyObjectP], lltype.Void)
  280. def PyErr_GetExcInfo(space, ptype, pvalue, ptraceback):
  281. """---Cython extension---
  282. Retrieve the exception info, as known from ``sys.exc_info()``. This
  283. refers to an exception that was already caught, not to an exception
  284. that was freshly raised. Returns new references for the three
  285. objects, any of which may be *NULL*. Does not modify the exception
  286. info state.
  287. .. note::
  288. This function is not normally used by code that wants to handle
  289. exceptions. Rather, it can be used when code needs to save and
  290. restore the exception state temporarily. Use
  291. :c:func:`PyErr_SetExcInfo` to restore or clear the exception
  292. state.
  293. """
  294. ec = space.getexecutioncontext()
  295. operror = ec.sys_exc_info()
  296. if operror:
  297. ptype[0] = make_ref(space, operror.w_type)
  298. pvalue[0] = make_ref(space, operror.get_w_value(space))
  299. ptraceback[0] = make_ref(space, space.wrap(operror.get_traceback()))
  300. else:
  301. ptype[0] = lltype.nullptr(PyObject.TO)
  302. pvalue[0] = lltype.nullptr(PyObject.TO)
  303. ptraceback[0] = lltype.nullptr(PyObject.TO)
  304. @cpython_api([PyObject, PyObject, PyObject], lltype.Void)
  305. def PyErr_SetExcInfo(space, w_type, w_value, w_traceback):
  306. """---Cython extension---
  307. Set the exception info, as known from ``sys.exc_info()``. This refers
  308. to an exception that was already caught, not to an exception that was
  309. freshly raised. This function steals the references of the arguments.
  310. To clear the exception state, pass *NULL* for all three arguments.
  311. For general rules about the three arguments, see :c:func:`PyErr_Restore`.
  312. .. note::
  313. This function is not normally used by code that wants to handle
  314. exceptions. Rather, it can be used when code needs to save and
  315. restore the exception state temporarily. Use
  316. :c:func:`PyErr_GetExcInfo` to read the exception state.
  317. """
  318. if w_value is None or space.is_w(w_value, space.w_None):
  319. operror = None
  320. else:
  321. tb = None
  322. if w_traceback is not None:
  323. try:
  324. tb = pytraceback.check_traceback(space, w_traceback, '?')
  325. except OperationError: # catch and ignore bogus objects
  326. pass
  327. operror = OperationError(w_type, w_value, tb)
  328. #
  329. ec = space.getexecutioncontext()
  330. ec.set_sys_exc_info(operror)
  331. Py_DecRef(space, w_type)
  332. Py_DecRef(space, w_value)
  333. Py_DecRef(space, w_traceback)