1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
|
/**************************************************************************
* *
* Regina - A Normal Surface Theory Calculator *
* Python Interface *
* *
* Copyright (c) 1999-2025, Ben Burton *
* For further details contact Ben Burton (bab@debian.org). *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* As an exception, when this program is distributed through (i) the *
* App Store by Apple Inc.; (ii) the Mac App Store by Apple Inc.; or *
* (iii) Google Play by Google Inc., then that store may impose any *
* digital rights management, device limits and/or redistribution *
* restrictions that are required by its terms of service. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
**************************************************************************/
/*! \file python/helpers/exception.h
* \brief Assists with wrapping Regina's exception classes.
*
* This header is _not_ included automatically by python/helpers.h.
* If you need it, you will need to include it yourself.
*/
#include <pybind11/pybind11.h>
#if REGINA_PYBIND11_VERSION == 3
#include <pybind11/subinterpreter.h>
#include <mutex>
#endif
#include "utilities/exception.h"
#include "../helpers/docstrings.h"
namespace regina::python {
#if REGINA_PYBIND11_VERSION == 3
/**
* For a single C++ exception type, holds a corresponding Python exception
* type for each subinterpreter.
*
* All insertion and lookup operations are thread-safe.
*/
class ExceptionCache {
private:
std::map<int64_t, PyObject*> cache_;
/**< A map from subinterpreter IDs to Python exception types. */
std::mutex mutex_;
/**< Protects cache_. */
public:
ExceptionCache() = default;
void insert(PyObject* exc) {
int64_t id = pybind11::subinterpreter::current().id();
std::scoped_lock lock(mutex_);
auto result = cache_.emplace(id, exc);
if (! result.second) {
// An exception is already registered for this subinterpreter.
// This should only happen if regina's module was loaded,
// unloaded, and is now being loaded again. We definitely
// want the new value -- the old value is a stale pointer
// which we can safely discard.
result.first->second = exc;
}
}
PyObject* lookup() {
// This function is non-const because we need to lock mutex_.
int64_t id = pybind11::subinterpreter::current().id();
std::scoped_lock lock(mutex_);
auto it = cache_.find(id);
return (it == cache_.end() ? nullptr : it->second);
}
};
#endif
/**
* Adds Python bindings for one of Regina's C++ exception types.
*
* This routine will create a corresponding Python exception type (using
* PyExc_RuntimeError as its base), and will register a translator between
* the two.
*
* Conceptually, this does a similar job to `pybind11::register_exception()`;
* however, it is also safe to use with subinterpreters (which, as of
* pybind11 3.0.0rc3, `pybind11::register_exception()` is not).
*/
template <typename ReginaExceptionType>
void registerReginaException(pybind11::module_& m, const char* className,
const char* docstring) {
#if REGINA_PYBIND11_VERSION == 3
// In pybind11 v3 (at least in 3.0.0rc3), the implementation of
// register_exception() uses a global singleton Python exception object,
// which breaks things when we load the module multiple times in different
// subinterpreters. We will need to implement things manually ourselves,
// with a different Python exception object for each subinterpreter.
//
// TODO: This code does come with a small memory leak, in that once a
// subinterpreter is destroyed, the corresponding entry in cache is not
// removed (although the Python exception type should be destroyed).
// For now, we live with this memory leak: it is only relevant when using
// subinterpreters in the GUI, and these are created manually by the user
// when opening a new python console -- this means there should never be
// so many that this becomes a serious problem.
static ExceptionCache cache;
// The following exception type should live for only as long as the module
// is loaded, since it is the reference in m.__dict__ that keeps it alive
// on the python side. In our own cache we just keep a borrowed reference.
pybind11::exception<ReginaExceptionType> exc(m, className, docstring,
PyExc_RuntimeError);
cache.insert(exc.ptr());
pybind11::register_exception_translator([](std::exception_ptr p) {
if (!p) {
return;
}
try {
std::rethrow_exception(p);
} catch (const ReginaExceptionType &e) {
if (PyObject* exc = cache.lookup())
PyErr_SetString(exc, e.what());
else {
// This should never happen. But.. just in case, translate
// this to a standard python RuntimeError instead.
PyErr_SetString(PyExc_RuntimeError, e.what());
}
}
});
#elif REGINA_PYBIND11_VERSION == 2
// pybind11 v2 does not support subinterpreters properly; however,
// register_exception() does appear to work perfectly fine with the
// subinterpreter hacks that we are using.
pybind11::register_exception<ReginaExceptionType>(m, className,
PyExc_RuntimeError).doc() = docstring;
#else
#error "Unsupported pybind11 version"
#endif
}
} // namespace regina::python
|