core-adapters 0.1.2
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
errors.hpp
Go to the documentation of this file.
1//
2// errors.hpp
3// core-adapters
4//
5// Copyright 2010-2026 Saxon Herschel Nicholls
6//
7
67
68#ifndef snicholls_core_adapters_nanobind_errors_hpp
69#define snicholls_core_adapters_nanobind_errors_hpp
70
71#include <nanobind/nanobind.h>
72
73#include <snicholls/core/result.hpp>
74#include <snicholls/core/traced.hpp>
75
76#include <exception>
77#include <new>
78#include <stdexcept>
79#include <string>
80#include <type_traits>
81#include <utility>
82
83namespace snicholls::python {
84
89class precondition_error : public std::invalid_argument
90{
91public:
93 explicit precondition_error(const std::string& what) : std::invalid_argument(what) {}
94};
95
98class traced_exception : public std::runtime_error
99{
100public:
102 explicit traced_exception(error_report report)
103 : std::runtime_error(report.message), report_(std::move(report))
104 {
105 }
106
108 [[nodiscard]] const error_report& report() const noexcept { return report_; }
109
110private:
111 error_report report_;
112};
113
114namespace detail {
115
116[[noreturn]] inline void throw_precondition(const char* message) { throw precondition_error(message); }
117
118// A class of snicholls_core.errors, imported once and kept for the life of the process (a leaked reference: a static
119// nanobind::object would be destroyed after the interpreter). Falls back to `fallback` when the package is missing.
120inline PyObject* error_class(const char* name, PyObject* fallback) noexcept
121{
122 PyObject* module = PyImport_ImportModule("snicholls_core.errors");
123 if (module == nullptr) {
124 PyErr_Clear();
125 return fallback;
126 }
127 PyObject* cls = PyObject_GetAttrString(module, name);
128 Py_DECREF(module);
129 if (cls == nullptr) {
130 PyErr_Clear();
131 return fallback;
132 }
133 return cls; // leaked on purpose
134}
135
136inline PyObject* precondition_class() noexcept
137{
138 static PyObject* cls = error_class("PreconditionError", PyExc_ValueError);
139 return cls;
140}
141
142inline PyObject* result_class() noexcept
143{
144 static PyObject* cls = error_class("ResultError", PyExc_RuntimeError);
145 return cls;
146}
147
148inline PyObject* traced_class() noexcept
149{
150 static PyObject* cls = error_class("TracedError", PyExc_RuntimeError);
151 return cls;
152}
153
154inline bool set_attr(PyObject* target, const char* name, PyObject* value) noexcept
155{
156 if (value == nullptr)
157 return false;
158 const int status = PyObject_SetAttrString(target, name, value);
159 Py_DECREF(value);
160 return status == 0;
161}
162
163inline PyObject* text(const std::string& s) noexcept
164{
165 return PyUnicode_DecodeUTF8(s.data(), static_cast<Py_ssize_t>(s.size()), "replace");
166}
167
168// TracedError(message) with error, file, line, function, frames, fields and stack set from the report.
169inline void set_traced(const error_report& r) noexcept
170{
171 PyObject* cls = traced_class();
172 PyObject* message = text(r.message);
173 if (message == nullptr)
174 return;
175 PyObject* instance = PyObject_CallFunctionObjArgs(cls, message, nullptr);
176 Py_DECREF(message);
177 if (instance == nullptr)
178 return; // the Python error from the call stands
179 bool ok = set_attr(instance, "error", text(r.error)) && set_attr(instance, "file", text(r.where.file_name())) &&
180 set_attr(instance, "line", PyLong_FromLong(static_cast<long>(r.where.line()))) &&
181 set_attr(instance, "function", text(r.where.function_name())) &&
182 set_attr(instance, "stack", text(r.stack));
183 if (ok) {
184 PyObject* frames = PyList_New(0);
185 for (std::size_t i = 0; ok && frames != nullptr && i < r.frames.size(); ++i) {
186 PyObject* f = text(r.frames[i].message);
187 ok = f != nullptr && PyList_Append(frames, f) == 0;
188 Py_XDECREF(f);
189 }
190 ok = ok && set_attr(instance, "frames", frames);
191 }
192 if (ok) {
193 PyObject* fields = PyDict_New();
194 for (std::size_t i = 0; ok && fields != nullptr && i < r.fields.size(); ++i) {
195 PyObject* v = text(r.fields[i].value);
196 ok = v != nullptr && PyDict_SetItemString(fields, r.fields[i].key.c_str(), v) == 0;
197 Py_XDECREF(v);
198 }
199 ok = ok && set_attr(instance, "fields", fields);
200 }
201 if (!ok) {
202 Py_DECREF(instance);
203 return; // the Python error from building it stands
204 }
205 PyErr_SetObject(cls, instance);
206 Py_DECREF(instance);
207}
208
209// The core-specific part of the mapping; rethrows anything else.
210inline void translate_core(const std::exception_ptr& p, void*)
211{
212 try {
213 std::rethrow_exception(p);
214 } catch (const traced_exception& e) {
215 set_traced(e.report());
216 } catch (const precondition_error& e) {
217 PyErr_SetString(precondition_class(), e.what());
218 } catch (const bad_result_access<void>& e) {
219 PyErr_SetString(result_class(), e.what());
220 }
221}
222
223} // namespace detail
224
229inline void register_exception_translators() { ::nanobind::register_exception_translator(&detail::translate_core); }
230
236inline void require(bool condition, const char* message)
237{
238 if (!condition) [[unlikely]]
239 detail::throw_precondition(message);
240}
241
251template <class E>
252[[noreturn]] void raise_error(const E& e)
253{
254 using T = std::remove_cvref_t<E>;
255 if constexpr (is_traced_v<T>)
256 throw traced_exception(make_error_report(e));
257 else if constexpr (std::is_base_of_v<std::exception, T> && std::is_copy_constructible_v<T>)
258 throw e;
259 else
260 throw bad_result_access<void>(error_text(e));
261}
262
270template <class V, class E>
271decltype(auto) unwrap(result<V, E>&& r)
272{
273 if (r.is_err()) [[unlikely]]
274 raise_error(r.unwrap_err_unchecked());
275 if constexpr (std::is_void_v<V>)
276 return;
277 else
278 return V(std::move(r).unwrap_unchecked());
279}
280
286inline void set_python_error(const std::exception_ptr& p) noexcept
287{
288 try {
289 try {
290 detail::translate_core(p, nullptr);
291 } catch (::nanobind::python_error& e) {
292 e.restore(); // already a Python exception
293 } catch (const std::bad_alloc&) {
294 PyErr_NoMemory();
295 } catch (const std::out_of_range& e) {
296 PyErr_SetString(PyExc_IndexError, e.what());
297 } catch (const std::overflow_error& e) {
298 PyErr_SetString(PyExc_OverflowError, e.what());
299 } catch (const std::invalid_argument& e) {
300 PyErr_SetString(PyExc_ValueError, e.what());
301 } catch (const std::domain_error& e) {
302 PyErr_SetString(PyExc_ValueError, e.what());
303 } catch (const std::length_error& e) {
304 PyErr_SetString(PyExc_ValueError, e.what());
305 } catch (const std::exception& e) {
306 PyErr_SetString(PyExc_RuntimeError, e.what());
307 } catch (...) {
308 PyErr_SetString(PyExc_RuntimeError, "unknown C++ exception");
309 }
310 } catch (...) {
311 PyErr_SetString(PyExc_RuntimeError, "snicholls::python: an exception while translating an exception");
312 }
313}
314
315} // namespace snicholls::python
316
317#endif /* snicholls_core_adapters_nanobind_errors_hpp */
A violated precondition of a bound function: snicholls_core.errors.PreconditionError (a ValueError).
Definition errors.hpp:90
precondition_error(const std::string &what)
Constructs it.
Definition errors.hpp:93
A snicholls::traced<E> error on its way to Python: snicholls_core.errors.TracedError.
Definition errors.hpp:99
traced_exception(error_report report)
Constructs it from a report.
Definition errors.hpp:102
const error_report & report() const noexcept
The report.
Definition errors.hpp:108
decltype(auto) unwrap(result< V, E > &&r)
The value of a result, or raise_error of its error.
Definition errors.hpp:271
void register_exception_translators()
Registers the translators for core's errors with nanobind. Call once in each NB_MODULE body.
Definition errors.hpp:229
void set_python_error(const std::exception_ptr &p) noexcept
Sets the Python error for a C++ exception, by the file's table. For type casters, which return a null...
Definition errors.hpp:286
void raise_error(const E &e)
Throws e as the C++ exception that maps to the right Python class.
Definition errors.hpp:252
void require(bool condition, const char *message)
Throws precondition_error(message) unless condition holds.
Definition errors.hpp:236