This is an automated email from the ASF dual-hosted git repository.
cyx-6 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tvm-ffi.git
The following commit(s) were added to refs/heads/main by this push:
new 95749413 [FEAT] Add typed enum attribute map lookup (#977)
95749413 is described below
commit 9574941391996aeb4001a7cdc4088e15fea56aff
Author: Tianqi Chen <[email protected]>
AuthorDate: Mon Nov 16 04:44:24 2026 -0500
[FEAT] Add typed enum attribute map lookup (#977)
Add `reflection::EnumAttrMap<EnumClsObj, T>` and
`GetEnumAttrMap<EnumClsObj>(AttrKey<T>)` alongside `EnumDef`. The
factory resolves the enum object type internally and deduces the
attribute value type from its key.
Maps retain the shared registry dictionary for typed lookup by enum
singleton identity. Missing columns throw; missing or None entries
return `std::nullopt`, and `AttrKey::ValueFrom` checks present values.
Later registrations and attribute updates remain visible.
---
include/tvm/ffi/reflection/enum_def.h | 76 +++++++++++++++++++++++++++++++++++
tests/cpp/test_reflection.cc | 14 +++++++
2 files changed, 90 insertions(+)
diff --git a/include/tvm/ffi/reflection/enum_def.h
b/include/tvm/ffi/reflection/enum_def.h
index 0dfbcff5..996327e5 100644
--- a/include/tvm/ffi/reflection/enum_def.h
+++ b/include/tvm/ffi/reflection/enum_def.h
@@ -37,6 +37,7 @@
#include <tvm/ffi/string.h>
#include <cstdint>
+#include <optional>
#include <type_traits>
#include <utility>
@@ -175,6 +176,81 @@ class EnumDef : public ReflectionDefBase {
Enum instance_{UnsafeInit{}};
};
+/*!
+ * \brief A typed enum attribute map indexed by singleton identity.
+ *
+ * Construction resolves an existing column once. Like TypeAttrColumn, it
throws
+ * if the column is missing; construct it after the attribute is registered.
+ * The shared column reflects subsequent EnumDef::set_attr calls, including new
+ * entries and updates. Registration must not run concurrently with lookups.
+ *
+ * \tparam EnumClsObj An Object subclass deriving from EnumObj.
+ * \tparam T The attribute value type, extracted strictly with
AttrKey::ValueFrom.
+ * \sa GetEnumAttrMap
+ */
+template <typename EnumClsObj, typename T>
+class EnumAttrMap {
+ static_assert(std::is_base_of_v<EnumObj, EnumClsObj>, "EnumClsObj must
derive from EnumObj");
+
+ public:
+ /*!
+ * \brief Resolve an enum type's existing attribute column using a typed key.
+ * \param key The attribute key.
+ * \throws Error if the enum state or attribute column is missing.
+ */
+ explicit EnumAttrMap(AttrKey<T> key) : column_(GetColumn(key)), key_(key) {}
+
+ /*!
+ * \brief Look up an attribute by enum singleton identity.
+ * \param instance The enum singleton; names and integer indices are not
used.
+ * \return The typed value, or std::nullopt for a missing or None entry.
+ * \throws Error if a present value has the wrong type. No fallback
conversion is run.
+ * \note Borrowed results remain valid only while the stored value remains
alive.
+ */
+ std::optional<T> operator[](const Enum& instance) const {
+ if (auto value = column_.Get(instance)) return key_.ValueFrom(*value);
+ return std::nullopt;
+ }
+
+ private:
+ static Dict<ObjectRef, Any> GetColumn(AttrKey<T> key) {
+ int32_t type_index = EnumClsObj::_GetOrAllocRuntimeTypeIndex();
+ TypeAttrColumn states(type_attr::kEnumState);
+ AnyView value = states[type_index];
+ if (value != nullptr) {
+ if (value.type_index() != EnumStateObj::_GetOrAllocRuntimeTypeIndex()) {
+ TVM_FFI_THROW(TypeError) << "Expected `" << EnumStateObj::_type_key
+ << "` in enum state column, but got `" <<
value.GetTypeKey()
+ << "`";
+ }
+ // Inline type indices may not be initialized yet during static
registration.
+ const auto* state = static_cast<const
EnumStateObj*>(value.cast<ObjectRef>().get());
+ if (auto column = state->attrs.Get(String(key.name))) {
+ return *column;
+ }
+ }
+ TVM_FFI_THROW(RuntimeError) << "Cannot find enum attribute " << key.name
<< " for type `"
+ << TypeIndexToTypeKey(type_index) << "`";
+ TVM_FFI_UNREACHABLE();
+ }
+
+ Dict<ObjectRef, Any> column_;
+ AttrKey<T> key_;
+};
+
+/*!
+ * \brief Resolve a typed enum attribute map, deducing the value type from its
key.
+ * \tparam EnumClsObj An Object subclass deriving from EnumObj.
+ * \tparam T The attribute value type.
+ * \param key The attribute key.
+ * \return The attribute map for the enum type.
+ * \throws Error if the enum state or attribute column is missing.
+ */
+template <typename EnumClsObj, typename T>
+EnumAttrMap<EnumClsObj, T> GetEnumAttrMap(AttrKey<T> key) {
+ return EnumAttrMap<EnumClsObj, T>(key);
+}
+
} // namespace reflection
} // namespace ffi
} // namespace tvm
diff --git a/tests/cpp/test_reflection.cc b/tests/cpp/test_reflection.cc
index f507b48a..08086851 100644
--- a/tests/cpp/test_reflection.cc
+++ b/tests/cpp/test_reflection.cc
@@ -76,6 +76,11 @@ class QueryEnumObj : public EnumObj {
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("test.QueryEnum", QueryEnumObj, EnumObj);
};
+class AttrEnumObj : public EnumObj {
+ public:
+ TVM_FFI_DECLARE_OBJECT_INFO_FINAL("test.AttrEnum", AttrEnumObj, EnumObj);
+};
+
TVM_FFI_STATIC_INIT_BLOCK() {
namespace refl = tvm::ffi::reflection;
@@ -151,6 +156,15 @@ TEST(Reflection, EnumIsDefined) {
EnumObj::_GetByIntIndex<QueryEnumObj>(1)));
}
+TEST(Reflection, EnumAttrMap) {
+ constexpr reflection::AttrKey<int64_t> kCost{"cost"};
+ reflection::EnumDef<AttrEnumObj>("Alpha").set_attr(kCost, 7);
+ reflection::EnumDef<AttrEnumObj>("Beta"); // NOLINT(bugprone-unused-raii)
+ const auto costs = reflection::GetEnumAttrMap<AttrEnumObj>(kCost);
+ EXPECT_EQ(costs[EnumObj::_GetByStrIndex<AttrEnumObj>("Alpha")], 7);
+
EXPECT_FALSE(costs[EnumObj::_GetByStrIndex<AttrEnumObj>("Beta")].has_value());
+}
+
TEST(Reflection, FieldGetter) {
ObjectRef a = TInt(10);
reflection::FieldGetter getter("test.Int", "value");