This is an automated email from the ASF dual-hosted git repository.

tqchen 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 455bf7bf [FEAT][Rust] Add object downcast_ref to Any, AnyView and 
managed references (#891)
455bf7bf is described below

commit 455bf7bff825c06c1c41bd248567e56c43da65d1
Author: Tianqi Chen <[email protected]>
AuthorDate: Sun Nov 1 20:07:38 2026 -0500

    [FEAT][Rust] Add object downcast_ref to Any, AnyView and managed references 
(#891)
    
    Add `downcast_ref<T: ObjectCore>() -> Option<&T>` to Any, AnyView and
    managed object references for inheritance-aware borrowed access without
    acquiring another strong reference. The Rust guide explains object
    handles and dynamically typed values in separate sections using
    MyPairObj examples.
---
 docs/guides/rust_lang_guide.md          | 60 +++++++++++++++++++++++++++++----
 rust/tvm-ffi/src/any.rs                 | 56 ++++++++++++++++++++++++++++++
 rust/tvm-ffi/src/object.rs              | 15 ++++++---
 rust/tvm-ffi/src/reflection/registry.rs |  2 +-
 rust/tvm-ffi/tests/test_any.rs          |  4 +++
 rust/tvm-ffi/tests/test_cast.rs         | 24 +++++++++++--
 6 files changed, 146 insertions(+), 15 deletions(-)

diff --git a/docs/guides/rust_lang_guide.md b/docs/guides/rust_lang_guide.md
index b6d5431e..d926edb3 100644
--- a/docs/guides/rust_lang_guide.md
+++ b/docs/guides/rust_lang_guide.md
@@ -65,12 +65,60 @@ export LD_LIBRARY_PATH=$(tvm-ffi-config 
--libdir):$LD_LIBRARY_PATH
 
 ## Basic Usage
 
-**Named managed reference**. A named managed reference follows the newtype 
pattern around
-`ObjectArc<T>`, which manages the underlying object’s lifetime through 
reference counting.
-Define methods and associated functions on the named type, and implement 
traits to provide
-shared interfaces. The named type can also impose additional constraints on 
the underlying object.
-For example, `Array<T>` holds an `ObjectArc<ArrayObj>` while constraining the 
array’s
-element type to `T`. Named reference types implement `ObjectRefCore` for 
shared reference operations.
+### Any and AnyView
+
+As in C++, `Any` owns a dynamically typed value, while `AnyView<'a>` borrows a 
value.
+An object stored in `Any` carries a strong reference; creating an `AnyView` 
does not
+increment its reference count. Rust tracks the view's lifetime so it cannot 
outlive
+the value it borrows. A custom pair illustrates owning and borrowed access:
+
+```rust
+use tvm_ffi::{def_object_ref, rs_class, Any, AnyView, Object};
+use tvm_ffi::object::ObjectRef;
+
+#[rs_class("my.MyPair")]
+pub struct MyPairObj {
+    base: Object,
+    pub first: i64,
+    pub second: i64,
+}
+def_object_ref!(pub MyPair, ObjectRef, MyPairObj);
+
+let pair = MyPair::from(MyPairObj::new(Object::new(), 3, 4));
+let value = Any::from(pair); // Transfer the handle's ownership into Any.
+assert_eq!(value.downcast_ref::<MyPairObj>().unwrap().second, 4);
+let view = AnyView::from(&value);
+assert_eq!(view.downcast_ref::<MyPairObj>().unwrap().first, 3);
+
+let owned_pair = value.try_as::<MyPair>().unwrap(); // Acquire another strong 
reference.
+assert_eq!(owned_pair.second, 4);
+```
+
+Both `Any` and `AnyView` provide object-only `downcast_ref::<T>() -> 
Option<&T>`,
+with `T: ObjectCore`. It accepts the runtime type or a compatible base type and
+returns `None` for unrelated types and non-object values. The returned 
reference
+borrows its source without consuming it or incrementing the reference count.
+In contrast, `try_as::<MyPair>()` returns an owned managed reference, which 
retains
+the object independently of the source `Any` or `AnyView`.
+
+### Object and ObjectRef
+
+The object representation and its owning handle are separate, as with C++ 
`Object`
+and `ObjectRef`. The `MyPairObj` representation above implements `ObjectCore`;
+`Object` is the root representation. Its named managed reference `MyPair` wraps
+`ObjectArc<MyPairObj>`, which manages shared ownership through reference 
counting.
+`ObjectRef` is the erased managed reference. Named references implement 
`ObjectRefCore`
+for shared operations and can define their own methods:
+
+```rust
+use tvm_ffi::ObjectRefCore;
+
+let pair = MyPair::from(MyPairObj::new(Object::new(), 3, 4));
+assert_eq!(pair.downcast_ref::<MyPairObj>().unwrap().first, 3);
+```
+
+Managed references provide `downcast_ref::<T>()` with the same inheritance and
+borrowing rules as `Any` and `AnyView`.
 
 ### Loading a Module
 
diff --git a/rust/tvm-ffi/src/any.rs b/rust/tvm-ffi/src/any.rs
index 1c5fc500..bb90dfd7 100644
--- a/rust/tvm-ffi/src/any.rs
+++ b/rust/tvm-ffi/src/any.rs
@@ -78,6 +78,24 @@ impl<'a> AnyView<'a> {
         }
     }
 
+    /// Borrow the viewed object as `T` when its runtime type is `T` or a 
subtype.
+    ///
+    /// `T` is an object representation type such as `MyPairObj`. Non-object
+    /// values and unrelated object types return `None`. This does not change
+    /// the object's reference count; the borrow cannot outlive this view or
+    /// the owner it borrows. See [`Any::downcast_ref`] for an example.
+    #[inline]
+    pub fn downcast_ref<T: object::ObjectCore>(&self) -> Option<&T> {
+        if self.data.type_index < TypeIndex::kTVMFFIStaticObjectBegin as i32
+            || !object::is_instance_of::<T>(self.data.type_index)
+        {
+            return None;
+        }
+        // SAFETY: the type check establishes T's layout, and AnyView keeps
+        // the allocation borrowed for at least the lifetime of this reference.
+        Some(unsafe { &*self.data.data_union.v_obj.cast::<T>() })
+    }
+
     /// More strict version than try_from/try_into
     ///
     /// This function will not try to cast the type
@@ -180,6 +198,44 @@ impl Any {
     pub(crate) fn as_raw_ffi_any(&self) -> &TVMFFIAny {
         &self.data
     }
+    /// Borrow the stored object as `T` when its runtime type is `T` or a 
subtype.
+    ///
+    /// `T` is an object representation type such as `FooObj`, rather than its
+    /// managed reference `Foo`. Non-object values and unrelated object types
+    /// return `None`. This neither consumes `self` nor changes the object's
+    /// reference count, and the returned reference cannot outlive `self`.
+    ///
+    /// ```
+    /// use tvm_ffi::{def_object_ref, rs_class, Any, AnyView, Object, 
ObjectRefCore};
+    /// use tvm_ffi::object::ObjectRef;
+    ///
+    /// #[rs_class("my.MyPair", crate = tvm_ffi)]
+    /// pub struct MyPairObj {
+    ///     base: Object,
+    ///     pub first: i64,
+    ///     pub second: i64,
+    /// }
+    /// def_object_ref!(pub MyPair, ObjectRef, MyPairObj, crate = tvm_ffi);
+    ///
+    /// let pair = MyPair::from(MyPairObj::new(Object::new(), 3, 4));
+    /// assert_eq!(pair.downcast_ref::<MyPairObj>().unwrap().first, 3);
+    /// let value = Any::from(pair);
+    /// assert_eq!(value.downcast_ref::<MyPairObj>().unwrap().second, 4);
+    /// let view = AnyView::from(&value);
+    /// assert_eq!(view.downcast_ref::<MyPairObj>().unwrap().first, 3);
+    /// ```
+    #[inline]
+    pub fn downcast_ref<T: object::ObjectCore>(&self) -> Option<&T> {
+        if self.data.type_index < TypeIndex::kTVMFFIStaticObjectBegin as i32
+            || !object::is_instance_of::<T>(self.data.type_index)
+        {
+            return None;
+        }
+        // SAFETY: the object tag and runtime type check guarantee a live T
+        // layout, and this borrow is bounded by the owning Any's lifetime.
+        Some(unsafe { &*self.data.data_union.v_obj.cast::<T>() })
+    }
+
     /// Try to query if stored typed in Any exactly matches the type T
     ///
     /// This function is fast in the case of failure and can be used to check
diff --git a/rust/tvm-ffi/src/object.rs b/rust/tvm-ffi/src/object.rs
index df5aae51..50b8b810 100644
--- a/rust/tvm-ffi/src/object.rs
+++ b/rust/tvm-ffi/src/object.rs
@@ -151,19 +151,24 @@ pub unsafe trait ObjectRefCore: Sized + Clone {
         }
     }
 
