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 3380316d [Rust] Add borrowed matching and rename MutationView (#896)
3380316d is described below
commit 3380316d02864ff51513a5edd353b6d1f2e86d40
Author: Tianqi Chen <[email protected]>
AuthorDate: Mon Nov 2 09:55:46 2026 -0500
[Rust] Add borrowed matching and rename MutationView (#896)
Rename the non-owning mutation capability to MutationView and its erased
inspection accessor to as_any_view, preserving the capability-bounded
borrow.
Add borrowed object-node patterns such as AddObj(ref node) to match_any.
Ordered matching uses conditional fallthrough with guard cleanup;
eligible final borrowed and mixed owning arms use exact-type lookup and
direct selected-arm conversion without acquiring ownership for borrowed
nodes.
---
docs/guides/rust_lang_guide.md | 29 +++--
rust/tvm-ffi-macros/src/dispatch.rs | 14 +-
rust/tvm-ffi-macros/src/lib.rs | 8 ++
rust/tvm-ffi-macros/src/match_any.rs | 140 +++++++++++++++++---
rust/tvm-ffi/src/extra/structural_mutate.rs | 141 +++++++++++----------
rust/tvm-ffi/src/extra/structural_mutate/policy.rs | 19 +--
rust/tvm-ffi/src/lib.rs | 2 +-
rust/tvm-ffi/src/match_any_internal.rs | 80 ++++++++++++
rust/tvm-ffi/tests/test_match_any.rs | 69 ++++++++++
rust/tvm-ffi/tests/test_match_any_ast_lookup.rs | 63 ++++++++-
rust/tvm-ffi/tests/test_structural_mutate.rs | 106 ++++++++--------
11 files changed, 502 insertions(+), 169 deletions(-)
diff --git a/docs/guides/rust_lang_guide.md b/docs/guides/rust_lang_guide.md
index 95be3bdc..1d6f9d84 100644
--- a/docs/guides/rust_lang_guide.md
+++ b/docs/guides/rust_lang_guide.md
@@ -454,6 +454,15 @@ fn may_fail(value: i32) -> Result<()> {
}
```
+`match_any!` provides typed checked-conversion arms for object-backed values.
+`MyPair(pair)` produces an owning handle; `MyPairObj(ref node)` binds a shared
+`&MyPairObj` without increasing its reference count. These are macro arm
+conventions, not native Rust destructuring. An owning or custom matcher such as
+`MyPair(ref pair)` still converts to its own value and borrows that local
result.
+Guards retain source order, and a borrowed node cannot outlive its view or
grant
+mutable access. Eligible final node and owning patterns share the exact-type
+lookup optimization; other patterns use ordered checked conversions.
+
### Structural Walk and Visit
Rust provides equivalents of the C++ `StructuralWalk`/`StructuralVisitor`
@@ -729,7 +738,7 @@ results are not cached. Default recursion manages identity
remapping with
the same semantics as C++.
`MutateCallbacks::with_policy` and `MapWithContextPolicy` use
`MutationContextPolicy<State>`
-to manage context around default recursion. Policies consume `MutationValue`
+to manage context around default recursion. Policies consume `MutationView`
and return `UnchangedOr<Any>`; see the API documentation for composition and
scoped definition regions. Pass `MapWithContextPolicy` directly to
`structural_map`,
or pass `&mut mapper` to reuse it and inspect its state afterward;
@@ -763,7 +772,7 @@ original value.
```rust
use tvm_ffi::{
- structural_mutate, Array, MutateCallbacks, MutationContext, MutationValue,
+ structural_mutate, Array, MutateCallbacks, MutationContext, MutationView,
};
#[derive(Default)]
@@ -778,7 +787,7 @@ let mut mutator = MutateCallbacks::new(
mutator.state_mut().integers += 1;
value + 1
},
- |value: MutationValue<'_>, mutator: &mut MutationContext<'_, Stats>| {
+ |value: MutationView<'_>, mutator: &mut MutationContext<'_, Stats>| {
mutator.default_maybe_inplace_mutate(value)
},
),
@@ -793,13 +802,13 @@ assert_eq!(mutator.state().integers, 2);
`maybe_inplace_mutate` preserves the reuse opportunity of an owned value.
Closure callbacks are `Fn`; mutable data belongs in the callback state.
-Use `MutationValue<'_, T>` with `default_maybe_inplace_mutate` to forward its
+Use `MutationView<'_, T>` with `default_maybe_inplace_mutate` to forward its
permission, or `default_mutate_with_mode` to restrict it. Inspect it through
-`let view = value.as_value()` and `view.downcast_ref::<Node>()`; finish using
+`let view = value.as_any_view()` and `view.downcast_ref::<Node>()`; finish
using
that view before consuming the capability. Mutation contexts do not expose
`current()`, and copy-only default descent takes an explicit borrow
(`default_mutate(&view)`). Generated handlers can read the mode
-through `Mutator::inplace_mode()`; see `MutationValue` for ownership
requirements.
+through `Mutator::inplace_mode()`; see `MutationView` for ownership
requirements.
`#[dispatch(mutate)]` groups typed `mutate_*` callbacks. The dispatch object
owns its mutable pass state, while `Mutator` supplies recursion and the current
@@ -839,8 +848,8 @@ Use `#[dispatch(mutate, policy = MyPolicy)]` to apply a
`MutationContextPolicy<S
to default recursion.
For low-level custom recursion, implement `StructuralMutator` and pass
-`&mut` it to `structural_mutate`. `MutationValue` carries the engine's reuse
-permission. `MutationValue::borrowed` wraps an `AnyView` with `Disallow`;
+`&mut` it to `structural_mutate`. `MutationView` carries the engine's reuse
+permission. `MutationView::borrowed` wraps an `AnyView` with `Disallow`;
only the engine can grant `Allow`, and explicit modes can only restrict it.
Override
`dispatch_maybe_inplace_mutate` to opt into default container reuse;
`default_maybe_inplace_mutate` rechecks uniqueness before writing. Borrowed
@@ -849,7 +858,7 @@ values can be re-entered with `mutate`, while owned values
can use
```rust
use tvm_ffi::{
- structural_mutate, Any, Array, DefRegionKind, MutationValue, AnyView,
Result,
+ structural_mutate, Any, Array, DefRegionKind, MutationView, AnyView,
Result,
StructuralMutator,
};
@@ -866,7 +875,7 @@ impl StructuralMutator for Increment {
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
) -> Result<Any> {
self.default_maybe_inplace_mutate(value, kind)
diff --git a/rust/tvm-ffi-macros/src/dispatch.rs
b/rust/tvm-ffi-macros/src/dispatch.rs
index 63301289..20f4d400 100644
--- a/rust/tvm-ffi-macros/src/dispatch.rs
+++ b/rust/tvm-ffi-macros/src/dispatch.rs
@@ -197,7 +197,7 @@ fn expand(item_impl: &ItemImpl, args: DispatchArgs) ->
syn::Result<TokenStream2>
quote! {
fn on_default_mutate(
&mut self,
- value: #tvm_ffi::MutationValue<'_>,
+ value: #tvm_ffi::MutationView<'_>,
kind: #tvm_ffi::DefRegionKind,
) -> #tvm_ffi::Result<#tvm_ffi::Any> {
let policy = #policy;
@@ -310,7 +310,7 @@ fn expand(item_impl: &ItemImpl, args: DispatchArgs) ->
syn::Result<TokenStream2>
mutator: &mut #tvm_ffi::extra::structural_mutate::Mutator,
) -> Option<#tvm_ffi::Result<#tvm_ffi::Any>> {
<Self as
#tvm_ffi::extra::structural_mutate::MutateDispatch>::dispatch_mutate_value(
- self, #tvm_ffi::MutationValue::borrowed(value),
mutator,
+ self, #tvm_ffi::MutationView::borrowed(value), mutator,
)
}
@@ -318,7 +318,7 @@ fn expand(item_impl: &ItemImpl, args: DispatchArgs) ->
syn::Result<TokenStream2>
#[allow(unreachable_code, unused_variables, unused_mut)]
fn dispatch_mutate_value(
&mut self,
- mut value: #tvm_ffi::MutationValue<'_>,
+ mut value: #tvm_ffi::MutationView<'_>,
mutator: &mut #tvm_ffi::Mutator,
) -> Option<#tvm_ffi::Result<#tvm_ffi::Any>> {
#(#links)*
@@ -364,7 +364,7 @@ fn expand_links(
let invoke = match &handler.argument {
HandlerArgument::Value => {
let value = if matches!(mode, DispatchMode::Mutate) {
- quote!(#value.as_value())
+ quote!(#value.as_any_view())
} else {
value.clone()
};
@@ -380,7 +380,7 @@ fn expand_links(
#into_result(self.#method(node #trailing_arg))
});
let value = if matches!(mode, DispatchMode::Mutate) {
- quote!(#value.as_value())
+ quote!(#value.as_any_view())
} else {
value.clone()
};
@@ -407,7 +407,7 @@ fn expand_links(
#into_result(self.#method(typed #trailing_arg))
});
let value = if matches!(mode, DispatchMode::Mutate) {
- quote!(#value.as_value())
+ quote!(#value.as_any_view())
} else {
value.clone()
};
@@ -499,7 +499,7 @@ fn parse_handler(method: &ImplItemMethod, mode:
DispatchMode) -> syn::Result<Han
.path
.segments
.last()
- .is_some_and(|s| s.ident == "MutationValue") =>
+ .is_some_and(|s| s.ident == "MutationView") =>
{
let segment = path.path.segments.last().unwrap();
let value_type = if let PathArguments::AngleBracketed(args) =
&segment.arguments {
diff --git a/rust/tvm-ffi-macros/src/lib.rs b/rust/tvm-ffi-macros/src/lib.rs
index 958b1e57..44cabbdc 100644
--- a/rust/tvm-ffi-macros/src/lib.rs
+++ b/rust/tvm-ffi-macros/src/lib.rs
@@ -44,6 +44,14 @@ pub fn dispatch(attr: TokenStream, item: TokenStream) ->
TokenStream {
/// The scrutinee may be an owned object handle, `Any`, or `AnyView`. Convert
an
/// already-borrowed object handle to `AnyView` before invoking the macro.
///
+/// Typed arms are checked conversions, not native Rust destructuring.
+/// `Handle(value)` converts to an owning handle. `NodeType(ref node)` borrows
+/// an `ObjectCore` node without acquiring ownership; the binding is
`&NodeType`.
+/// For owning or custom matcher types, `Matcher(ref value)` retains the
existing
+/// conversion and borrows its local result. Shared node matching cannot grant
+/// mutable access, and bindings remain bounded by the scrutinee/view borrow.
+/// Guards are evaluated in source order before selecting an arm.
+///
/// Non-object values skip the typed patterns and use the `_` fallback.
#[proc_macro_error]
#[proc_macro]
diff --git a/rust/tvm-ffi-macros/src/match_any.rs
b/rust/tvm-ffi-macros/src/match_any.rs
index 5cb12c2c..07640948 100644
--- a/rust/tvm-ffi-macros/src/match_any.rs
+++ b/rust/tvm-ffi-macros/src/match_any.rs
@@ -198,6 +198,9 @@ where
.enumerate()
.rev()
.fold(fallback, |next, (arm_id, arm)| {
+ if let Some(binding) = shared_ref_binding(&arm.binding) {
+ return expand_ref_pattern_arm(tvm_ffi, arm, binding, view,
next);
+ }
let matcher = &arm.matcher;
let matched = matched_arm(arm_id, arm);
let conversion = expand_pattern_conversion(tvm_ffi, matcher, view);
@@ -214,6 +217,83 @@ where
})
}
+fn shared_ref_binding(binding: &Pat) -> Option<&Ident> {
+ match binding {
+ Pat::Ident(binding)
+ if binding.by_ref.is_some()
+ && binding.mutability.is_none()
+ && binding.subpat.is_none() =>
+ {
+ Some(&binding.ident)
+ }
+ _ => None,
+ }
+}
+
+fn expand_ref_pattern_arm(
+ tvm_ffi: &TokenStream,
+ arm: &TypedArm,
+ binding: &Ident,
+ view: &Ident,
+ next: TokenStream,
+) -> TokenStream {
+ let holder = Ident::new("__tvm_ffi_match_any_ref_holder",
Span::mixed_site());
+ let matcher = &arm.matcher;
+ let body = &arm.body;
+ let borrow = quote! {
+ #[allow(unused_variables)]
+ let #binding: &#matcher =
::core::borrow::Borrow::<#matcher>::borrow(&#holder);
+ };
+ let conversion = expand_ref_pattern_conversion(tvm_ffi, matcher, view);
+ if let Some(guard) = &arm.guard {
+ let converted = Ident::new("__tvm_ffi_match_any_ref_converted",
Span::mixed_site());
+ let accepted = Ident::new("__tvm_ffi_match_any_ref_accepted",
Span::mixed_site());
+ // Keep the guard binding out of the fallthrough scope. Preserve native
+ // guard control flow and emit the remaining arms only once.
+ quote! {{
+ let #converted = #conversion;
+ let #accepted = if let ::core::result::Result::Ok(#holder) =
&#converted {
+ #[allow(unused_variables)]
+ let #binding: &#matcher =
::core::borrow::Borrow::<#matcher>::borrow(#holder);
+ #guard
+ } else {
+ false
+ };
+ if #accepted {
+ let #holder = #converted.as_ref().unwrap();
+ #[allow(unused_variables)]
+ let #binding: &#matcher =
::core::borrow::Borrow::<#matcher>::borrow(#holder);
+ #body
+ } else {
+ ::core::mem::drop(#converted);
+ #next
+ }
+ }}
+ } else {
+ quote! {
+ if let ::core::result::Result::Ok(#holder) = #conversion {
+ #borrow
+ #body
+ } else {
+ #next
+ }
+ }
+ }
+}
+
+fn expand_ref_pattern_conversion(
+ tvm_ffi: &TokenStream,
+ matcher: &Path,
+ view: &Ident,
+) -> TokenStream {
+ let probe = Ident::new("__tvm_ffi_match_any_ref_probe",
Span::mixed_site());
+ quote! {{
+ use #tvm_ffi::match_any_internal::RefPatternConversion as _;
+ let #probe =
#tvm_ffi::match_any_internal::PatternConversionProbe::<#matcher>::new();
+ (&&&#probe).try_convert_ref(&#view)
+ }}
+}
+
fn expand_pattern_conversion(tvm_ffi: &TokenStream, matcher: &Path, view:
&Ident) -> TokenStream {
let span = Span::mixed_site();
let probe = Ident::new("__tvm_ffi_match_any_conversion_probe", span);
@@ -263,18 +343,29 @@ fn expand_leaf_table_lookup(tvm_ffi: &TokenStream, arms:
&[TypedArm], view: &Ide
let static_table = Ident::new("__TVM_FFI_MATCH_ANY_LEAF_TABLE", span);
let table = Ident::new("__tvm_ffi_match_any_leaf_table", span);
let arm_count = arms.len();
- let pattern_list = arms
- .iter()
- .map(|arm| &arm.matcher)
- .rev()
- .fold(quote!(()), |tail, matcher| quote!((#matcher, #tail)));
+ let pattern_probe = arms.iter().rev().fold(
+ quote!(#tvm_ffi::match_any_internal::LeafPatternProbe::<()>::new()),
+ |tail, arm| {
+ let matcher = &arm.matcher;
+ let metadata = if shared_ref_binding(&arm.binding).is_some() {
+ quote!({
+ use #tvm_ffi::match_any_internal::RefPatternConversion as
_;
+ let probe =
#tvm_ffi::match_any_internal::PatternConversionProbe::<#matcher>::new();
+ (&&&probe).leaf_pattern()
+ })
+ } else {
+ quote!(::core::marker::PhantomData::<#matcher>)
+ };
+ quote!(#tail.prepend(#metadata))
+ },
+ );
quote! {
{
use #tvm_ffi::match_any_internal::LeafPatternMetadata as _;
let #probe =
-
#tvm_ffi::match_any_internal::LeafPatternProbe::<#pattern_list>::new();
+ #pattern_probe;
match (&#probe).leaf_pattern_list_id() {
::core::option::Option::Some(#pattern_list_id) => {
static #static_table: ::std::sync::OnceLock<
@@ -316,7 +407,11 @@ fn expand_direct_leaf_selection(
let matcher = &arm.matcher;
let variant = &arm_variants[arm_id];
let arm_constant = &arm_constants[arm_id];
- let conversion = expand_exact_pattern_conversion(tvm_ffi, matcher,
view);
+ let conversion = if shared_ref_binding(&arm.binding).is_some() {
+ expand_ref_pattern_conversion(tvm_ffi, matcher, view)
+ } else {
+ expand_exact_pattern_conversion(tvm_ffi, matcher, view)
+ };
quote! {
#arm_constant => {
@@ -355,6 +450,16 @@ fn expand_leaf_body_dispatch(
let binding = &arm.binding;
let body = &arm.body;
let variant = &arm_variants[arm_id];
+ if let Some(binding) = shared_ref_binding(binding) {
+ let holder = Ident::new("__tvm_ffi_match_any_ref_holder",
Span::mixed_site());
+ let matcher = &arm.matcher;
+ return quote! {
+ #selected_enum::#variant(#holder) => {
+ let #binding: &#matcher =
::core::borrow::Borrow::<#matcher>::borrow(&#holder);
+ #body
+ }
+ };
+ }
quote! {
#selected_enum::#variant(#binding) => {
@@ -410,19 +515,22 @@ fn expand_leaf_lookup_match(
}
});
let lookup_arm_id = expand_leaf_table_lookup(tvm_ffi, arms, &view);
- let ordered_selection = expand_ordered_try_into_chain(
- tvm_ffi,
- arms,
+ let ordered_selection = arms.iter().enumerate().rev().fold(
quote!(#selected_enum::#fallback_variant),
- &view,
- &rejected,
- |arm_id, _| {
+ |next, (arm_id, arm)| {
let variant = &arm_variants[arm_id];
- quote!(
- ::core::result::Result::Ok(#selected_value) => {
+ let conversion = if shared_ref_binding(&arm.binding).is_some() {
+ expand_ref_pattern_conversion(tvm_ffi, &arm.matcher, &view)
+ } else {
+ expand_pattern_conversion(tvm_ffi, &arm.matcher, &view)
+ };
+ quote! {
+ if let ::core::result::Result::Ok(#selected_value) =
#conversion {
#selected_enum::#variant(#selected_value)
+ } else {
+ #next
}
- )
+ }
},
);
diff --git a/rust/tvm-ffi/src/extra/structural_mutate.rs
b/rust/tvm-ffi/src/extra/structural_mutate.rs
index fda61db8..502e10c7 100644
--- a/rust/tvm-ffi/src/extra/structural_mutate.rs
+++ b/rust/tvm-ffi/src/extra/structural_mutate.rs
@@ -106,7 +106,7 @@ impl<T: Into<Any>> IntoMutateResult for Result<T> {
///
/// `Allow` still requires unique ownership; it does not grant permission to
/// modify a borrowed value. Use an owned value or an engine-issued
-/// [`MutationValue`] with the mode-aware mutation helpers.
+/// [`MutationView`] with the mode-aware mutation helpers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InplaceMode {
/// Use ordinary mutation, including for uniquely owned values.
@@ -125,7 +125,10 @@ impl InplaceMode {
}
}
-/// A mutation value carrying the engine's in-place permission.
+/// A non-owning, move-only view carrying the engine's in-place permission.
+///
+/// This view cannot be copied or cloned. Consuming it transfers the same
+/// permission; narrowing its matched type does not acquire ownership.
///
/// Unlike an owning typed argument, this handle does not increment the
reference
/// count. Borrow through it to inspect the node, then consume it in
@@ -138,9 +141,9 @@ impl InplaceMode {
///
/// A node borrowed through a copied view cannot survive consumption of the
handle:
/// ```compile_fail,E0505
-/// use tvm_ffi::{MutationContext, MutationValue};
-/// fn invalid(value: MutationValue<'_>, ctx: &mut MutationContext<'_>) {
-/// let view = value.as_value();
+/// use tvm_ffi::{MutationContext, MutationView};
+/// fn invalid(value: MutationView<'_>, ctx: &mut MutationContext<'_>) {
+/// let view = value.as_any_view();
/// let copy = view;
/// let node =
copy.downcast_ref::<tvm_ffi::collections::array::ArrayObj>().unwrap();
/// ctx.default_maybe_inplace_mutate(value).unwrap();
@@ -151,9 +154,9 @@ impl InplaceMode {
/// Moving the handle into a nested callback cannot bypass that borrow:
/// ```compile_fail,E0505
/// use std::cell::RefCell;
-/// use tvm_ffi::{structural_mutate, MutationContext, MutationValue};
-/// fn invalid(value: MutationValue<'_>) {
-/// let view = value.as_value();
+/// use tvm_ffi::{structural_mutate, MutationContext, MutationView};
+/// fn invalid(value: MutationView<'_>) {
+/// let view = value.as_any_view();
/// let node =
view.downcast_ref::<tvm_ffi::collections::array::ArrayObj>().unwrap();
/// let pending = RefCell::new(Some(value));
/// structural_mutate(true, |_: bool, inner: &mut MutationContext<'_>| {
@@ -165,15 +168,15 @@ impl InplaceMode {
///
/// A copied inspection view also cannot survive low-level default mutation:
/// ```compile_fail,E0505
-/// use tvm_ffi::{DefRegionKind, MutationValue, StructuralMutator};
-/// fn invalid<M: StructuralMutator>(value: MutationValue<'_>, mutator: &mut
M) {
-/// let view = value.as_value();
+/// use tvm_ffi::{DefRegionKind, MutationView, StructuralMutator};
+/// fn invalid<M: StructuralMutator>(value: MutationView<'_>, mutator: &mut M)
{
+/// let view = value.as_any_view();
/// let copy = view;
/// mutator.default_maybe_inplace_mutate(value,
DefRegionKind::None).unwrap();
/// println!("{}", copy.type_index());
/// }
/// ```
-pub struct MutationValue<'a, T = Any> {
+pub struct MutationView<'a, T = Any> {
value: TVMFFIAny,
mode: InplaceMode,
_scope: PhantomData<AnyView<'a>>,
@@ -181,7 +184,7 @@ pub struct MutationValue<'a, T = Any> {
_not_send_sync: PhantomData<Rc<()>>,
}
-impl<'a> MutationValue<'a> {
+impl<'a> MutationView<'a> {
fn new(value: AnyView<'a>, mode: InplaceMode) -> Self {
Self {
value: raw_of(value),
@@ -198,7 +201,7 @@ impl<'a> MutationValue<'a> {
}
}
-impl<'a, T> MutationValue<'a, T> {
+impl<'a, T> MutationView<'a, T> {
/// Permission established before callback arguments acquire ownership.
pub fn inplace_mode(&self) -> InplaceMode {
self.mode
@@ -206,7 +209,7 @@ impl<'a, T> MutationValue<'a, T> {
/// Borrow the current value. The view and its copies borrow this handle,
/// so their last use must precede consuming it for default mutation.
- pub fn as_value(&self) -> AnyView<'_> {
+ pub fn as_any_view(&self) -> AnyView<'_> {
// SAFETY: the engine keeps this payload live while the capability is
// borrowed. The returned lifetime is bounded by self, not by 'a.
unsafe { borrowed_view(&self.value) }
@@ -215,11 +218,11 @@ impl<'a, T> MutationValue<'a, T> {
/// Narrow the matched type without acquiring an owning reference.
pub fn try_cast<U: crate::type_traits::ContainerElement>(
self,
- ) -> std::result::Result<MutationValue<'a, U>, Self> {
+ ) -> std::result::Result<MutationView<'a, U>, Self> {
// SAFETY: the engine keeps the borrowed value live for this handle's
// lifetime. This only checks its type and does not acquire ownership.
if unsafe { U::container_check_any_strict(&self.value) } {
- Ok(MutationValue {
+ Ok(MutationView {
value: self.value,
mode: self.mode,
_scope: PhantomData,
@@ -232,8 +235,8 @@ impl<'a, T> MutationValue<'a, T> {
}
/// Erase the matched type while preserving the engine-issued permission.
- pub fn into_untyped(self) -> MutationValue<'a> {
- MutationValue {
+ pub fn into_untyped(self) -> MutationView<'a> {
+ MutationView {
value: self.value,
mode: self.mode,
_scope: PhantomData,
@@ -281,7 +284,7 @@ impl Mutator {
/// Engine-established permission for this callback's current value.
///
/// This is not authority to modify a borrow: default in-place descent also
- /// requires consuming a [`MutationValue`].
+ /// requires consuming a [`MutationView`].
pub fn inplace_mode(&self) -> InplaceMode {
self.inplace_mode
}
@@ -422,7 +425,7 @@ impl Mutator {
pub fn default_maybe_inplace_mutate<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
) -> Result<Any> {
let mode = value.inplace_mode();
self.default_mutate_with_mode(dispatch, value, mode)
@@ -433,7 +436,7 @@ impl Mutator {
pub fn default_maybe_inplace_mutate_result<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
) -> Result<UnchangedOr<Any>> {
let mode = value.inplace_mode();
self.default_mutate_with_mode_result(dispatch, value, mode)
@@ -446,7 +449,7 @@ impl Mutator {
pub fn default_mutate_with_mode<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
mode: InplaceMode,
) -> Result<Any> {
let raw = value.value;
@@ -459,7 +462,7 @@ impl Mutator {
pub fn default_mutate_with_mode_result<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
mode: InplaceMode,
) -> Result<UnchangedOr<Any>> {
let permit = value.permit(mode);
@@ -502,11 +505,11 @@ trait MutateContextDriver<State> {
/// Consume the handle to exclude node borrows before default descent.
fn default_mutate_value(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
_mode: InplaceMode,
) -> Result<Any> {
- self.default_mutate_borrowed(value.as_value(), kind)
+ self.default_mutate_borrowed(value.as_any_view(), kind)
}
fn var_remap_get(&mut self, var: AnyView<'_>) -> Result<Option<Any>>;
fn var_remap_set(&mut self, var: AnyView<'_>, mutated_value: &Any) ->
Result<()>;
@@ -528,7 +531,7 @@ impl<State> MutationContext<'_, State> {
/// Engine-established permission for this callback's current value.
///
/// This is not authority to modify a borrow: default in-place descent also
- /// requires consuming a [`MutationValue`].
+ /// requires consuming a [`MutationView`].
pub fn inplace_mode(&self) -> InplaceMode {
self.inplace_mode
}
@@ -668,7 +671,7 @@ impl<State> MutationContext<'_, State> {
/// Consume the handle for default descent with its existing permission.
#[inline]
- pub fn default_maybe_inplace_mutate<T>(&mut self, value: MutationValue<'_,
T>) -> Result<Any> {
+ pub fn default_maybe_inplace_mutate<T>(&mut self, value: MutationView<'_,
T>) -> Result<Any> {
let mode = value.inplace_mode();
self.default_mutate_with_mode(value, mode)
}
@@ -677,7 +680,7 @@ impl<State> MutationContext<'_, State> {
#[inline]
pub fn default_maybe_inplace_mutate_result<T>(
&mut self,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
) -> Result<UnchangedOr<Any>> {
let mode = value.inplace_mode();
self.default_mutate_with_mode_result(value, mode)
@@ -690,7 +693,7 @@ impl<State> MutationContext<'_, State> {
/// before this call to preserve reuse of the current value.
pub fn default_mutate_with_mode<T>(
&mut self,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
mode: InplaceMode,
) -> Result<Any> {
let raw = value.value;
@@ -702,7 +705,7 @@ impl<State> MutationContext<'_, State> {
/// Consume the callback value for default descent, preserving `Unchanged`.
pub fn default_mutate_with_mode_result<T>(
&mut self,
- value: MutationValue<'_, T>,
+ value: MutationView<'_, T>,
mode: InplaceMode,
) -> Result<UnchangedOr<Any>> {
self.driver
@@ -731,7 +734,7 @@ impl<State> MutationContext<'_, State> {
/// remains available for closure callback chains with separate state.
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a supported `structural_mutate` mutator",
- note = "accepted mutators: `&mut U` where `U: StructuralMutator`; a
generated `MutateDispatch`; an `Fn` callback over an FFI value type `T`, `&N`
of an object node type, or `AnyView<'_>`, or a consuming `MutationValue<T>`,
followed by `&mut MutationContext<'_, State>`; or a tuple of up to 12 such
callbacks (tuples may nest)",
+ note = "accepted mutators: `&mut U` where `U: StructuralMutator`; a
generated `MutateDispatch`; an `Fn` callback over an FFI value type `T`, `&N`
of an object node type, or `AnyView<'_>`, or a consuming `MutationView<T>`,
followed by `&mut MutationContext<'_, State>`; or a tuple of up to 12 such
callbacks (tuples may nest)",
note = "callback arguments need explicit type annotations; use
`MutateCallbacks::new(state, callbacks)` for ordinary mutable callback state"
)]
pub trait IntoMutator<Marker> {
@@ -750,7 +753,7 @@ pub trait MutateChainLink<State, Marker>:
mutate_sealed::SealedLink<State, Marke
#[doc(hidden)]
fn try_mutate(
&self,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>>;
}
@@ -762,7 +765,7 @@ pub trait MutateChainLink<State, Marker>:
mutate_sealed::SealedLink<State, Marke
/// `mutate_*` methods in source order and passes the same [`Mutator`] to the
/// first match. The implementation owns its pass state and receives `&mut
/// self`, while [`Mutator`] controls recursion, the definition region, and
-/// in-place permission. Handlers can consume [`MutationValue`] and take an
+/// in-place permission. Handlers can consume [`MutationView`] and take an
/// optional `&mut Mutator` to inspect the region and in-place permission.
pub trait MutateDispatch: Sized {
fn dispatch_mutate(&mut self, value: AnyView<'_>, mutator: &mut Mutator)
@@ -772,14 +775,14 @@ pub trait MutateDispatch: Sized {
/// their copy-only default recursion; generated dispatch supports
consuming it.
fn dispatch_mutate_value(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
mutator: &mut Mutator,
) -> Option<Result<Any>> {
- self.dispatch_mutate(value.as_value(), mutator)
+ self.dispatch_mutate(value.as_any_view(), mutator)
}
#[doc(hidden)]
- fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationView<'_>, kind:
DefRegionKind) -> Result<Any> {
default_mutate_driver(self, value.value, kind,
value.permit(value.inplace_mode()))
}
}
@@ -792,14 +795,14 @@ impl<D: MutateDispatch> IntoMutator<ByMutateDispatch> for
D {
}
mod mutate_sealed {
- use super::{AnyView, IntoMutateResult, MutationContext, MutationValue,
ObjectCore};
+ use super::{AnyView, IntoMutateResult, MutationContext, MutationView,
ObjectCore};
pub trait SealedLink<State, Marker> {}
impl<F, State, T, O> SealedLink<State, super::ByMutateValue<T>> for F
where
F: for<'value, 'mutator, 'driver> Fn(
- MutationValue<'value, T>,
+ MutationView<'value, T>,
&'mutator mut MutationContext<'driver, State>,
) -> O,
O: IntoMutateResult,
@@ -843,7 +846,7 @@ pub struct ByMutateValue<T>(PhantomData<T>);
impl<F, State, T, O> MutateChainLink<State, ByMutateValue<T>> for F
where
F: for<'value, 'mutator, 'driver> Fn(
- MutationValue<'value, T>,
+ MutationView<'value, T>,
&'mutator mut MutationContext<'driver, State>,
) -> O,
T: crate::type_traits::ContainerElement,
@@ -851,7 +854,7 @@ where
{
fn try_mutate(
&self,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
match value
@@ -879,13 +882,13 @@ where
{
fn try_mutate(
&self,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
value
.as_ref()
.expect("unconsumed callback value")
- .as_value()
+ .as_any_view()
.try_as::<T>()
.map(|typed| self(typed, mutator).into_mutate_result())
}
@@ -905,13 +908,13 @@ where
{
fn try_mutate(
&self,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
value
.as_ref()
.expect("unconsumed callback value")
- .as_value()
+ .as_any_view()
.downcast_ref::<N>()
.map(|node| self(node, mutator).into_mutate_result())
}
@@ -930,7 +933,7 @@ where
{
fn try_mutate(
&self,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
Some(
@@ -938,7 +941,7 @@ where
value
.as_ref()
.expect("unconsumed callback value")
- .as_value(),
+ .as_any_view(),
mutator,
)
.into_mutate_result(),
@@ -965,7 +968,7 @@ macro_rules! impl_mutate_chain_link {
{
fn try_mutate(
&self,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
$(
@@ -1530,14 +1533,14 @@ pub trait StructuralMutator: Sized {
/// reuse path.
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
- self.dispatch_mutate(value.as_value(), def_region_kind)
+ self.dispatch_mutate(value.as_any_view(), def_region_kind)
}
#[doc(hidden)]
- fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationView<'_>, kind:
DefRegionKind) -> Result<Any> {
default_mutate_driver(self, value.value, kind,
value.permit(value.inplace_mode()))
}
@@ -1610,7 +1613,7 @@ pub trait StructuralMutator: Sized {
/// an owning alias after the capability was issued.
fn default_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
let mode = value.inplace_mode();
@@ -1626,7 +1629,7 @@ pub trait StructuralMutator: Sized {
/// the earlier uniqueness check after arbitrary user code has run.
fn default_maybe_inplace_mutate_with_mode(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
@@ -1667,7 +1670,7 @@ pub trait StructuralMutator: Sized {
/// Default mutation with the handle's existing permission, preserving
unchanged.
fn default_maybe_inplace_mutate_result(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
) -> Result<UnchangedOr<Any>> {
let mode = value.inplace_mode();
@@ -1679,7 +1682,7 @@ pub trait StructuralMutator: Sized {
/// Uses the same ownership checks as
[`Self::default_maybe_inplace_mutate_with_mode`].
fn default_maybe_inplace_mutate_with_mode_result(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<UnchangedOr<Any>> {
@@ -1700,7 +1703,7 @@ pub trait StructuralMutator: Sized {
}
impl<D: MutateDispatch> StructuralMutator for D {
- fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationView<'_>, kind:
DefRegionKind) -> Result<Any> {
MutateDispatch::on_default_mutate(self, value, kind)
}
@@ -1717,7 +1720,7 @@ impl<D: MutateDispatch> StructuralMutator for D {
};
match MutateDispatch::dispatch_mutate_value(
self,
- MutationValue::borrowed(value),
+ MutationView::borrowed(value),
&mut mutator,
) {
Some(result) => result,
@@ -1728,7 +1731,7 @@ impl<D: MutateDispatch> StructuralMutator for D {
#[inline(always)]
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
let raw = value.value;
@@ -1751,7 +1754,7 @@ impl<D: MutateDispatch> StructuralMutator for D {
pub fn default_mutate_with_policy<D: MutateDispatch + MutateCallbackState<D>>(
dispatch: &mut D,
policy: &impl MutationContextPolicy<D>,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
) -> Result<Any> {
policy::mutate_with_policy(
@@ -1768,7 +1771,7 @@ pub fn default_mutate_with_policy<D: MutateDispatch +
MutateCallbackState<D>>(
fn try_mutate_callbacks<State, Link, Marker, Driver>(
driver: &mut Driver,
callback_ptr: *const Link,
- value: &mut Option<MutationValue<'_>>,
+ value: &mut Option<MutationView<'_>>,
def_region_kind: DefRegionKind,
) -> Option<Result<Any>>
where
@@ -1800,13 +1803,13 @@ where
value: AnyView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
- self.dispatch_maybe_inplace_mutate(MutationValue::borrowed(value),
def_region_kind)
+ self.dispatch_maybe_inplace_mutate(MutationView::borrowed(value),
def_region_kind)
}
#[inline(always)]
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
let mut value = Some(value);
@@ -1827,7 +1830,7 @@ where
}
}
- fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationView<'_>, kind:
DefRegionKind) -> Result<Any> {
match self.policy.clone() {
Some(policy) => policy::mutate_with_policy(
&mut policy::MutationDescent { driver: self },
@@ -1852,13 +1855,13 @@ where
value: AnyView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
- self.dispatch_maybe_inplace_mutate(MutationValue::borrowed(value),
def_region_kind)
+ self.dispatch_maybe_inplace_mutate(MutationView::borrowed(value),
def_region_kind)
}
#[inline(always)]
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
let mut value = Some(value);
@@ -1911,7 +1914,7 @@ where
fn default_mutate_value(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
@@ -2697,7 +2700,7 @@ impl<D: MapDispatch, Policy: MutationContextPolicy<D>,
const PRE_ORDER: bool> Mu
policy::mutate_with_policy(
&mut policy::MutationDescent { driver: self },
policy.as_ref(),
- MutationValue::new(view, permit.inplace_mode(raw)),
+ MutationView::new(view, permit.inplace_mode(raw)),
kind,
)
}
@@ -3047,7 +3050,7 @@ fn dispatch_user_current_raw<U: StructuralMutator>(
// The engine keeps the input live for this call; the capability's
// inspection borrows remain bounded by the handle itself.
let view = unsafe { borrowed_view(&raw) };
- mutator.dispatch_maybe_inplace_mutate(MutationValue::new(view,
InplaceMode::Allow), kind)
+ mutator.dispatch_maybe_inplace_mutate(MutationView::new(view,
InplaceMode::Allow), kind)
} else {
mutator.dispatch_mutate(unsafe { borrowed_view(&raw) }, kind)
};
@@ -3062,7 +3065,7 @@ fn user_default_mutate<U: StructuralMutator>(
) -> Result<Any> {
with_mutation_region(def_region_kind, |kind| {
let value = unsafe { borrowed_view(&raw) };
- mutator.on_default_mutate(MutationValue::new(value,
permit.inplace_mode(raw)), kind)
+ mutator.on_default_mutate(MutationView::new(value,
permit.inplace_mode(raw)), kind)
})
.map_err(|error| with_value_context(error, raw))
}
diff --git a/rust/tvm-ffi/src/extra/structural_mutate/policy.rs
b/rust/tvm-ffi/src/extra/structural_mutate/policy.rs
index 5e042335..ea199923 100644
--- a/rust/tvm-ffi/src/extra/structural_mutate/policy.rs
+++ b/rust/tvm-ffi/src/extra/structural_mutate/policy.rs
@@ -32,7 +32,7 @@ pub trait MutationContextPolicy<State> {
/// Customize default descent, preserving the input permission and result
marker.
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>>;
}
@@ -43,7 +43,7 @@ pub struct DefaultMutationContextPolicy;
impl<State> MutationContextPolicy<State> for DefaultMutationContextPolicy {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
ctx.default_maybe_inplace_mutate_result(value)
@@ -55,7 +55,7 @@ impl<State, Outer: MutationContextPolicy<State>, Inner:
MutationContextPolicy<St
{
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
let kind = ctx.def_region_kind();
@@ -76,7 +76,7 @@ impl<State, Outer: MutationContextPolicy<State>, Inner:
MutationContextPolicy<St
pub(super) fn mutate_with_policy<State>(
driver: &mut dyn MutateContextDriver<State>,
policy: &impl MutationContextPolicy<State>,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
) -> Result<Any> {
let raw = value.value;
@@ -118,16 +118,11 @@ impl<State, Policy: MutationContextPolicy<State>>
MutateContextDriver<State>
}
fn default_mutate_borrowed(&mut self, value: AnyView<'_>, kind:
DefRegionKind) -> Result<Any> {
let view = value;
- mutate_with_policy(
- self.driver,
- self.policy,
- MutationValue::borrowed(view),
- kind,
- )
+ mutate_with_policy(self.driver, self.policy,
MutationView::borrowed(view), kind)
}
fn default_mutate_value(
&mut self,
- mut value: MutationValue<'_>,
+ mut value: MutationView<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
@@ -170,7 +165,7 @@ impl<State, Driver: MutationDriver +
MutateCallbackState<State>> MutateContextDr
}
fn default_mutate_value(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
diff --git a/rust/tvm-ffi/src/lib.rs b/rust/tvm-ffi/src/lib.rs
index e7bcd75c..65415420 100644
--- a/rust/tvm-ffi/src/lib.rs
+++ b/rust/tvm-ffi/src/lib.rs
@@ -56,7 +56,7 @@ pub use crate::extra::module::Module;
pub use crate::extra::structural_mutate::{
structural_map, structural_mutate, DefaultMutationContextPolicy,
InplaceMode, IntoMapper,
IntoMutator, MapChainLink, MapDispatch, MapWithContextPolicy,
MutateCallbacks, MutateChainLink,
- MutateDispatch, MutationContext, MutationContextPolicy, MutationValue,
Mutator,
+ MutateDispatch, MutationContext, MutationContextPolicy, MutationView,
Mutator,
StructuralMutator, StructuralVarRemap,
};
pub use crate::extra::structural_visit::{
diff --git a/rust/tvm-ffi/src/match_any_internal.rs
b/rust/tvm-ffi/src/match_any_internal.rs
index 8c785426..d89ad994 100644
--- a/rust/tvm-ffi/src/match_any_internal.rs
+++ b/rust/tvm-ffi/src/match_any_internal.rs
@@ -89,6 +89,64 @@ where
}
}
+/// Conversion for a shared `ref` binding, borrowing object nodes while
retaining
+/// the ordinary owning conversion for object handles and custom matchers.
+#[doc(hidden)]
+pub trait RefPatternConversion<'view, 'value, T> {
+ #[doc(hidden)]
+ type LeafPattern;
+
+ #[doc(hidden)]
+ fn leaf_pattern(&self) -> PhantomData<Self::LeafPattern> {
+ PhantomData
+ }
+
+ #[doc(hidden)]
+ type Holder: std::borrow::Borrow<T>;
+
+ #[doc(hidden)]
+ fn try_convert_ref(&self, view: &'view AnyView<'value>) ->
Result<Self::Holder, ()>;
+}
+
+// The macro starts at three references. Autoderef selects the first applicable
+// implementation: borrowed ObjectCore, AnyCompatible, then custom TryInto.
+impl<'view, 'value, T: crate::object::ObjectCore> RefPatternConversion<'view,
'value, T>
+ for &&PatternConversionProbe<T>
+{
+ type LeafPattern = BorrowedLeaf<T>;
+ type Holder = &'view T;
+
+ #[inline(always)]
+ fn try_convert_ref(&self, view: &'view AnyView<'value>) ->
Result<Self::Holder, ()> {
+ view.downcast_ref::<T>().ok_or(())
+ }
+}
+
+impl<'view, 'value, T: AnyCompatible> RefPatternConversion<'view, 'value, T>
+ for &PatternConversionProbe<T>
+{
+ type LeafPattern = T;
+ type Holder = T;
+
+ #[inline(always)]
+ fn try_convert_ref(&self, view: &'view AnyView<'value>) ->
Result<Self::Holder, ()> {
+ (*self).try_convert(*view)
+ }
+}
+
+impl<'view, 'value, T> RefPatternConversion<'view, 'value, T> for
PatternConversionProbe<T>
+where
+ AnyView<'value>: TryInto<T>,
+{
+ type LeafPattern = T;
+ type Holder = T;
+
+ #[inline(always)]
+ fn try_convert_ref(&self, view: &'view AnyView<'value>) ->
Result<Self::Holder, ()> {
+ (*view).try_into().map_err(|_| ())
+ }
+}
+
/// Runtime type-index lookup for one `match_any!` call site.
///
/// The smallest pattern `TypeIndex` is used as the base of a direct table.
@@ -192,11 +250,33 @@ where
}
}
+/// Lifetime-free metadata for a borrowed object node pattern.
+#[doc(hidden)]
+pub struct BorrowedLeaf<T>(PhantomData<fn() -> T>);
+
+impl<Head: crate::object::ObjectCore, Tail: LeafPatternList> LeafPatternList
+ for (BorrowedLeaf<Head>, Tail)
+{
+ const ALL_EXACT_LEAF: bool = Head::TYPE_FINAL && Tail::ALL_EXACT_LEAF;
+
+ #[inline(always)]
+ fn fill_leaf_type_indices(out: &mut [i32]) {
+ let (head, tail) = out.split_first_mut().expect("missing leaf pattern
slot");
+ *head = Head::type_index();
+ Tail::fill_leaf_type_indices(tail);
+ }
+}
+
/// Probe used by the macro to retain ordered matching for non-leaf patterns.
#[doc(hidden)]
pub struct LeafPatternProbe<T>(PhantomData<fn() -> T>);
impl<T> LeafPatternProbe<T> {
+ #[doc(hidden)]
+ pub fn prepend<Head>(self, _: PhantomData<Head>) ->
LeafPatternProbe<(Head, T)> {
+ LeafPatternProbe::new()
+ }
+
#[doc(hidden)]
pub const fn new() -> Self {
Self(PhantomData)
diff --git a/rust/tvm-ffi/tests/test_match_any.rs
b/rust/tvm-ffi/tests/test_match_any.rs
index 40fdd90b..bcc8d025 100644
--- a/rust/tvm-ffi/tests/test_match_any.rs
+++ b/rust/tvm-ffi/tests/test_match_any.rs
@@ -71,6 +71,66 @@ fn matches_concrete_object_containers_in_source_order() {
}
};
assert_eq!(matched_view, ("tensor", 2));
+
+ use tvm_ffi::collections::array::ArrayObj;
+ use tvm_ffi::{ObjectArc, ObjectRefCore};
+ let source = Array::new(vec![1_i64, 2, 3]);
+ let count = || ObjectArc::strong_count(<Array<i64> as
ObjectRefCore>::data(&source));
+ let size = match_any! {
+ source {
+ Array::<i64>(ref handle) if {
+ assert_eq!(count(), 2);
+ assert_eq!(handle.len(), 3);
+ false
+ } => unreachable!(),
+ ArrayObj(ref node) if {
+ let _: &ArrayObj = node;
+ assert_eq!(count(), 1);
+ assert_eq!(node.size, 3);
+ false
+ } => unreachable!(),
+ ArrayObj(ref node) => {
+ let _: &ArrayObj = node;
+ assert_eq!(count(), 1);
+ node.size
+ },
+ _ => 0,
+ }
+ };
+ assert_eq!(size, 3);
+ assert_eq!(count(), 1);
+ let size = match_any! {
+ source {
+ Array::<i64>(ref handle) => {
+ let _: &Array<i64> = handle;
+ assert_eq!(count(), 2);
+ handle.len()
+ },
+ _ => 0,
+ }
+ };
+ assert_eq!(size, 3);
+ assert_eq!(count(), 1);
+ let mut saved = None;
+ assert_eq!(
+ match_any! {
+ source {
+ Array::<i64>(ref handle) if { saved = Some(handle); true } =>
saved.unwrap().len(),
+ _ => 0,
+ }
+ },
+ 3
+ );
+ let node = 7;
+ assert_eq!(
+ match_any! {
+ source {
+ ArrayObj(ref node) if node.size == 0 => 0,
+ _ => node,
+ }
+ },
+ 7
+ );
}
#[test]
@@ -92,6 +152,15 @@ fn custom_try_into_matcher_keeps_ordered_compatibility() {
.unwrap();
assert!(matches(AnyView::from(&module)));
assert!(!matches(AnyView::from(&Shape::from([1_i64, 2]))));
+ assert!(match_any! {
+ module {
+ CustomModuleMatcher(ref matcher) => {
+ let _: &CustomModuleMatcher = matcher;
+ true
+ },
+ _ => false,
+ }
+ });
}
#[test]
diff --git a/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
b/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
index ad7ce02a..340d7c51 100644
--- a/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
+++ b/rust/tvm-ffi/tests/test_match_any_ast_lookup.rs
@@ -115,6 +115,20 @@ define_expr_leaves!(
fn dispatches_representative_ast_leaf_nodes() {
register_expr_types();
+ // The ref adapter must expose final-node metadata, including in mixed
lists.
+ use tvm_ffi::match_any_internal::{
+ LeafPatternMetadata, LeafPatternProbe, PatternConversionProbe,
RefPatternConversion,
+ };
+ let node_probe = PatternConversionProbe::<AddExprObj>::new();
+ let mixed = LeafPatternProbe::<(SubExpr,
())>::new().prepend((&&&node_probe).leaf_pattern());
+ assert!((&mixed).leaf_pattern_list_id().is_some());
+ let mut indices = [0; 2];
+ (&mixed).fill_leaf_type_indices(&mut indices);
+ assert_eq!(
+ indices,
+ [AddExprObj::type_index(), SubExprObj::type_index()]
+ );
+
fn classify(value: Any) -> &'static str {
match_any! {
value {
@@ -143,6 +157,40 @@ fn dispatches_representative_ast_leaf_nodes() {
}
}
+ fn checked<T>(_: &T, value: &Any, count: usize, name: &'static str) ->
&'static str {
+ assert_eq!(value.debug_strong_count(), Some(count));
+ name
+ }
+
+ fn classify_refs<T: ObjectCore>(value: &Any) -> &'static str {
+ match_any! {
+ *value {
+ T(ref node) => checked(node, value, 1, "add"),
+ SubExpr(ref handle) => checked(handle, value, 2, "sub"),
+ MulExprObj(ref node) => checked(node, value, 1, "mul"),
+ DivExpr(ref handle) => checked(handle, value, 2, "div"),
+ ModExprObj(ref node) => checked(node, value, 1, "mod"),
+ NegExpr(ref handle) => checked(handle, value, 2, "neg"),
+ CallExprObj(ref node) => checked(node, value, 1, "call"),
+ LetExpr(ref handle) => checked(handle, value, 2, "let"),
+ IfExprObj(ref node) => checked(node, value, 1, "if"),
+ TupleExpr(ref handle) => checked(handle, value, 2, "tuple"),
+ TupleGetItemExprObj(ref node) => checked(node, value, 1,
"tuple_get_item"),
+ CastExpr(ref handle) => checked(handle, value, 2, "cast"),
+ LoadExprObj(ref node) => checked(node, value, 1, "load"),
+ StoreExpr(ref handle) => checked(handle, value, 2, "store"),
+ ForExprObj(ref node) => checked(node, value, 1, "for"),
+ WhileExpr(ref handle) => checked(handle, value, 2, "while"),
+ SeqExprObj(ref node) => checked(node, value, 1, "seq"),
+ ReturnExpr(ref handle) => checked(handle, value, 2, "return"),
+ ConstantExprObj(ref node) => checked(node, value, 1,
"constant"),
+ VarExpr(ref handle) => checked(handle, value, 2, "var"),
+ AddExpr(_) => "duplicate_must_not_win",
+ _ => "unsupported",
+ }
+ }
+ }
+
let cases = [
(Any::from(AddExpr::default()), "add"),
(Any::from(SubExpr::default()), "sub"),
@@ -166,11 +214,21 @@ fn dispatches_representative_ast_leaf_nodes() {
(Any::from(VarExpr::default()), "var"),
];
for (value, expected) in cases {
+ for _ in 0..2 {
+ assert_eq!(classify_refs::<AddExprObj>(&value), expected);
+ assert_eq!(value.debug_strong_count(), Some(1));
+ }
assert_eq!(classify(value), expected);
}
assert_eq!(classify(Any::from(Shape::from([1_i64, 2]))), "unsupported");
assert_eq!(classify(Any::from(1_i64)), "unsupported");
+ // The call-site cache was initialized for AddExprObj; another generic
+ // instantiation must take the ordered path and preserve its first arm.
+ assert_eq!(
+ classify_refs::<SubExprObj>(&Any::from(SubExpr::default())),
+ "add"
+ );
// This call site has enough syntactically eligible arms to consider leaf
// lookup, but Array<T> requires complete type conversion. The entire match
@@ -197,7 +255,10 @@ fn dispatches_representative_ast_leaf_nodes() {
SeqExpr(_) => "seq",
ReturnExpr(_) => "return",
Array::<i64>(_) => "integer_array",
- Array::<f64>(_) => "float_array",
+ Array::<f64>(ref array) => {
+ assert_eq!(array.len(), 2);
+ "float_array"
+ },
_ => "unsupported",
}
}
diff --git a/rust/tvm-ffi/tests/test_structural_mutate.rs
b/rust/tvm-ffi/tests/test_structural_mutate.rs
index 715f1b19..724e3f17 100644
--- a/rust/tvm-ffi/tests/test_structural_mutate.rs
+++ b/rust/tvm-ffi/tests/test_structural_mutate.rs
@@ -25,7 +25,7 @@ use tvm_ffi::{
dispatch, structural_map, structural_mutate, structural_visit,
structural_walk, Any, AnyView,
Array, DefRegionKind, DefaultContextPolicy, DefaultMutationContextPolicy,
Error, FieldGetter,
Function, InplaceMode, IntoMapper, Map, MapDispatch, MapWithContextPolicy,
MutateCallbacks,
- MutationContext, MutationContextPolicy, MutationValue, Mutator, Object,
ObjectArc,
+ MutationContext, MutationContextPolicy, MutationView, Mutator, Object,
ObjectArc,
ObjectRefCore, Result, String as FfiString, StructuralMutator,
StructuralVarRemap,
StructuralVisitor, TypeIndex, Unchanged, UnchangedOr, VisitCallbacks,
VisitContext,
VisitInterrupt, WalkOrder, WalkResult, RUNTIME_ERROR,
@@ -65,7 +65,7 @@ impl StructuralMutator for ManualIncrement {
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
self.default_maybe_inplace_mutate(value, def_region_kind)
@@ -102,7 +102,7 @@ impl StructuralMutator for ReplaceNone {
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
self.default_maybe_inplace_mutate(value, def_region_kind)
@@ -146,7 +146,7 @@ impl StructuralMutator for RecursiveEntryMutator {
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
self.default_maybe_inplace_mutate(value, def_region_kind)
@@ -360,7 +360,7 @@ fn
default_mutation_mode_preserves_ownership_and_unchanged_results() {
}
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
kind: DefRegionKind,
) -> Result<Any> {
if self.increment {
@@ -400,7 +400,7 @@ fn
borrowed_capabilities_cannot_enable_low_level_default_reuse() {
assert_eq!(value.try_as::<bool>(), Some(true));
let source = Array::new(vec![1_i64]);
let pointer = array_pointer(&source);
- let value = MutationValue::borrowed(AnyView::from(&source));
+ let value = MutationView::borrowed(AnyView::from(&source));
assert_eq!(value.inplace_mode(), InplaceMode::Disallow);
// A count of one is insufficient: this handle only borrows source.
assert_eq!(
@@ -442,7 +442,7 @@ fn
borrowed_capabilities_keep_their_mode_in_dispatch_adapters() {
impl Inspect {
fn mutate_array(
&mut self,
- value: tvm_ffi::MutationValue<'_, Array<i64>>,
+ value: tvm_ffi::MutationView<'_, Array<i64>>,
ctx: &mut Mutator,
) -> Unchanged {
assert_eq!(value.inplace_mode(), InplaceMode::Disallow);
@@ -453,7 +453,7 @@ fn
borrowed_capabilities_keep_their_mode_in_dispatch_adapters() {
let source = Array::new(vec![1_i64]);
let result = StructuralMutator::dispatch_maybe_inplace_mutate(
&mut Inspect,
- MutationValue::borrowed(AnyView::from(&source)),
+ MutationView::borrowed(AnyView::from(&source)),
DefRegionKind::None,
)
.unwrap();
@@ -461,7 +461,7 @@ fn
borrowed_capabilities_keep_their_mode_in_dispatch_adapters() {
let mut callbacks = MutateCallbacks::new(
(),
- |value: MutationValue<'_, Array<i64>>, ctx: &mut MutationContext<'_>| {
+ |value: MutationView<'_, Array<i64>>, ctx: &mut MutationContext<'_>| {
assert_eq!(value.inplace_mode(), InplaceMode::Disallow);
assert_eq!(ctx.inplace_mode(), value.inplace_mode());
Unchanged
@@ -469,7 +469,7 @@ fn
borrowed_capabilities_keep_their_mode_in_dispatch_adapters() {
);
let result = callbacks
.dispatch_maybe_inplace_mutate(
- MutationValue::borrowed(AnyView::from(&source)),
+ MutationView::borrowed(AnyView::from(&source)),
DefRegionKind::None,
)
.unwrap();
@@ -545,15 +545,15 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
modes: Vec<InplaceMode>,
}
impl Forward {
- fn observe(&mut self, value: &MutationValue<'_, Array<Any>>) {
+ fn observe(&mut self, value: &MutationView<'_, Array<Any>>) {
self.modes.push(value.inplace_mode());
- let view = value.as_value();
+ let view = value.as_any_view();
let node = view
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.unwrap();
assert_eq!(node.size, 1);
// A temporary typed handle must not permanently revoke permission.
- let temporary = value.as_value().try_as::<Array<Any>>().unwrap();
+ let temporary =
value.as_any_view().try_as::<Array<Any>>().unwrap();
if self.retain && self.alias.is_none() {
self.alias = Some(temporary.clone().into());
}
@@ -562,12 +562,12 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
}
#[dispatch(mutate)]
impl Forward {
- fn mutate_string(&mut self, _: MutationValue<'_, FfiString>) -> Any {
+ fn mutate_string(&mut self, _: MutationView<'_, FfiString>) -> Any {
panic!("typed miss must preserve the capability for the next
handler")
}
fn mutate_array(
&mut self,
- value: MutationValue<'_, Array<Any>>,
+ value: MutationView<'_, Array<Any>>,
ctx: &mut Mutator,
) -> Result<UnchangedOr<Any>> {
assert_eq!(ctx.inplace_mode(), value.inplace_mode());
@@ -601,12 +601,12 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
let result = if generated {
structural_mutate(root, &mut state).unwrap()
} else {
- let miss = |_: MutationValue<'_, FfiString>,
+ let miss = |_: MutationView<'_, FfiString>,
_: &mut MutationContext<'_, Forward>|
-> Any { panic!("typed miss must continue") };
let increment = |value: i64, _: &mut MutationContext<'_,
Forward>| value + 1;
let descend =
- |value: MutationValue<'_, Array<Any>>,
+ |value: MutationView<'_, Array<Any>>,
ctx: &mut MutationContext<'_, Forward>| {
assert_eq!(value.inplace_mode(), ctx.inplace_mode());
ctx.state_mut().observe(&value);
@@ -642,7 +642,7 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
#[test]
fn consuming_default_descent_transfers_between_contexts_without_node_borrows()
{
struct Inner<'a> {
- value: Option<MutationValue<'a>>,
+ value: Option<MutationView<'a>>,
preserve_unchanged: bool,
result: Any,
}
@@ -662,12 +662,12 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
}
}
fn transfer(
- value: MutationValue<'_>,
+ value: MutationView<'_>,
generated: bool,
preserve: bool,
retain: bool,
) -> Result<Any> {
- let alias = retain.then(||
value.as_value().try_as::<Array<i64>>().unwrap());
+ let alias = retain.then(||
value.as_any_view().try_as::<Array<i64>>().unwrap());
assert_eq!(value.inplace_mode(), InplaceMode::Allow);
// Carry the result back to the array callback: Unchanged belongs to
// that input, not to the nested traversal's boolean root.
@@ -710,7 +710,7 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
}
#[dispatch(mutate)]
impl Outer {
- fn mutate_any(&mut self, value: MutationValue<'_>) -> Result<Any> {
+ fn mutate_any(&mut self, value: MutationView<'_>) -> Result<Any> {
transfer(value, true, self.preserve, self.retain)
}
}
@@ -724,7 +724,7 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
} else {
structural_mutate(
root,
- |value: MutationValue<'_>, _: &mut
MutationContext<'_>| {
+ |value: MutationView<'_>, _: &mut MutationContext<'_>|
{
transfer(value, false, preserve, retain)
},
)
@@ -745,8 +745,8 @@ fn
consuming_default_descent_preserves_unchanged_and_propagates_errors() {
let pointer = array_pointer(&root);
let result = structural_mutate(
root,
- |value: MutationValue<'_>, ctx: &mut MutationContext<'_>| ->
Result<UnchangedOr<Any>> {
- if value.as_value().try_as::<i64>().is_some() {
+ |value: MutationView<'_>, ctx: &mut MutationContext<'_>| ->
Result<UnchangedOr<Any>> {
+ if value.as_any_view().try_as::<i64>().is_some() {
return if fail {
Err(Error::new(RUNTIME_ERROR, "child failed", ""))
} else {
@@ -857,8 +857,8 @@ fn
callback_errors_preserve_message_and_add_object_context() {
}
#[dispatch(mutate, policy = (DefaultMutationContextPolicy,
DefaultMutationContextPolicy))]
impl Delegate {
- fn mutate_any(&mut self, value: MutationValue<'_>, ctx: &mut Mutator)
-> Result<Any> {
- if value.as_value().try_as::<i64>().is_some() {
+ fn mutate_any(&mut self, value: MutationView<'_>, ctx: &mut Mutator)
-> Result<Any> {
+ if value.as_any_view().try_as::<i64>().is_some() {
return Err(self.0.clone());
}
ctx.default_maybe_inplace_mutate(self, value)
@@ -957,8 +957,8 @@ fn
callback_errors_preserve_message_and_add_object_context() {
.with_policy((DefaultContextPolicy, DefaultContextPolicy));
errors.push(structural_visit(&root, &mut visitor).err().unwrap());
let mut mutator =
- MutateCallbacks::new((), |value: MutationValue<'_>, ctx: &mut
MutationContext| {
- if value.as_value().try_as::<i64>().is_some() {
+ MutateCallbacks::new((), |value: MutationView<'_>, ctx: &mut
MutationContext| {
+ if value.as_any_view().try_as::<i64>().is_some() {
return Err(source.clone());
}
ctx.default_maybe_inplace_mutate(value)
@@ -1397,10 +1397,10 @@ fn pre_order_mapping_preserves_inplace_permission() {
impl<State> MutationContextPolicy<State> for Observe<'_> {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut tvm_ffi::MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
- if value.as_value().type_index() >=
TypeIndex::kTVMFFIStaticObjectBegin as i32 {
+ if value.as_any_view().type_index() >=
TypeIndex::kTVMFFIStaticObjectBegin as i32 {
self.0.set(Some(value.inplace_mode()));
}
ctx.default_maybe_inplace_mutate_result(value)
@@ -2096,11 +2096,11 @@ struct ArrayPolicy;
impl MutationContextPolicy<PolicyState> for ArrayPolicy {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, PolicyState>,
) -> Result<UnchangedOr<Any>> {
if value
- .as_value()
+ .as_any_view()
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.is_none()
{
@@ -2120,11 +2120,11 @@ struct RecordPolicy;
impl MutationContextPolicy<PolicyState> for RecordPolicy {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, PolicyState>,
) -> Result<UnchangedOr<Any>> {
if value
- .as_value()
+ .as_any_view()
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.is_some()
{
@@ -2198,7 +2198,7 @@ fn
mutation_policies_share_state_and_preserve_callback_order() {
ctx.state_mut().events.push(("integer", depth));
x + 1
},
- |value: MutationValue<'_>, ctx: &mut MutationContext<'_,
PolicyState>| {
+ |value: MutationView<'_>, ctx: &mut MutationContext<'_,
PolicyState>| {
let depth = ctx.state().depth;
ctx.state_mut().events.push(("callback", depth));
ctx.default_maybe_inplace_mutate_result(value)
@@ -2233,7 +2233,7 @@ fn
map_policy_entries_preserve_descent_and_callback_composition() {
impl<State> MutationContextPolicy<State> for Stop {
fn default_mutate(
&self,
- _: MutationValue<'_>,
+ _: MutationView<'_>,
_: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
Ok(UnchangedOr::unchanged())
@@ -2294,15 +2294,15 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
impl MutationContextPolicy<Ownership> for Control {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, Ownership>,
) -> Result<UnchangedOr<Any>> {
let array = value
- .as_value()
+ .as_any_view()
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.is_some();
if array && self.retain {
- ctx.state_mut().retained = Some(Any::from(value.as_value()));
+ ctx.state_mut().retained =
Some(Any::from(value.as_any_view()));
}
let result = ctx.default_mutate_with_mode_result(value,
self.mode)?;
if array && !ctx.state().increment {
@@ -2321,7 +2321,7 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
}
fn mutate_array(
&mut self,
- value: MutationValue<'_, Array<i64>>,
+ value: MutationView<'_, Array<i64>>,
mutator: &mut Mutator,
) -> Result<UnchangedOr<Any>> {
mutator.default_maybe_inplace_mutate_result(self, value)
@@ -2376,7 +2376,7 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
|x: i64, ctx: &mut MutationContext<'_, Ownership>|
{
ctx.state_mut().map_integer(x)
},
- |value: MutationValue<'_>, ctx: &mut
MutationContext<'_, Ownership>| {
+ |value: MutationView<'_>, ctx: &mut
MutationContext<'_, Ownership>| {
ctx.default_maybe_inplace_mutate_result(value)
},
),
@@ -2419,17 +2419,17 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
impl MutationContextPolicy<Regions> for Redirect {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, Regions>,
) -> Result<UnchangedOr<Any>> {
- if value.as_value().try_as::<bool>() == Some(false) {
+ if value.as_any_view().try_as::<bool>() == Some(false) {
// Bypass this container's callback, but enter the next policy
and redispatch its children.
return ctx.with_def_region_kind(Pattern, |ctx| {
ctx.default_mutate(&Array::new(vec![1_i64]))
.map(UnchangedOr::changed)
});
}
- if value.as_value().try_as::<i64>() == Some(2) {
+ if value.as_any_view().try_as::<i64>() == Some(2) {
assert_eq!(ctx.def_region_kind(), Pattern);
ctx.mutate_with(&99_i64, self.0)?;
let error: Result<()> = ctx.with_def_region_kind(Use, |ctx| {
@@ -2446,11 +2446,11 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
impl MutationContextPolicy<Regions> for Observe {
fn default_mutate(
&self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
ctx: &mut MutationContext<'_, Regions>,
) -> Result<UnchangedOr<Any>> {
if value
- .as_value()
+ .as_any_view()
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.is_some()
{
@@ -2465,14 +2465,14 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
impl Regions {
fn mutate_any(
&mut self,
- value: MutationValue<'_>,
+ value: MutationView<'_>,
mutator: &mut Mutator,
) -> Result<UnchangedOr<Any>> {
- if let Some(x) = value.as_value().try_as::<i64>() {
+ if let Some(x) = value.as_any_view().try_as::<i64>() {
self.map_integer(x, mutator.def_region_kind());
}
if value
- .as_value()
+ .as_any_view()
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.is_some()
{
@@ -2511,13 +2511,13 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
}
let mut mutator = MutateCallbacks::new(
Regions::default(),
- |value: MutationValue<'_>, ctx: &mut MutationContext<'_, Regions>|
{
- if let Some(x) = value.as_value().try_as::<i64>() {
+ |value: MutationView<'_>, ctx: &mut MutationContext<'_, Regions>| {
+ if let Some(x) = value.as_any_view().try_as::<i64>() {
let kind = ctx.def_region_kind();
ctx.state_mut().0.push((x, kind));
}
if value
- .as_value()
+ .as_any_view()
.downcast_ref::<tvm_ffi::collections::array::ArrayObj>()
.is_some()
{
@@ -2564,7 +2564,7 @@ fn
mutation_policy_halts_restore_state_and_skip_later_policies() {
impl MutationContextPolicy<PolicyState> for Halt {
fn default_mutate(
&self,
- _: MutationValue<'_>,
+ _: MutationView<'_>,
_: &mut MutationContext<'_, PolicyState>,
) -> Result<UnchangedOr<Any>> {
if self.0 {