|
| 1 | +// Copyright (c) 2022 The pybind Community. |
| 2 | +// All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +#pragma once |
| 6 | + |
| 7 | +#include "pybind11.h" |
| 8 | + |
| 9 | +#include <type_traits> |
| 10 | + |
| 11 | +PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) |
| 12 | + |
| 13 | +/// Conversions between Python's native (stdlib) enum types and C++ enums. |
| 14 | +template <typename Type> |
| 15 | +class native_enum { |
| 16 | +public: |
| 17 | + using Underlying = typename std::underlying_type<Type>::type; |
| 18 | + // Scalar is the integer representation of underlying type |
| 19 | + using Scalar = detail::conditional_t<detail::any_of<detail::is_std_char_type<Underlying>, |
| 20 | + std::is_same<Underlying, bool>>::value, |
| 21 | + detail::equivalent_integer_t<Underlying>, |
| 22 | + Underlying>; |
| 23 | + |
| 24 | + template <typename... Extra> |
| 25 | + native_enum(const handle &scope, const char *name, const Extra &.../*extra*/) |
| 26 | + : m_scope(reinterpret_borrow<object>(scope)), m_name(name) { |
| 27 | + constexpr bool is_arithmetic = detail::any_of<std::is_same<arithmetic, Extra>...>::value; |
| 28 | + constexpr bool is_convertible = std::is_convertible<Type, Underlying>::value; |
| 29 | + if (is_arithmetic || is_convertible) { |
| 30 | + // IGNORED. |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + /// Export enumeration entries into the parent scope |
| 35 | + native_enum &export_values() { return *this; } |
| 36 | + |
| 37 | + /// Add an enumeration entry |
| 38 | + native_enum &value(char const *name, Type value, const char *doc = nullptr) { |
| 39 | + if (doc) { |
| 40 | + // IGNORED. |
| 41 | + } |
| 42 | + m_members.append(make_tuple(name, static_cast<Scalar>(value))); |
| 43 | + return *this; |
| 44 | + } |
| 45 | + |
| 46 | + native_enum(const native_enum &) = delete; |
| 47 | + native_enum &operator=(const native_enum &) = delete; |
| 48 | + |
| 49 | + ~native_enum() { |
| 50 | + // Any exception here will terminate the process. |
| 51 | + auto enum_module = module_::import("enum"); |
| 52 | + auto int_enum = enum_module.attr("IntEnum"); |
| 53 | + auto int_enum_color = int_enum(m_name, m_members); |
| 54 | + int_enum_color.attr("__module__") = m_scope; |
| 55 | + m_scope.attr(m_name) = int_enum_color; |
| 56 | + // Intentionally leak Python reference. |
| 57 | + detail::get_internals().native_enum_types[std::type_index(typeid(Type))] |
| 58 | + = int_enum_color.release().ptr(); |
| 59 | + } |
| 60 | + |
| 61 | +private: |
| 62 | + object m_scope; |
| 63 | + str m_name; |
| 64 | + list m_members; |
| 65 | +}; |
| 66 | + |
| 67 | +PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE) |
0 commit comments