-    /// Borrow the underlying object as node type `N` when its runtime type 
matches.
+    /// Borrow the underlying object as `T` when its runtime type is `T` or a 
subtype.
     ///
+    /// `T` is an object representation type such as `FooObj`, rather than its
+    /// managed reference `Foo`. Unrelated object types return `None`.
     /// Unlike [`ObjectRefCast::try_cast`], this method neither consumes the
-    /// reference nor changes the object's reference count. The returned node
+    /// reference nor changes the object's reference count. The returned borrow
     /// cannot outlive `self`.
+    /// See [`crate::Any::downcast_ref`] for an example.
     #[inline(always)]
-    fn as_node<N: ObjectCore>(&self) -> Option<&N> {
+    fn downcast_ref<T: ObjectCore>(&self) -> Option<&T> {
         let object = unsafe { ObjectArc::as_raw(Self::data(self)) };
         let type_index = unsafe { (*object.cast::<TVMFFIObject>()).type_index 
};
-        if !is_instance_of::<N>(type_index) {
+        if !is_instance_of::<T>(type_index) {
             return None;
         }
-        Some(unsafe { &*object.cast::<N>() })
+        // SAFETY: ObjectRefCore guarantees a live object allocation, the type
+        // check establishes T's layout, and the borrow cannot outlive self.
+        Some(unsafe { &*object.cast::<T>() })
     }
 }
 
diff --git a/rust/tvm-ffi/src/reflection/registry.rs 
b/rust/tvm-ffi/src/reflection/registry.rs
index 8c70ef0d..f733eadc 100644
--- a/rust/tvm-ffi/src/reflection/registry.rs
+++ b/rust/tvm-ffi/src/reflection/registry.rs
@@ -420,7 +420,7 @@ unsafe fn inherited_kind(info: *const 
crate::tvm_ffi_sys::TVMFFITypeInfo) -> i32
 
 /// `__ffi_shallow_copy__` of `N`: a copy of `object`, which must be an `N`, 
as a new object.
 fn shallow_copy_any<N: ObjectCore + ShallowCopy>(object: &ObjectRef) -> 
Result<Any> {
-    let Some(node) = object.as_node::<N>() else {
+    let Some(node) = object.downcast_ref::<N>() else {
         return Err(Error::new(
             TYPE_ERROR,
             &format!(
diff --git a/rust/tvm-ffi/tests/test_any.rs b/rust/tvm-ffi/tests/test_any.rs
index dfa2ea16..7568c009 100644
--- a/rust/tvm-ffi/tests/test_any.rs
+++ b/rust/tvm-ffi/tests/test_any.rs
@@ -171,6 +171,8 @@ fn test_any_option_i32() {
 
     // Test Any with Some value
     assert_eq!(any_some.type_index(), TypeIndex::kTVMFFIInt as i32);
+    assert!(any_some.downcast_ref::<Object>().is_none());
+    assert!(any_view_some.downcast_ref::<Object>().is_none());
     assert_eq!(Option::<i32>::try_from(any_some).unwrap(), Some(42i32));
 
     // Test AnyView with Some value
@@ -184,6 +186,8 @@ fn test_any_option_i32() {
 
     // Test Any with None value
     assert_eq!(any_none.type_index(), TypeIndex::kTVMFFINone as i32);
+    assert!(any_none.downcast_ref::<Object>().is_none());
+    assert!(any_view_none.downcast_ref::<Object>().is_none());
     assert_eq!(Option::<i32>::try_from(any_none).unwrap(), None::<i32>);
 
     // Test AnyView with None value
diff --git a/rust/tvm-ffi/tests/test_cast.rs b/rust/tvm-ffi/tests/test_cast.rs
index 4cd1ce90..7717e07e 100644
--- a/rust/tvm-ffi/tests/test_cast.rs
+++ b/rust/tvm-ffi/tests/test_cast.rs
@@ -151,16 +151,34 @@ fn test_borrowed_node_cast_preserves_reference_count() {
         .unwrap();
     let strong_count = ObjectArc::strong_count(TestBase::data(&base));
 
-    let derived = base.as_node::<TestDerivedObj>().unwrap();
+    let derived = base.downcast_ref::<TestDerivedObj>().unwrap();
     assert_eq!(derived.base.value, 7);
     assert_eq!(derived.extra, 8);
-    let base_node = base.as_node::<TestBaseObj>().unwrap();
+    let base_node = base.downcast_ref::<TestBaseObj>().unwrap();
     assert_eq!(base_node.value, 7);
     assert_eq!(ObjectArc::strong_count(TestBase::data(&base)), strong_count);
 
     let base_only = new_base(1, delete_counter.clone());
-    assert!(base_only.as_node::<TestDerivedObj>().is_none());
+    assert!(base_only.downcast_ref::<TestDerivedObj>().is_none());
     assert_eq!(ObjectArc::strong_count(TestBase::data(&base_only)), 1);
+
+    let any = Any::from(base);
+    let view = AnyView::from(&any);
+    let derived = any.downcast_ref::<TestDerivedObj>().unwrap();
+    assert!(std::ptr::eq(
+        view.downcast_ref::<TestDerivedObj>().unwrap(),
+        derived
+    ));
+    assert_eq!(view.downcast_ref::<TestBaseObj>().unwrap().value, 7);
+    assert!(any.downcast_ref::<Object>().is_some());
+    assert_eq!(any.debug_strong_count(), Some(1));
+    assert_eq!(derived.extra, 8);
+
+    let base_only = Any::from(base_only);
+    assert!(base_only.downcast_ref::<TestDerivedObj>().is_none());
+    assert!(AnyView::from(&base_only)
+        .downcast_ref::<TestDerivedObj>()
+        .is_none());
 }
 
 #[test]

Reply via email to