tvm_ffi/reflection/enum_def.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//! Registration of enum values and their attributes, kept in each enum type's
21//! registry (the `__ffi_enum__` type attribute) that every language shares.
22
23use std::marker::PhantomData;
24use std::mem::{align_of, size_of};
25
26use super::registry::{ensure_not_opaque_ptr, register_type_attr};
27use super::{NativeFunction, TypeAttrColumn, get_method};
28use crate::any::TryFromTemp;
29use crate::derive::{Object, ObjectRef};
30use crate::enum_ref::EnumObj;
31use crate::object::{
32 Object, ObjectArc, ObjectCore, ObjectRef, is_instance_of, lock_type_registration,
33};
34use crate::tvm_ffi_sys::{TVMFFIGetTypeInfo, TVMFFIObject, TVMFFITypeInfo};
35use crate::type_traits::AnyCompatible;
36use crate::{Any, AnyView, EnumRef, Error, List, Result, String, TYPE_ERROR, VALUE_ERROR};
37
38/// Registers a value of the enum type `E`, then its attributes.
39///
40/// [`new`](Self::new) registers the value at once, and
41/// [`set_attr`](Self::set_attr) sets each attribute on it, which
42/// [`EnumRef::attr_map`] reads. The value's object is an [`EnumObj`], so `E`'s
43/// object type adds no fields to its parent `EnumObj`.
44///
45/// As in C++, values and attributes register during static initialization,
46/// such as in a [`static_init_block!`](crate::static_init_block), before other
47/// threads read them: registrations from Rust lock each other out, but
48/// readers take no lock.
49///
50/// # Examples
51///
52/// ```standalone_crate
53/// use tvm_ffi::derive::{Object, ObjectRef};
54/// use tvm_ffi::reflection::EnumDef;
55/// use tvm_ffi::{EnumRef, ObjectArc};
56/// use tvm_ffi::enum_ref::EnumObj;
57///
58/// #[repr(C)]
59/// #[derive(Object)]
60/// #[object(type_key = "my_ext.Color", register, final, immutable)]
61/// pub struct ColorObj {
62/// base_: EnumObj,
63/// }
64///
65/// #[derive(Clone, ObjectRef)]
66/// pub struct Color {
67/// data: ObjectArc<ColorObj>,
68/// }
69///
70/// impl EnumRef for Color {}
71///
72/// let red = EnumDef::<Color>::new("red")?.set_attr("my_ext.hex", 0xff0000_i64)?.value();
73///
74/// let hex = Color::attr_map::<i64>("my_ext.hex")?.unwrap();
75/// assert_eq!(hex.get(&red)?, Some(0xff0000));
76/// # Ok::<(), tvm_ffi::Error>(())
77/// ```
78pub struct EnumDef<E: EnumRef> {
79 value: E,
80}
81
82impl<E: EnumRef> EnumDef<E> {
83 /// Register the value `name` of `E`.
84 ///
85 /// # Arguments
86 ///
87 /// * `name` - The name of the value.
88 ///
89 /// # Returns
90 ///
91 /// The builder of the value's attributes.
92 ///
93 /// # Errors
94 ///
95 /// Returns a `ValueError` if `name` is empty or `E` already has a value named
96 /// `name`, and a `TypeError` if `E` is not an enum type, is an integer enum
97 /// (`ffi.IntEnum`), whose values name their own indices, or registers an
98 /// object size other than that of [`EnumObj`]: an enum type whose objects
99 /// have fields of their own.
100 ///
101 /// `E` accepts every object of its type, as a non-generic
102 /// [`#[derive(ObjectRef)]`](crate::derive::ObjectRef) reference does.
103 pub fn new(name: &str) -> Result<Self>
104 where
105 E: crate::object::PlainObjectRef,
106 {
107 const {
108 assert!(
109 size_of::<E::ContainerType>() == size_of::<EnumObj>()
110 && align_of::<E::ContainerType>() == align_of::<EnumObj>(),
111 "an enum type registered from Rust adds no fields to `EnumObj`"
112 )
113 };
114 let type_index = E::ContainerType::type_index();
115 let type_key = E::ContainerType::TYPE_KEY;
116 if name.is_empty() {
117 return Err(Error::new(
118 VALUE_ERROR,
119 &format!("a value name of `{type_key}` must be non-empty"),
120 ));
121 }
122 if !is_instance_of::<EnumObj>(type_index) || is_int_enum(type_index) {
123 return Err(Error::new(
124 TYPE_ERROR,
125 &format!("`{type_key}` is not an enum type whose values Rust can register"),
126 ));
127 }
128 // The assert above sees only the Rust mirror, which may be opaque: a
129 // registered object size must be exactly that of the `EnumObj`
130 // allocated below. A type registered without one (such as by
131 // `#[derive(Object)]`) is laid out as its Rust struct.
132 // SAFETY: the type is registered, and its information is static.
133 let metadata = unsafe { (*TVMFFIGetTypeInfo(type_index)).metadata };
134 // SAFETY: registered metadata is static.
135 let total_size = unsafe { metadata.as_ref() }.map_or(0, |metadata| metadata.total_size);
136 if total_size != 0 && total_size as usize != size_of::<EnumObj>() {
137 return Err(Error::new(
138 TYPE_ERROR,
139 &format!(
140 "`{type_key}` objects have fields beyond `ffi.Enum`, so Rust cannot \
141 register its values"
142 ),
143 ));
144 }
145 let _registering = lock_type_registration();
146 let state = ensure_state(type_index)?;
147 let index = state.entries.len() as i64;
148 let key = String::from(name);
149 let indexes = AnyView::from(&state.indexes);
150 if dict_get(indexes, AnyView::from(&key))?.is_some()
151 || dict_get(indexes, AnyView::from(&index))?.is_some()
152 {
153 return Err(Error::new(
154 VALUE_ERROR,
155 &format!("Enum `{type_key}` already has a value named `{name}`"),
156 ));
157 }
158 let object = ObjectArc::into_raw(ObjectArc::new(EnumObj::new(index, name)));
159 // SAFETY: `E`'s object is an `EnumObj` with `E`'s type index (checked
160 // above), and the object is not shared yet. The deleter stays that of
161 // `EnumObj`, which drops the same fields.
162 let value = unsafe {
163 (*object.cast_mut().cast::<TVMFFIObject>()).type_index = type_index;
164 E::from_data(ObjectArc::from_raw(object.cast()))
165 };
166 state.entries.push(Any::from(value.clone()))?;
167 dict_set(indexes, AnyView::from(&index), AnyView::from(&value))?;
168 dict_set(indexes, AnyView::from(&key), AnyView::from(&value))?;
169 Ok(Self { value })
170 }
171
172 /// Set the attribute `name` of the value.
173 ///
174 /// See also [`EnumRef::attr_map`].
175 ///
176 /// # Arguments
177 ///
178 /// * `name` - The name of the attribute.
179 /// * `value` - The value of the attribute, `Send + Sync` since every
180 /// thread reads it.
181 ///
182 /// # Returns
183 ///
184 /// The builder, for the next attribute.
185 ///
186 /// # Errors
187 ///
188 /// Returns a `TypeError` if `value` is an opaque pointer: set a native
189 /// hook with [`set_native_fn_attr`](Self::set_native_fn_attr).
190 pub fn set_attr(self, name: &str, value: impl Into<Any> + Send + Sync) -> Result<Self> {
191 let value = value.into();
192 ensure_not_opaque_ptr(name, &value)?;
193 self.set_attr_any(name, value)
194 }
195
196 /// Set the native hook `f` as the attribute `name` of the value.
197 ///
198 /// # Arguments
199 ///
200 /// * `name` - The name of the attribute.
201 /// * `f` - The hook.
202 ///
203 /// # Returns
204 ///
205 /// The builder, for the next attribute.
206 ///
207 /// # Safety
208 ///
209 /// Every caller of the attribute `name` calls its hooks with exactly
210 /// `Args` and reads `R`: a native caller calls the function pointer
211 /// unchecked.
212 pub unsafe fn set_native_fn_attr<Args, R>(
213 self,
214 name: &str,
215 f: NativeFunction<Args, R>,
216 ) -> Result<Self> {
217 // SAFETY: the caller vouches for the readers of `name`.
218 self.set_attr_any(name, unsafe { f.into_any() })
219 }
220
221 fn set_attr_any(self, name: &str, value: Any) -> Result<Self> {
222 // Before the lock, which a first `type_index()` takes to register `E`.
223 let type_index = E::ContainerType::type_index();
224 let _registering = lock_type_registration();
225 let state = ensure_state(type_index)?;
226 let attrs = AnyView::from(&state.attrs);
227 let key = String::from(name);
228 let column = match dict_get(attrs, AnyView::from(&key))? {
229 Some(column) => column,
230 None => {
231 let column = crate::cached_global_func!("ffi.Dict").call_packed(&[])?;
232 dict_set(attrs, AnyView::from(&key), AnyView::from(&column))?;
233 column
234 }
235 };
236 dict_set(
237 AnyView::from(&column),
238 AnyView::from(&self.value),
239 AnyView::from(&value),
240 )?;
241 Ok(self)
242 }
243
244 /// The registered value.
245 pub fn value(&self) -> E {
246 self.value.clone()
247 }
248}
249
250/// One attribute of the values of the enum type `E`, as `V`, returned by
251/// [`EnumRef::attr_map`].
252pub struct EnumAttrMap<E, V> {
253 column: Any,
254 _types: PhantomData<fn() -> (E, V)>,
255}
256
257impl<E: EnumRef, V: AnyCompatible> EnumAttrMap<E, V> {
258 pub(crate) fn lookup(name: &str) -> Result<Option<Self>> {
259 let Some(state) = enum_state(E::ContainerType::type_index())? else {
260 return Ok(None);
261 };
262 let key = String::from(name);
263 let column = dict_get(AnyView::from(&state.attrs), AnyView::from(&key))?;
264 Ok(column.map(|column| Self {
265 column,
266 _types: PhantomData,
267 }))
268 }
269
270 /// The attribute of `value`, or `None` when it has none.
271 ///
272 /// # Errors
273 ///
274 /// Returns a `TypeError` if the attribute is not a `V`.
275 pub fn get(&self, value: &E) -> Result<Option<V>> {
276 dict_get(AnyView::from(&self.column), AnyView::from(value))?
277 .map(any_into)
278 .transpose()
279 }
280}
281
282/// The type attribute that holds an enum type's registry.
283const ENUM_STATE_ATTR: &str = "__ffi_enum__";
284
285/// The registry of one enum type: its values in registration order, the
286/// values by index and by name (`Dict<Any, ObjectRef>`), and the attribute
287/// columns (`Dict<String, Dict<ObjectRef, Any>>`).
288#[repr(C)]
289#[derive(Object)]
290#[object(type_key = "ffi.EnumState", final)]
291pub(crate) struct EnumStateObj {
292 base_: Object,
293 entries: List<Any>,
294 // The crate has no `Dict`; `dict_get` and `dict_set` call its global
295 // functions instead.
296 pub(crate) indexes: ObjectRef,
297 attrs: ObjectRef,
298}
299
300#[repr(C)]
301#[derive(ObjectRef, Clone)]
302pub(crate) struct EnumState {
303 data: ObjectArc<EnumStateObj>,
304}
305
306/// The registry of the enum type `type_index`, or `None` before its first value.
307pub(crate) fn enum_state(type_index: i32) -> Result<Option<EnumState>> {
308 let Some(column) = TypeAttrColumn::lookup(ENUM_STATE_ATTR) else {
309 return Ok(None);
310 };
311 column.get(type_index).map(EnumState::try_from).transpose()
312}
313
314/// The registry of the enum type `type_index`, created with its first value,
315/// under the registration lock.
316fn ensure_state(type_index: i32) -> Result<EnumState> {
317 if let Some(state) = enum_state(type_index)? {
318 return Ok(state);
319 }
320 let state: EnumState =
321 any_into(get_method("ffi.EnumState", "__ffi_init__")?.call_packed(&[])?)?;
322 register_type_attr(type_index, ENUM_STATE_ATTR, Any::from(state.clone()))?;
323 Ok(state)
324}
325
326fn is_int_enum(type_index: i32) -> bool {
327 let is_int_enum =
328 |info: *const TVMFFITypeInfo| unsafe { (*info).type_key.as_str() == "ffi.IntEnum" };
329 unsafe {
330 let info = TVMFFIGetTypeInfo(type_index);
331 !info.is_null()
332 && (is_int_enum(info)
333 || (0..(*info).type_depth as usize)
334 .any(|depth| is_int_enum(*(*info).type_acenstors.add(depth))))
335 }
336}
337
338pub(crate) fn dict_get(dict: AnyView<'_>, key: AnyView<'_>) -> Result<Option<Any>> {
339 // `ffi.DictGetItemOrMissing` saves a call but returns a sentinel object
340 // that Rust cannot name.
341 let count: i64 = crate::cached_global_func!("ffi.DictCount")
342 .call_packed(&[dict, key])?
343 .try_into()?;
344 if count == 0 {
345 return Ok(None);
346 }
347 crate::cached_global_func!("ffi.DictGetItem")
348 .call_packed(&[dict, key])
349 .map(Some)
350}
351
352fn dict_set(dict: AnyView<'_>, key: AnyView<'_>, value: AnyView<'_>) -> Result<()> {
353 crate::cached_global_func!("ffi.DictSetItem").call_packed(&[dict, key, value])?;
354 Ok(())
355}
356
357pub(crate) fn any_into<T: AnyCompatible>(value: Any) -> Result<T> {
358 TryFromTemp::<T>::try_from(AnyView::from(&value)).map(TryFromTemp::into_value)
359}