Skip to main content

tvm_ffi/
enum_ref.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Enums shared across languages: each value is a named singleton of an
21//! object type whose parent is [`EnumObj`]. [`EnumRef`] looks values up;
22//! [`reflection::EnumDef`](crate::reflection::EnumDef) registers them.
23
24use crate::derive::Object;
25use crate::object::{Object, ObjectCore, ObjectRefCore};
26use crate::reflection::EnumAttrMap;
27use crate::reflection::enum_def::{any_into, dict_get, enum_state};
28use crate::type_traits::AnyCompatible;
29use crate::{AnyView, Error, Result, String, VALUE_ERROR};
30
31/// The object behind every enum value: its name and the index the registry
32/// assigned it. An enum type's object embeds it as its parent,
33/// `base_: EnumObj`.
34#[repr(C)]
35#[derive(Object)]
36#[object(type_key = "ffi.Enum", immutable)]
37pub struct EnumObj {
38    base_: Object,
39    // The registration order, which can differ between processes, so values
40    // are identified by name only.
41    #[allow(dead_code)]
42    index: i64,
43    name: String,
44}
45
46impl EnumObj {
47    pub(crate) fn new(index: i64, name: &str) -> Self {
48        Self {
49            base_: Object::new(),
50            index,
51            name: String::from(name),
52        }
53    }
54}
55
56/// A reference to an enum value: one named singleton of an enum type,
57/// registered once and shared with every language.
58///
59/// [`get`](Self::get) looks a value up by name. Each name has one value, so
60/// equality is identity: compare values with
61/// [`same_as`](ObjectRefCore::same_as).
62/// [`EnumDef`](crate::reflection::EnumDef) registers values and their
63/// attributes, and [`attr_map`](Self::attr_map) reads an attribute.
64///
65/// The stub generator implements it for the enum types it binds. A
66/// hand-written reference implements it when its object's parent is
67/// [`EnumObj`].
68///
69/// # Examples
70///
71/// ```standalone_crate
72/// use tvm_ffi::derive::{Object, ObjectRef};
73/// use tvm_ffi::reflection::EnumDef;
74/// use tvm_ffi::{EnumRef, ObjectArc, ObjectRefCore};
75/// use tvm_ffi::enum_ref::EnumObj;
76///
77/// #[repr(C)]
78/// #[derive(Object)]
79/// #[object(type_key = "my_ext.Color", register, final, immutable)]
80/// pub struct ColorObj {
81///     base_: EnumObj,
82/// }
83///
84/// #[derive(Clone, ObjectRef)]
85/// pub struct Color {
86///     data: ObjectArc<ColorObj>,
87/// }
88///
89/// impl EnumRef for Color {}
90///
91/// EnumDef::<Color>::new("red")?;
92///
93/// let red = Color::get("red")?;
94/// assert_eq!(red.name(), "red");
95/// assert!(red.same_as(&Color::get("red")?));
96/// # Ok::<(), tvm_ffi::Error>(())
97/// ```
98pub trait EnumRef: ObjectRefCore {
99    /// Look up the value registered as `name`.
100    ///
101    /// # Arguments
102    ///
103    /// * `name` - The name of the value.
104    ///
105    /// # Returns
106    ///
107    /// The value, the same object on every call.
108    ///
109    /// # Errors
110    ///
111    /// Returns a `ValueError` if the enum type has no value named `name`.
112    fn get(name: &str) -> Result<Self> {
113        let key = String::from(name);
114        let found = match enum_state(Self::ContainerType::type_index())? {
115            Some(state) => dict_get(AnyView::from(&state.indexes), AnyView::from(&key))?,
116            None => None,
117        };
118        let Some(value) = found else {
119            return Err(Error::new(
120                VALUE_ERROR,
121                &format!(
122                    "Enum `{}` has no value named `{name}`",
123                    Self::ContainerType::TYPE_KEY
124                ),
125            ));
126        };
127        any_into(value)
128    }
129
130    /// The name of the value, unique within its enum type.
131    ///
132    /// # Panics
133    ///
134    /// Panics if the object of `Self` does not have [`EnumObj`] as an
135    /// ancestor, which only an incorrect `impl EnumRef` allows.
136    fn name(&self) -> &str {
137        let object = self
138            .downcast_ref::<EnumObj>()
139            .expect("an `EnumRef` object has `EnumObj` as an ancestor");
140        object.name.as_str()
141    }
142
143    /// The attribute `name` of the values of the enum type, or `None` when no
144    /// value has it.
145    ///
146    /// The map holds the registry's column, so it also sees the attributes set
147    /// after it was read. See also
148    /// [`EnumDef::set_attr`](crate::reflection::EnumDef::set_attr).
149    ///
150    /// # Arguments
151    ///
152    /// * `name` - The name of the attribute.
153    ///
154    /// # Returns
155    ///
156    /// The attribute of every value that has it, read as `V`.
157    fn attr_map<V: AnyCompatible>(name: &str) -> Result<Option<EnumAttrMap<Self, V>>> {
158        EnumAttrMap::lookup(name)
159    }
160}