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 b80178f4 [REFACTOR][Rust] Unify mutation capabilities and context
names (#894)
b80178f4 is described below
commit b80178f4dde2f05b1eed4817d8af3bf0d87d35eb
Author: Tianqi Chen <[email protected]>
AuthorDate: Sun Nov 1 21:48:03 2026 -0500
[REFACTOR][Rust] Unify mutation capabilities and context names (#894)
Use one mode-carrying `MutationValue` for low-level structural mutation,
typed callbacks and policies. Consuming handles preserve inspection
borrow bounds, combine stored and requested permissions, and retain the
uniqueness checks needed for copy-on-write.
Rename the related interfaces to `MutationContext`,
`MutationContextPolicy` and `DefaultMutationContextPolicy`, with
matching exports, macro handling and guide examples. Keep `Mutator`,
dispatch/callback APIs and map-policy composition unchanged. A small
permission helper exposes constant-mode checks to inlining.
---
docs/guides/rust_lang_guide.md | 29 +-
rust/tvm-ffi-macros/src/dispatch.rs | 8 +-
rust/tvm-ffi-macros/src/lib.rs | 2 +-
rust/tvm-ffi/src/extra/structural_mutate.rs | 340 +++++++++------------
rust/tvm-ffi/src/extra/structural_mutate/policy.rs | 57 ++--
rust/tvm-ffi/src/lib.rs | 6 +-
rust/tvm-ffi/tests/test_structural_mutate.rs | 296 ++++++++++++------
7 files changed, 394 insertions(+), 344 deletions(-)
diff --git a/docs/guides/rust_lang_guide.md b/docs/guides/rust_lang_guide.md
index 242cec14..95be3bdc 100644
--- a/docs/guides/rust_lang_guide.md
+++ b/docs/guides/rust_lang_guide.md
@@ -728,8 +728,8 @@ Within one `structural_map` call, callbacks run at every
occurrence; their
results are not cached. Default recursion manages identity remapping with
the same semantics as C++.
-`MutateCallbacks::with_policy` and `MapWithContextPolicy` use
`MutContextPolicy<State>`
-to manage context around default recursion. Policies consume `MutateValue`
+`MutateCallbacks::with_policy` and `MapWithContextPolicy` use
`MutationContextPolicy<State>`
+to manage context around default recursion. Policies consume `MutationValue`
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;
@@ -758,12 +758,12 @@ owning-value helpers and top-level functions resolve the
marker to the
original value.
`structural_mutate` accepts typed callback chains in addition to a
-`StructuralMutator`. Closure callbacks receive a `MutateContext`;
+`StructuralMutator`. Closure callbacks receive a `MutationContext`;
`MutateCallbacks` adds state shared by that callback chain:
```rust
use tvm_ffi::{
- structural_mutate, Array, MutateCallbacks, MutateContext, MutateValue,
+ structural_mutate, Array, MutateCallbacks, MutationContext, MutationValue,
};
#[derive(Default)]
@@ -774,11 +774,11 @@ struct Stats {
let mut mutator = MutateCallbacks::new(
Stats::default(),
(
- |value: i64, mutator: &mut MutateContext<'_, Stats>| {
+ |value: i64, mutator: &mut MutationContext<'_, Stats>| {
mutator.state_mut().integers += 1;
value + 1
},
- |value: MutateValue<'_>, mutator: &mut MutateContext<'_, Stats>| {
+ |value: MutationValue<'_>, mutator: &mut MutationContext<'_, Stats>| {
mutator.default_maybe_inplace_mutate(value)
},
),
@@ -789,17 +789,17 @@ assert_eq!(mutated.iter().collect::<Vec<_>>(), vec![2,
3]);
assert_eq!(mutator.state().integers, 2);
```
-`MutateContext::mutate` uses the copy path for a borrowed value, while
+`MutationContext::mutate` uses the copy path for a borrowed value, while
`maybe_inplace_mutate` preserves the reuse opportunity of an owned value.
Closure callbacks are `Fn`; mutable data belongs in the callback state.
-Use `MutateValue<'_, T>` with `default_maybe_inplace_mutate` to forward its
+Use `MutationValue<'_, 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
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 `MutateValue` for ownership
requirements.
+through `Mutator::inplace_mode()`; see `MutationValue` for ownership
requirements.
`#[dispatch(mutate)]` groups typed `mutate_*` callbacks. The dispatch object
owns its mutable pass state, while `Mutator` supplies recursion and the current
@@ -835,12 +835,13 @@ assert_eq!(mutated.iter().collect::<Vec<_>>(), vec![2,
3]);
assert_eq!(increment.integers, 2);
```
-Use `#[dispatch(mutate, policy = MyPolicy)]` to apply a
`MutContextPolicy<Self>`
+Use `#[dispatch(mutate, policy = MyPolicy)]` to apply a
`MutationContextPolicy<Self>`
to default recursion.
For low-level custom recursion, implement `StructuralMutator` and pass
-`&mut` it to `structural_mutate`. `InplaceValue` is an engine-issued
-capability: callers cannot construct it from a read-only `AnyView`. Override
+`&mut` it to `structural_mutate`. `MutationValue` carries the engine's reuse
+permission. `MutationValue::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
values can be re-entered with `mutate`, while owned values can use
@@ -848,7 +849,7 @@ values can be re-entered with `mutate`, while owned values
can use
```rust
use tvm_ffi::{
- structural_mutate, Any, Array, DefRegionKind, InplaceValue, AnyView,
Result,
+ structural_mutate, Any, Array, DefRegionKind, MutationValue, AnyView,
Result,
StructuralMutator,
};
@@ -865,7 +866,7 @@ impl StructuralMutator for Increment {
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
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 ea5339e1..63301289 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::MutateValue<'_>,
+ value: #tvm_ffi::MutationValue<'_>,
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::MutateValue::borrowed(value), mutator,
+ self, #tvm_ffi::MutationValue::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::MutateValue<'_>,
+ mut value: #tvm_ffi::MutationValue<'_>,
mutator: &mut #tvm_ffi::Mutator,
) -> Option<#tvm_ffi::Result<#tvm_ffi::Any>> {
#(#links)*
@@ -499,7 +499,7 @@ fn parse_handler(method: &ImplItemMethod, mode:
DispatchMode) -> syn::Result<Han
.path
.segments
.last()
- .is_some_and(|s| s.ident == "MutateValue") =>
+ .is_some_and(|s| s.ident == "MutationValue") =>
{
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 7e43b8db..958b1e57 100644
--- a/rust/tvm-ffi-macros/src/lib.rs
+++ b/rust/tvm-ffi-macros/src/lib.rs
@@ -30,7 +30,7 @@ mod utils;
/// Generate `walk`, `map`, `visit`, or `mutate` dispatch from an inherent
impl.
///
/// `#[dispatch(visit, policy = expr)]` and `#[dispatch(mutate, policy =
expr)]`
-/// use a `ContextPolicy<Self>` or `MutContextPolicy<Self>` for default
recursion.
+/// use a `ContextPolicy<Self>` or `MutationContextPolicy<Self>` for default
recursion.
/// The expression runs at each default descent and may read `self` for
configuration;
/// mutable traversal state stays on `self`. Policy tuples compose as usual.
#[proc_macro_error]
diff --git a/rust/tvm-ffi/src/extra/structural_mutate.rs
b/rust/tvm-ffi/src/extra/structural_mutate.rs
index 69d945d7..fda61db8 100644
--- a/rust/tvm-ffi/src/extra/structural_mutate.rs
+++ b/rust/tvm-ffi/src/extra/structural_mutate.rs
@@ -66,7 +66,7 @@ const FLAG_SEQ_HASH_IGNORE: i64 =
kTVMFFIFieldFlagBitMaskSEqHashIgnore as i64;
const FLAG_SETTER_IS_FUNCTION: i64 = kTVMFFIFieldFlagBitSetterIsFunctionObj as
i64;
mod policy;
-pub use policy::{DefaultMutContextPolicy, MapWithContextPolicy,
MutContextPolicy};
+pub use policy::{DefaultMutationContextPolicy, MapWithContextPolicy,
MutationContextPolicy};
mod callback_result_sealed {
use super::{Any, Result};
@@ -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
-/// [`InplaceValue`] with the mode-aware mutation helpers.
+/// [`MutationValue`] with the mode-aware mutation helpers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InplaceMode {
/// Use ordinary mutation, including for uniquely owned values.
@@ -123,17 +123,9 @@ impl InplaceMode {
Self::Allow => Permit::MaybeInPlace,
}
}
-
- fn permit_if_unique(self, raw: TVMFFIAny) -> Permit {
- if self == Self::Allow && object_is_unique(raw) {
- Permit::MaybeInPlace
- } else {
- Permit::Copy
- }
- }
}
-/// A callback value carrying the engine's in-place permission.
+/// A mutation value carrying the engine's in-place permission.
///
/// Unlike an owning typed argument, this handle does not increment the
reference
/// count. Borrow through it to inspect the node, then consume it in
@@ -141,11 +133,13 @@ impl InplaceMode {
/// still forces copying. Node borrows come from this handle, not from the
/// callback context, so the handle can safely be passed to another context.
/// `T` selects the callback's matched FFI type; `Any` matches every value.
+/// The same handle is used by low-level [`StructuralMutator`] hooks. A
publicly
+/// borrowed handle always disallows reuse; only the engine can issue
permission.
///
/// A node borrowed through a copied view cannot survive consumption of the
handle:
/// ```compile_fail,E0505
-/// use tvm_ffi::{MutateContext, MutateValue};
-/// fn invalid(value: MutateValue<'_>, ctx: &mut MutateContext<'_>) {
+/// use tvm_ffi::{MutationContext, MutationValue};
+/// fn invalid(value: MutationValue<'_>, ctx: &mut MutationContext<'_>) {
/// let view = value.as_value();
/// let copy = view;
/// let node =
copy.downcast_ref::<tvm_ffi::collections::array::ArrayObj>().unwrap();
@@ -157,18 +151,29 @@ 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, MutateContext, MutateValue};
-/// fn invalid(value: MutateValue<'_>) {
+/// use tvm_ffi::{structural_mutate, MutationContext, MutationValue};
+/// fn invalid(value: MutationValue<'_>) {
/// let view = value.as_value();
/// let node =
view.downcast_ref::<tvm_ffi::collections::array::ArrayObj>().unwrap();
/// let pending = RefCell::new(Some(value));
-/// structural_mutate(true, |_: bool, inner: &mut MutateContext<'_>| {
+/// structural_mutate(true, |_: bool, inner: &mut MutationContext<'_>| {
///
inner.default_maybe_inplace_mutate(pending.borrow_mut().take().unwrap())
/// }).unwrap();
/// println!("{}", node.size);
/// }
/// ```
-pub struct MutateValue<'a, T = Any> {
+///
+/// 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();
+/// let copy = view;
+/// mutator.default_maybe_inplace_mutate(value,
DefRegionKind::None).unwrap();
+/// println!("{}", copy.type_index());
+/// }
+/// ```
+pub struct MutationValue<'a, T = Any> {
value: TVMFFIAny,
mode: InplaceMode,
_scope: PhantomData<AnyView<'a>>,
@@ -176,7 +181,7 @@ pub struct MutateValue<'a, T = Any> {
_not_send_sync: PhantomData<Rc<()>>,
}
-impl<'a> MutateValue<'a> {
+impl<'a> MutationValue<'a> {
fn new(value: AnyView<'a>, mode: InplaceMode) -> Self {
Self {
value: raw_of(value),
@@ -193,7 +198,7 @@ impl<'a> MutateValue<'a> {
}
}
-impl<'a, T> MutateValue<'a, T> {
+impl<'a, T> MutationValue<'a, T> {
/// Permission established before callback arguments acquire ownership.
pub fn inplace_mode(&self) -> InplaceMode {
self.mode
@@ -210,11 +215,11 @@ impl<'a, T> MutateValue<'a, T> {
/// Narrow the matched type without acquiring an owning reference.
pub fn try_cast<U: crate::type_traits::ContainerElement>(
self,
- ) -> std::result::Result<MutateValue<'a, U>, Self> {
+ ) -> std::result::Result<MutationValue<'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(MutateValue {
+ Ok(MutationValue {
value: self.value,
mode: self.mode,
_scope: PhantomData,
@@ -227,8 +232,8 @@ impl<'a, T> MutateValue<'a, T> {
}
/// Erase the matched type while preserving the engine-issued permission.
- pub fn into_untyped(self) -> MutateValue<'a> {
- MutateValue {
+ pub fn into_untyped(self) -> MutationValue<'a> {
+ MutationValue {
value: self.value,
mode: self.mode,
_scope: PhantomData,
@@ -253,7 +258,7 @@ impl<'a, T> MutateValue<'a, T> {
/// reborrow the mutator, so mutable state cannot remain borrowed across them.
/// The context does not store a node: inspect the callback argument and pass
/// it explicitly to default recursion.
-pub struct MutateContext<'a, State = ()> {
+pub struct MutationContext<'a, State = ()> {
driver: &'a mut dyn MutateContextDriver<State>,
def_region_kind: DefRegionKind,
inplace_mode: InplaceMode,
@@ -276,7 +281,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 [`MutateValue`].
+ /// requires consuming a [`MutationValue`].
pub fn inplace_mode(&self) -> InplaceMode {
self.inplace_mode
}
@@ -417,7 +422,7 @@ impl Mutator {
pub fn default_maybe_inplace_mutate<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
) -> Result<Any> {
let mode = value.inplace_mode();
self.default_mutate_with_mode(dispatch, value, mode)
@@ -428,7 +433,7 @@ impl Mutator {
pub fn default_maybe_inplace_mutate_result<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
) -> Result<UnchangedOr<Any>> {
let mode = value.inplace_mode();
self.default_mutate_with_mode_result(dispatch, value, mode)
@@ -441,7 +446,7 @@ impl Mutator {
pub fn default_mutate_with_mode<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
mode: InplaceMode,
) -> Result<Any> {
let raw = value.value;
@@ -454,7 +459,7 @@ impl Mutator {
pub fn default_mutate_with_mode_result<D: MutateDispatch, T>(
&mut self,
dispatch: &mut D,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
mode: InplaceMode,
) -> Result<UnchangedOr<Any>> {
let permit = value.permit(mode);
@@ -484,7 +489,7 @@ impl Mutator {
}
}
-/// Internal operations used by [`MutateContext`].
+/// Internal operations used by [`MutationContext`].
///
/// Borrowed inputs carry a lifetime; in-place entry requires an owned
/// value or a consumed capability, never a bare ABI value plus permission.
@@ -497,7 +502,7 @@ trait MutateContextDriver<State> {
/// Consume the handle to exclude node borrows before default descent.
fn default_mutate_value(
&mut self,
- value: MutateValue<'_>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
_mode: InplaceMode,
) -> Result<Any> {
@@ -507,7 +512,7 @@ trait MutateContextDriver<State> {
fn var_remap_set(&mut self, var: AnyView<'_>, mutated_value: &Any) ->
Result<()>;
}
-impl<State> MutateContext<'_, State> {
+impl<State> MutationContext<'_, State> {
/// User state shared by every callback in this mutation.
#[inline(always)]
pub fn state(&self) -> &State {
@@ -523,7 +528,7 @@ impl<State> MutateContext<'_, 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 [`MutateValue`].
+ /// requires consuming a [`MutationValue`].
pub fn inplace_mode(&self) -> InplaceMode {
self.inplace_mode
}
@@ -539,10 +544,10 @@ impl<State> MutateContext<'_, State> {
pub fn with_def_region_kind<T>(
&mut self,
kind: DefRegionKind,
- callback: impl FnOnce(&mut MutateContext<'_, State>) -> Result<T>,
+ callback: impl FnOnce(&mut MutationContext<'_, State>) -> Result<T>,
) -> Result<T> {
with_mutation_region(kind, |kind| {
- callback(&mut MutateContext {
+ callback(&mut MutationContext {
driver: &mut *self.driver,
def_region_kind: kind,
inplace_mode: self.inplace_mode,
@@ -663,7 +668,7 @@ impl<State> MutateContext<'_, State> {
/// Consume the handle for default descent with its existing permission.
#[inline]
- pub fn default_maybe_inplace_mutate<T>(&mut self, value: MutateValue<'_,
T>) -> Result<Any> {
+ pub fn default_maybe_inplace_mutate<T>(&mut self, value: MutationValue<'_,
T>) -> Result<Any> {
let mode = value.inplace_mode();
self.default_mutate_with_mode(value, mode)
}
@@ -672,7 +677,7 @@ impl<State> MutateContext<'_, State> {
#[inline]
pub fn default_maybe_inplace_mutate_result<T>(
&mut self,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
) -> Result<UnchangedOr<Any>> {
let mode = value.inplace_mode();
self.default_mutate_with_mode_result(value, mode)
@@ -685,7 +690,7 @@ impl<State> MutateContext<'_, State> {
/// before this call to preserve reuse of the current value.
pub fn default_mutate_with_mode<T>(
&mut self,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
mode: InplaceMode,
) -> Result<Any> {
let raw = value.value;
@@ -697,7 +702,7 @@ impl<State> MutateContext<'_, State> {
/// Consume the callback value for default descent, preserving `Unchanged`.
pub fn default_mutate_with_mode_result<T>(
&mut self,
- value: MutateValue<'_, T>,
+ value: MutationValue<'_, T>,
mode: InplaceMode,
) -> Result<UnchangedOr<Any>> {
self.driver
@@ -726,7 +731,7 @@ impl<State> MutateContext<'_, 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 `MutateValue<T>`,
followed by `&mut MutateContext<'_, 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 `MutationValue<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> {
@@ -745,8 +750,8 @@ pub trait MutateChainLink<State, Marker>:
mutate_sealed::SealedLink<State, Marke
#[doc(hidden)]
fn try_mutate(
&self,
- value: &mut Option<MutateValue<'_>>,
- mutator: &mut MutateContext<'_, State>,
+ value: &mut Option<MutationValue<'_>>,
+ mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>>;
}
@@ -757,7 +762,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 [`MutateValue`] and take an
+/// in-place permission. Handlers can consume [`MutationValue`] 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)
@@ -767,14 +772,14 @@ pub trait MutateDispatch: Sized {
/// their copy-only default recursion; generated dispatch supports
consuming it.
fn dispatch_mutate_value(
&mut self,
- value: MutateValue<'_>,
+ value: MutationValue<'_>,
mutator: &mut Mutator,
) -> Option<Result<Any>> {
self.dispatch_mutate(value.as_value(), mutator)
}
#[doc(hidden)]
- fn on_default_mutate(&mut self, value: MutateValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
default_mutate_driver(self, value.value, kind,
value.permit(value.inplace_mode()))
}
}
@@ -787,15 +792,15 @@ impl<D: MutateDispatch> IntoMutator<ByMutateDispatch> for
D {
}
mod mutate_sealed {
- use super::{AnyView, IntoMutateResult, MutateContext, MutateValue,
ObjectCore};
+ use super::{AnyView, IntoMutateResult, MutationContext, MutationValue,
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(
- MutateValue<'value, T>,
- &'mutator mut MutateContext<'driver, State>,
+ MutationValue<'value, T>,
+ &'mutator mut MutationContext<'driver, State>,
) -> O,
O: IntoMutateResult,
{
@@ -803,7 +808,7 @@ mod mutate_sealed {
impl<F, State, T, O> SealedLink<State, super::ByMutateOwned<T>> for F
where
- F: for<'mutator, 'driver> Fn(T, &'mutator mut MutateContext<'driver,
State>) -> O,
+ F: for<'mutator, 'driver> Fn(T, &'mutator mut MutationContext<'driver,
State>) -> O,
O: IntoMutateResult,
{
}
@@ -812,7 +817,7 @@ mod mutate_sealed {
where
F: for<'value, 'mutator, 'driver> Fn(
&'value N,
- &'mutator mut MutateContext<'driver, State>,
+ &'mutator mut MutationContext<'driver, State>,
) -> O,
O: IntoMutateResult,
{
@@ -822,7 +827,7 @@ mod mutate_sealed {
where
F: for<'value, 'mutator, 'driver> Fn(
AnyView<'value>,
- &'mutator mut MutateContext<'driver, State>,
+ &'mutator mut MutationContext<'driver, State>,
) -> O,
O: IntoMutateResult,
{
@@ -838,16 +843,16 @@ pub struct ByMutateValue<T>(PhantomData<T>);
impl<F, State, T, O> MutateChainLink<State, ByMutateValue<T>> for F
where
F: for<'value, 'mutator, 'driver> Fn(
- MutateValue<'value, T>,
- &'mutator mut MutateContext<'driver, State>,
+ MutationValue<'value, T>,
+ &'mutator mut MutationContext<'driver, State>,
) -> O,
T: crate::type_traits::ContainerElement,
O: IntoMutateResult,
{
fn try_mutate(
&self,
- value: &mut Option<MutateValue<'_>>,
- mutator: &mut MutateContext<'_, State>,
+ value: &mut Option<MutationValue<'_>>,
+ mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
match value
.take()
@@ -868,14 +873,14 @@ pub struct ByMutateOwned<T>(PhantomData<T>);
impl<F, State, T, O> MutateChainLink<State, ByMutateOwned<T>> for F
where
- F: for<'mutator, 'driver> Fn(T, &'mutator mut MutateContext<'driver,
State>) -> O,
+ F: for<'mutator, 'driver> Fn(T, &'mutator mut MutationContext<'driver,
State>) -> O,
T: crate::type_traits::AnyCompatible,
O: IntoMutateResult,
{
fn try_mutate(
&self,
- value: &mut Option<MutateValue<'_>>,
- mutator: &mut MutateContext<'_, State>,
+ value: &mut Option<MutationValue<'_>>,
+ mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
value
.as_ref()
@@ -893,15 +898,15 @@ impl<F, State, N, O> MutateChainLink<State,
ByMutateNode<N>> for F
where
F: for<'value, 'mutator, 'driver> Fn(
&'value N,
- &'mutator mut MutateContext<'driver, State>,
+ &'mutator mut MutationContext<'driver, State>,
) -> O,
N: ObjectCore,
O: IntoMutateResult,
{
fn try_mutate(
&self,
- value: &mut Option<MutateValue<'_>>,
- mutator: &mut MutateContext<'_, State>,
+ value: &mut Option<MutationValue<'_>>,
+ mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
value
.as_ref()
@@ -919,14 +924,14 @@ impl<F, State, O> MutateChainLink<State,
ByMutateCatchAll> for F
where
F: for<'value, 'mutator, 'driver> Fn(
AnyView<'value>,
- &'mutator mut MutateContext<'driver, State>,
+ &'mutator mut MutationContext<'driver, State>,
) -> O,
O: IntoMutateResult,
{
fn try_mutate(
&self,
- value: &mut Option<MutateValue<'_>>,
- mutator: &mut MutateContext<'_, State>,
+ value: &mut Option<MutationValue<'_>>,
+ mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
Some(
self(
@@ -960,8 +965,8 @@ macro_rules! impl_mutate_chain_link {
{
fn try_mutate(
&self,
- value: &mut Option<MutateValue<'_>>,
- mutator: &mut MutateContext<'_, State>,
+ value: &mut Option<MutationValue<'_>>,
+ mutator: &mut MutationContext<'_, State>,
) -> Option<Result<Any>> {
$(
if let Some(result) = self.$idx.try_mutate(value, mutator)
{
@@ -977,7 +982,7 @@ macro_rules! impl_mutate_chain_link {
impl_callback_chain_tuple_arities!(impl_mutate_chain_link);
/// A reusable typed-dispatch or callback mutator with shared user state.
-pub struct MutateCallbacks<State, Link, Marker, Policy =
DefaultMutContextPolicy> {
+pub struct MutateCallbacks<State, Link, Marker, Policy =
DefaultMutationContextPolicy> {
policy: Option<Rc<Policy>>,
state: State,
callbacks: Rc<Link>,
@@ -1001,7 +1006,7 @@ where
impl<State, Link, Marker, Policy> MutateCallbacks<State, Link, Marker, Policy>
{
/// Customize default descent while sharing the callback state.
- pub fn with_policy<P: MutContextPolicy<State>>(
+ pub fn with_policy<P: MutationContextPolicy<State>>(
self,
policy: P,
) -> MutateCallbacks<State, Link, Marker, P> {
@@ -1102,7 +1107,7 @@ pub trait NativeMap: Sized {
impl<D: MapDispatch> NativeMap for D {
fn map_root(&mut self, root: Any, order: WalkOrder) -> Result<Any> {
- run_native_mapper::<_, DefaultMutContextPolicy>(root, self, None,
order)
+ run_native_mapper::<_, DefaultMutationContextPolicy>(root, self, None,
order)
}
}
@@ -1467,51 +1472,6 @@ where
}
}
-/// Engine-issued permission to attempt in-place mutation of one value.
-///
-/// The engine issues it only when the current ownership path permits reuse.
-/// A copied inspection view cannot survive consumption of this capability:
-/// ```compile_fail,E0505
-/// use tvm_ffi::{DefRegionKind, InplaceValue, StructuralMutator};
-/// fn invalid<M: StructuralMutator>(value: InplaceValue<'_>, mutator: &mut M)
{
-/// let view = value.as_value();
-/// let copy = view;
-/// mutator.default_maybe_inplace_mutate(value,
DefRegionKind::None).unwrap();
-/// println!("{}", copy.type_index());
-/// }
-/// ```
-pub struct InplaceValue<'a> {
- value: TVMFFIAny,
- _scope: PhantomData<&'a mut TVMFFIAny>,
-}
-
-impl<'a> InplaceValue<'a> {
- #[inline]
- fn from_raw(raw: &'a mut TVMFFIAny) -> Self {
- Self {
- value: *raw,
- _scope: PhantomData,
- }
- }
-
- /// Borrow the value without its in-place capability.
- #[inline]
- pub fn as_value(&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) }
- }
-
- /// Retain an owning copy of the value.
- ///
- /// Retaining an object creates an alias. The default in-place helper
- /// rechecks uniqueness and automatically falls back to copying.
- #[inline]
- pub fn to_owned(&self) -> Any {
- Any::from(self.as_value())
- }
-}
-
/// Identity substitutions for a custom [`StructuralMutator`] remapping policy.
///
/// The map owns its keys and values so object addresses remain stable.
@@ -1561,21 +1521,23 @@ pub trait StructuralMutator: Sized {
def_region_kind: DefRegionKind,
) -> Result<Any>;
- /// Dispatch one value for which the engine permits an in-place attempt.
+ /// Dispatch one value with its stored in-place permission.
///
+ /// The engine uses this hook when reuse is permitted, but callers may also
+ /// pass a borrowed handle with `Disallow`. Overrides must preserve that
mode.
/// The default delegates to [`Self::dispatch_mutate`] and therefore
remains
/// non-in-place. Override this method to opt into the default container
/// reuse path.
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
self.dispatch_mutate(value.as_value(), def_region_kind)
}
#[doc(hidden)]
- fn on_default_mutate(&mut self, value: MutateValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
default_mutate_driver(self, value.value, kind,
value.permit(value.inplace_mode()))
}
@@ -1642,33 +1604,34 @@ pub trait StructuralMutator: Sized {
.and_then(|result| resolve_result(result, *view.as_raw_ffi_any()))
}
- /// Apply the default mutation under an engine-issued in-place capability.
+ /// Apply default mutation with the handle's existing in-place permission.
///
/// Uniqueness is checked again here because user code may have retained
/// an owning alias after the capability was issued.
fn default_maybe_inplace_mutate(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
- self.default_maybe_inplace_mutate_with_mode(value, def_region_kind,
InplaceMode::Allow)
+ let mode = value.inplace_mode();
+ self.default_maybe_inplace_mutate_with_mode(value, def_region_kind,
mode)
}
/// Apply default mutation with a capability and an explicit permission.
///
- /// `Disallow` overrides the capability and uses the copy path. `Allow`
- /// rechecks uniqueness because the handler may have retained an owning
+ /// The requested mode can restrict, but cannot upgrade, the capability.
+ /// `Allow` rechecks uniqueness because the handler may have retained an
owning
/// alias. Consuming the capability prevents a borrow from it surviving
this
/// call. Unlike the C++ default-descent API, safe Rust cannot simply trust
/// the earlier uniqueness check after arbitrary user code has run.
fn default_maybe_inplace_mutate_with_mode(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
def_region_kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
let raw = value.value;
- let permit = mode.permit_if_unique(raw);
+ let permit = value.permit(mode);
user_default_mutate(self, raw, def_region_kind, permit)
.and_then(|result| resolve_result(result, raw))
}
@@ -1701,13 +1664,14 @@ pub trait StructuralMutator: Sized {
.and_then(UnchangedOr::from_carrier)
}
- /// Default mutation under an engine-issued capability, preserving
unchanged.
+ /// Default mutation with the handle's existing permission, preserving
unchanged.
fn default_maybe_inplace_mutate_result(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
) -> Result<UnchangedOr<Any>> {
- self.default_maybe_inplace_mutate_with_mode_result(value, kind,
InplaceMode::Allow)
+ let mode = value.inplace_mode();
+ self.default_maybe_inplace_mutate_with_mode_result(value, kind, mode)
}
/// Default mutation with a capability and permission, preserving
unchanged.
@@ -1715,12 +1679,12 @@ 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: InplaceValue<'_>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<UnchangedOr<Any>> {
let raw = value.value;
- let permit = mode.permit_if_unique(raw);
+ let permit = value.permit(mode);
user_default_mutate(self, raw, kind,
permit).and_then(UnchangedOr::from_carrier)
}
@@ -1736,7 +1700,7 @@ pub trait StructuralMutator: Sized {
}
impl<D: MutateDispatch> StructuralMutator for D {
- fn on_default_mutate(&mut self, value: MutateValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
MutateDispatch::on_default_mutate(self, value, kind)
}
@@ -1753,7 +1717,7 @@ impl<D: MutateDispatch> StructuralMutator for D {
};
match MutateDispatch::dispatch_mutate_value(
self,
- MutateValue::borrowed(value),
+ MutationValue::borrowed(value),
&mut mutator,
) {
Some(result) => result,
@@ -1764,29 +1728,21 @@ impl<D: MutateDispatch> StructuralMutator for D {
#[inline(always)]
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
+ let raw = value.value;
+ let mode = value.inplace_mode();
let mut mutator = Mutator {
def_region_kind,
- inplace_mode: InplaceMode::Allow,
+ inplace_mode: mode,
_not_send_sync: PhantomData,
};
- match MutateDispatch::dispatch_mutate_value(
- self,
- MutateValue::new(value.as_value(), InplaceMode::Allow),
- &mut mutator,
- ) {
+ match MutateDispatch::dispatch_mutate_value(self, value, &mut mutator)
{
Some(result) => result,
- None => {
- let raw = value.value;
- let permit = if object_is_unique(raw) {
- Permit::MaybeInPlace
- } else {
- Permit::Copy
- };
- user_default_mutate(self, raw, def_region_kind, permit)
- }
+ // The engine keeps the input live through dispatch. Default
descent
+ // rechecks ownership because a callback may have retained an
alias.
+ None => user_default_mutate(self, raw, def_region_kind,
mode.permit()),
}
}
}
@@ -1794,8 +1750,8 @@ impl<D: MutateDispatch> StructuralMutator for D {
#[doc(hidden)]
pub fn default_mutate_with_policy<D: MutateDispatch + MutateCallbackState<D>>(
dispatch: &mut D,
- policy: &impl MutContextPolicy<D>,
- value: MutateValue<'_>,
+ policy: &impl MutationContextPolicy<D>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
) -> Result<Any> {
policy::mutate_with_policy(
@@ -1812,33 +1768,30 @@ 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: AnyView<'_>,
+ value: &mut Option<MutationValue<'_>>,
def_region_kind: DefRegionKind,
- inplace_mode: InplaceMode,
) -> Option<Result<Any>>
where
Link: MutateChainLink<State, Marker>,
Driver: MutateContextDriver<State>,
{
- let mut mutator = MutateContext {
+ let mut mutator = MutationContext {
driver,
def_region_kind,
- inplace_mode,
+ inplace_mode: value
+ .as_ref()
+ .expect("unconsumed callback value")
+ .inplace_mode(),
_not_send_sync: PhantomData,
};
// SAFETY: The owning `Rc` or the direct callback's stack slot remains live
// and is never modified through the driver during recursive reentry.
- unsafe {
- (&*callback_ptr).try_mutate(
- &mut Some(MutateValue::new(value, inplace_mode)),
- &mut mutator,
- )
- }
+ unsafe { (&*callback_ptr).try_mutate(value, &mut mutator) }
}
impl<State, Link, Marker, Policy> StructuralMutator for MutateCallbacks<State,
Link, Marker, Policy>
where
- Policy: MutContextPolicy<State>,
+ Policy: MutationContextPolicy<State>,
Link: MutateChainLink<State, Marker>,
{
#[inline(always)]
@@ -1847,41 +1800,34 @@ where
value: AnyView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
- let callback_ptr = Rc::as_ptr(&self.callbacks);
- match try_mutate_callbacks::<State, Link, Marker, _>(
- self,
- callback_ptr,
- value,
- def_region_kind,
- InplaceMode::Disallow,
- ) {
- Some(result) => result,
- None => user_default_mutate(self, raw_of(value), def_region_kind,
Permit::Copy),
- }
+ self.dispatch_maybe_inplace_mutate(MutationValue::borrowed(value),
def_region_kind)
}
#[inline(always)]
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
+ let mut value = Some(value);
let callback_ptr = Rc::as_ptr(&self.callbacks);
match try_mutate_callbacks::<State, Link, Marker, _>(
self,
callback_ptr,
- value.as_value(),
+ &mut value,
def_region_kind,
- InplaceMode::Allow,
) {
Some(result) => result,
None => self
- .default_maybe_inplace_mutate_result(value, def_region_kind)
+ .default_maybe_inplace_mutate_result(
+ value.expect("unmatched callback value"),
+ def_region_kind,
+ )
.map(Any::from),
}
}
- fn on_default_mutate(&mut self, value: MutateValue<'_>, kind:
DefRegionKind) -> Result<Any> {
+ fn on_default_mutate(&mut self, value: MutationValue<'_>, kind:
DefRegionKind) -> Result<Any> {
match self.policy.clone() {
Some(policy) => policy::mutate_with_policy(
&mut policy::MutationDescent { driver: self },
@@ -1906,36 +1852,29 @@ where
value: AnyView<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
- let callback_ptr = std::ptr::from_ref(self.callbacks);
- match try_mutate_callbacks::<(), Link, Marker, _>(
- self,
- callback_ptr,
- value,
- def_region_kind,
- InplaceMode::Disallow,
- ) {
- Some(result) => result,
- None => user_default_mutate(self, raw_of(value), def_region_kind,
Permit::Copy),
- }
+ self.dispatch_maybe_inplace_mutate(MutationValue::borrowed(value),
def_region_kind)
}
#[inline(always)]
fn dispatch_maybe_inplace_mutate(
&mut self,
- value: InplaceValue<'_>,
+ value: MutationValue<'_>,
def_region_kind: DefRegionKind,
) -> Result<Any> {
+ let mut value = Some(value);
let callback_ptr = std::ptr::from_ref(self.callbacks);
match try_mutate_callbacks::<(), Link, Marker, _>(
self,
callback_ptr,
- value.as_value(),
+ &mut value,
def_region_kind,
- InplaceMode::Allow,
) {
Some(result) => result,
None => self
- .default_maybe_inplace_mutate_result(value, def_region_kind)
+ .default_maybe_inplace_mutate_result(
+ value.expect("unmatched callback value"),
+ def_region_kind,
+ )
.map(Any::from),
}
}
@@ -1972,7 +1911,7 @@ where
fn default_mutate_value(
&mut self,
- value: MutateValue<'_>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
@@ -1998,6 +1937,7 @@ enum Permit {
}
impl Permit {
+ #[inline]
fn inplace_mode(self, raw: TVMFFIAny) -> InplaceMode {
if self == Self::MaybeInPlace && object_is_unique(raw) {
InplaceMode::Allow
@@ -2020,7 +1960,7 @@ struct NativeMapper<'a, D, Policy, const PRE_ORDER: bool>
{
remap: StructuralVarRemap,
}
-fn run_native_mapper<D: MapDispatch, Policy: MutContextPolicy<D>>(
+fn run_native_mapper<D: MapDispatch, Policy: MutationContextPolicy<D>>(
root: Any,
dispatch: &mut D,
policy: Option<Rc<Policy>>,
@@ -2032,7 +1972,7 @@ fn run_native_mapper<D: MapDispatch, Policy:
MutContextPolicy<D>>(
}
}
-impl<D: MapDispatch, Policy: MutContextPolicy<D>, const PRE_ORDER: bool>
+impl<D: MapDispatch, Policy: MutationContextPolicy<D>, const PRE_ORDER: bool>
NativeMapper<'_, D, Policy, PRE_ORDER>
{
fn run(root: Any, dispatch: &mut D, policy: Option<Rc<Policy>>) ->
Result<Any> {
@@ -2718,7 +2658,7 @@ fn def_region_from_raw(kind: i32) ->
Result<DefRegionKind> {
}
}
-impl<D: MapDispatch, Policy: MutContextPolicy<D>, const PRE_ORDER: bool>
MutationDriver
+impl<D: MapDispatch, Policy: MutationContextPolicy<D>, const PRE_ORDER: bool>
MutationDriver
for NativeMapper<'_, D, Policy, PRE_ORDER>
{
fn dispatch_raw(
@@ -2757,7 +2697,7 @@ impl<D: MapDispatch, Policy: MutContextPolicy<D>, const
PRE_ORDER: bool> Mutatio
policy::mutate_with_policy(
&mut policy::MutationDescent { driver: self },
policy.as_ref(),
- MutateValue::new(view, permit.inplace_mode(raw)),
+ MutationValue::new(view, permit.inplace_mode(raw)),
kind,
)
}
@@ -3104,8 +3044,10 @@ fn dispatch_user_current_raw<U: StructuralMutator>(
permit: Permit,
) -> Result<Any> {
let result = if permit == Permit::MaybeInPlace && object_is_unique(raw) {
- let mut scoped_raw = raw;
- mutator.dispatch_maybe_inplace_mutate(InplaceValue::from_raw(&mut
scoped_raw), kind)
+ // 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)
} else {
mutator.dispatch_mutate(unsafe { borrowed_view(&raw) }, kind)
};
@@ -3120,7 +3062,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(MutateValue::new(value,
permit.inplace_mode(raw)), kind)
+ mutator.on_default_mutate(MutationValue::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 81758f3a..5e042335 100644
--- a/rust/tvm-ffi/src/extra/structural_mutate/policy.rs
+++ b/rust/tvm-ffi/src/extra/structural_mutate/policy.rs
@@ -27,36 +27,36 @@ use super::*;
/// then hooks or reflected fields; children re-enter callback dispatch.
/// Policies share callback state and compose as `(outer, inner)`.
/// Restore user state before returning, including on errors; use
-/// [`MutateContext::with_def_region_kind`] for scoped definition regions.
-pub trait MutContextPolicy<State> {
+/// [`MutationContext::with_def_region_kind`] for scoped definition regions.
+pub trait MutationContextPolicy<State> {
/// Customize default descent, preserving the input permission and result
marker.
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, State>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>>;
}
/// Default descent through registered hooks or reflected structural fields.
-pub struct DefaultMutContextPolicy;
+pub struct DefaultMutationContextPolicy;
-impl<State> MutContextPolicy<State> for DefaultMutContextPolicy {
+impl<State> MutationContextPolicy<State> for DefaultMutationContextPolicy {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, State>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
ctx.default_maybe_inplace_mutate_result(value)
}
}
-impl<State, Outer: MutContextPolicy<State>, Inner: MutContextPolicy<State>>
MutContextPolicy<State>
- for (Outer, Inner)
+impl<State, Outer: MutationContextPolicy<State>, Inner:
MutationContextPolicy<State>>
+ MutationContextPolicy<State> for (Outer, Inner)
{
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, State>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
let kind = ctx.def_region_kind();
mutate_with_policy(
@@ -75,8 +75,8 @@ impl<State, Outer: MutContextPolicy<State>, Inner:
MutContextPolicy<State>> MutC
#[inline(always)]
pub(super) fn mutate_with_policy<State>(
driver: &mut dyn MutateContextDriver<State>,
- policy: &impl MutContextPolicy<State>,
- value: MutateValue<'_>,
+ policy: &impl MutationContextPolicy<State>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
) -> Result<Any> {
let raw = value.value;
@@ -84,7 +84,7 @@ pub(super) fn mutate_with_policy<State>(
kind,
#[inline(always)]
|kind| {
- let mut ctx = MutateContext {
+ let mut ctx = MutationContext {
driver,
def_region_kind: kind,
inplace_mode: value.inplace_mode(),
@@ -101,7 +101,7 @@ struct NextPolicy<'a, State, Policy> {
policy: &'a Policy,
}
-impl<State, Policy: MutContextPolicy<State>> MutateContextDriver<State>
+impl<State, Policy: MutationContextPolicy<State>> MutateContextDriver<State>
for NextPolicy<'_, State, Policy>
{
fn state(&self) -> &State {
@@ -118,11 +118,16 @@ impl<State, Policy: MutContextPolicy<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,
MutateValue::borrowed(view), kind)
+ mutate_with_policy(
+ self.driver,
+ self.policy,
+ MutationValue::borrowed(view),
+ kind,
+ )
}
fn default_mutate_value(
&mut self,
- mut value: MutateValue<'_>,
+ mut value: MutationValue<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
@@ -165,7 +170,7 @@ impl<State, Driver: MutationDriver +
MutateCallbackState<State>> MutateContextDr
}
fn default_mutate_value(
&mut self,
- value: MutateValue<'_>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
mode: InplaceMode,
) -> Result<Any> {
@@ -191,7 +196,7 @@ impl<D, Policy, const PRE_ORDER: bool>
MutateCallbackState<D>
}
}
-/// A [`MapDispatch`] with a [`MutContextPolicy`], sharing the dispatcher's
state.
+/// A [`MapDispatch`] with a [`MutationContextPolicy`], sharing the
dispatcher's state.
///
/// Pass this value or a mutable reference to [`structural_map`]. Each node's
/// map callback runs outside its policy scope; its children run inside.
@@ -202,7 +207,9 @@ pub struct MapWithContextPolicy<Mapper, Policy> {
policy: Rc<Policy>,
}
-impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
MapWithContextPolicy<Mapper, Policy> {
+impl<Mapper: MapDispatch, Policy: MutationContextPolicy<Mapper>>
+ MapWithContextPolicy<Mapper, Policy>
+{
/// Combine a dispatcher and a default-recursion policy.
pub fn new(mapper: Mapper, policy: Policy) -> Self {
Self {
@@ -227,7 +234,7 @@ impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
MapWithContextPolicy
}
}
-impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>> NativeMap
+impl<Mapper: MapDispatch, Policy: MutationContextPolicy<Mapper>> NativeMap
for MapWithContextPolicy<Mapper, Policy>
{
fn map_root(&mut self, root: Any, order: WalkOrder) -> Result<Any> {
@@ -235,7 +242,7 @@ impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
NativeMap
}
}
-impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>> NativeMap
+impl<Mapper: MapDispatch, Policy: MutationContextPolicy<Mapper>> NativeMap
for &mut MapWithContextPolicy<Mapper, Policy>
{
fn map_root(&mut self, root: Any, order: WalkOrder) -> Result<Any> {
@@ -246,7 +253,7 @@ impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
NativeMap
#[doc(hidden)]
pub enum ByPolicyMap {}
-impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
IntoMapper<ByPolicyMap>
+impl<Mapper: MapDispatch, Policy: MutationContextPolicy<Mapper>>
IntoMapper<ByPolicyMap>
for MapWithContextPolicy<Mapper, Policy>
{
type Mapper = Self;
@@ -255,7 +262,7 @@ impl<Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
IntoMapper<ByPolicyM
}
}
-impl<'a, Mapper: MapDispatch, Policy: MutContextPolicy<Mapper>>
IntoMapper<ByPolicyMap>
+impl<'a, Mapper: MapDispatch, Policy: MutationContextPolicy<Mapper>>
IntoMapper<ByPolicyMap>
for &'a mut MapWithContextPolicy<Mapper, Policy>
{
type Mapper = Self;
diff --git a/rust/tvm-ffi/src/lib.rs b/rust/tvm-ffi/src/lib.rs
index 059450d4..e7bcd75c 100644
--- a/rust/tvm-ffi/src/lib.rs
+++ b/rust/tvm-ffi/src/lib.rs
@@ -54,9 +54,9 @@ pub use crate::error::{
};
pub use crate::extra::module::Module;
pub use crate::extra::structural_mutate::{
- structural_map, structural_mutate, DefaultMutContextPolicy, InplaceMode,
InplaceValue,
- IntoMapper, IntoMutator, MapChainLink, MapDispatch, MapWithContextPolicy,
MutContextPolicy,
- MutateCallbacks, MutateChainLink, MutateContext, MutateDispatch,
MutateValue, Mutator,
+ structural_map, structural_mutate, DefaultMutationContextPolicy,
InplaceMode, IntoMapper,
+ IntoMutator, MapChainLink, MapDispatch, MapWithContextPolicy,
MutateCallbacks, MutateChainLink,
+ MutateDispatch, MutationContext, MutationContextPolicy, MutationValue,
Mutator,
StructuralMutator, StructuralVarRemap,
};
pub use crate::extra::structural_visit::{
diff --git a/rust/tvm-ffi/tests/test_structural_mutate.rs
b/rust/tvm-ffi/tests/test_structural_mutate.rs
index 2a784883..715f1b19 100644
--- a/rust/tvm-ffi/tests/test_structural_mutate.rs
+++ b/rust/tvm-ffi/tests/test_structural_mutate.rs
@@ -23,9 +23,9 @@ use tvm_ffi::function::FunctionObj;
use tvm_ffi::object::ObjectRef;
use tvm_ffi::{
dispatch, structural_map, structural_mutate, structural_visit,
structural_walk, Any, AnyView,
- Array, DefRegionKind, DefaultContextPolicy, DefaultMutContextPolicy,
Error, FieldGetter,
- Function, InplaceMode, InplaceValue, IntoMapper, Map, MapDispatch,
MapWithContextPolicy,
- MutContextPolicy, MutateCallbacks, MutateContext, MutateValue, Mutator,
Object, ObjectArc,
+ Array, DefRegionKind, DefaultContextPolicy, DefaultMutationContextPolicy,
Error, FieldGetter,
+ Function, InplaceMode, IntoMapper, Map, MapDispatch, MapWithContextPolicy,
MutateCallbacks,
+ MutationContext, MutationContextPolicy, MutationValue, 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: InplaceValue<'_>,
+ value: MutationValue<'_>,
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: InplaceValue<'_>,
+ value: MutationValue<'_>,
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: InplaceValue<'_>,
+ value: MutationValue<'_>,
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: InplaceValue<'_>,
+ value: MutationValue<'_>,
kind: DefRegionKind,
) -> Result<Any> {
if self.increment {
@@ -389,6 +389,98 @@ fn
default_mutation_mode_preserves_ownership_and_unchanged_results() {
}
}
+#[test]
+fn borrowed_capabilities_cannot_enable_low_level_default_reuse() {
+ struct BorrowedEntry(usize);
+ impl StructuralMutator for BorrowedEntry {
+ fn dispatch_mutate(&mut self, value: AnyView<'_>, kind: DefRegionKind)
-> Result<Any> {
+ if let Some(integer) = value.try_as::<i64>() {
+ return Ok(Any::from(integer + 1));
+ }
+ 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));
+ assert_eq!(value.inplace_mode(), InplaceMode::Disallow);
+ // A count of one is insufficient: this handle only borrows source.
+ assert_eq!(
+ ObjectArc::strong_count(<Array<i64> as
ObjectRefCore>::data(&source)),
+ 1
+ );
+ let result = match self.0 {
+ 0 => self.default_maybe_inplace_mutate(value, kind)?,
+ 1 => {
+ self.default_maybe_inplace_mutate_with_mode(value, kind,
InplaceMode::Allow)?
+ }
+ 2 => self
+ .default_maybe_inplace_mutate_result(value, kind)?
+ .into(),
+ _ => self
+ .default_maybe_inplace_mutate_with_mode_result(value,
kind, InplaceMode::Allow)?
+ .into(),
+ };
+ let result = Array::<i64>::try_from(result)?;
+ assert_ne!(array_pointer(&result), pointer);
+ assert_eq!(source.get(0).unwrap(), 1);
+ assert_eq!(result.get(0).unwrap(), 2);
+ assert_eq!(
+ ObjectArc::strong_count(<Array<i64> as
ObjectRefCore>::data(&source)),
+ 1
+ );
+ Ok(result.into())
+ }
+ }
+ for helper in 0..4 {
+ structural_mutate(true, &mut BorrowedEntry(helper)).unwrap();
+ }
+}
+
+#[test]
+fn borrowed_capabilities_keep_their_mode_in_dispatch_adapters() {
+ struct Inspect;
+ #[dispatch(mutate)]
+ impl Inspect {
+ fn mutate_array(
+ &mut self,
+ value: tvm_ffi::MutationValue<'_, Array<i64>>,
+ ctx: &mut Mutator,
+ ) -> Unchanged {
+ assert_eq!(value.inplace_mode(), InplaceMode::Disallow);
+ assert_eq!(ctx.inplace_mode(), value.inplace_mode());
+ Unchanged
+ }
+ }
+ let source = Array::new(vec![1_i64]);
+ let result = StructuralMutator::dispatch_maybe_inplace_mutate(
+ &mut Inspect,
+ MutationValue::borrowed(AnyView::from(&source)),
+ DefRegionKind::None,
+ )
+ .unwrap();
+ assert!(UnchangedOr::<Any>::try_from(result).unwrap().is_unchanged());
+
+ let mut callbacks = MutateCallbacks::new(
+ (),
+ |value: MutationValue<'_, Array<i64>>, ctx: &mut MutationContext<'_>| {
+ assert_eq!(value.inplace_mode(), InplaceMode::Disallow);
+ assert_eq!(ctx.inplace_mode(), value.inplace_mode());
+ Unchanged
+ },
+ );
+ let result = callbacks
+ .dispatch_maybe_inplace_mutate(
+ MutationValue::borrowed(AnyView::from(&source)),
+ DefRegionKind::None,
+ )
+ .unwrap();
+ assert!(UnchangedOr::<Any>::try_from(result).unwrap().is_unchanged());
+ assert_eq!(source.get(0).unwrap(), 1);
+ assert_eq!(
+ ObjectArc::strong_count(<Array<i64> as ObjectRefCore>::data(&source)),
+ 1
+ );
+}
+
#[test]
fn owned_entry_mode_is_forwarded_by_generated_and_closure_callbacks() {
struct Entry {
@@ -423,12 +515,12 @@ fn
owned_entry_mode_is_forwarded_by_generated_and_closure_callbacks() {
let result = structural_mutate(
true,
(
- |_: bool, ctx: &mut MutateContext<'_>| {
+ |_: bool, ctx: &mut MutationContext<'_>| {
let child = Array::new(vec![1_i64]);
pointer.set(array_pointer(&child) as usize);
ctx.maybe_inplace_mutate_with_mode(child,
DefRegionKind::Pattern, mode)
},
- |value: i64, ctx: &mut MutateContext<'_>| {
+ |value: i64, ctx: &mut MutationContext<'_>| {
assert_eq!(ctx.def_region_kind(), DefRegionKind::Pattern);
value + 1
},
@@ -453,7 +545,7 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
modes: Vec<InplaceMode>,
}
impl Forward {
- fn observe(&mut self, value: &MutateValue<'_, Array<Any>>) {
+ fn observe(&mut self, value: &MutationValue<'_, Array<Any>>) {
self.modes.push(value.inplace_mode());
let view = value.as_value();
let node = view
@@ -470,12 +562,12 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
}
#[dispatch(mutate)]
impl Forward {
- fn mutate_string(&mut self, _: MutateValue<'_, FfiString>) -> Any {
+ fn mutate_string(&mut self, _: MutationValue<'_, FfiString>) -> Any {
panic!("typed miss must preserve the capability for the next
handler")
}
fn mutate_array(
&mut self,
- value: MutateValue<'_, Array<Any>>,
+ value: MutationValue<'_, Array<Any>>,
ctx: &mut Mutator,
) -> Result<UnchangedOr<Any>> {
assert_eq!(ctx.inplace_mode(), value.inplace_mode());
@@ -509,17 +601,18 @@ fn
consuming_callbacks_forward_permissions_without_temporary_owners() {
let result = if generated {
structural_mutate(root, &mut state).unwrap()
} else {
- let miss = |_: MutateValue<'_, FfiString>,
- _: &mut MutateContext<'_, Forward>|
+ let miss = |_: MutationValue<'_, FfiString>,
+ _: &mut MutationContext<'_, Forward>|
-> Any { panic!("typed miss must continue") };
- let increment = |value: i64, _: &mut MutateContext<'_,
Forward>| value + 1;
- let descend = |value: MutateValue<'_, Array<Any>>,
- ctx: &mut MutateContext<'_, Forward>| {
- assert_eq!(value.inplace_mode(), ctx.inplace_mode());
- ctx.state_mut().observe(&value);
- let requested = ctx.state().requested;
- ctx.default_mutate_with_mode(value, requested)
- };
+ let increment = |value: i64, _: &mut MutationContext<'_,
Forward>| value + 1;
+ let descend =
+ |value: MutationValue<'_, Array<Any>>,
+ ctx: &mut MutationContext<'_, Forward>| {
+ assert_eq!(value.inplace_mode(), ctx.inplace_mode());
+ ctx.state_mut().observe(&value);
+ let requested = ctx.state().requested;
+ ctx.default_mutate_with_mode(value, requested)
+ };
let mut callbacks = MutateCallbacks::new(state, (miss,
(increment, descend)));
let result = structural_mutate(root, &mut callbacks).unwrap();
state = callbacks.into_state();
@@ -549,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<MutateValue<'a>>,
+ value: Option<MutationValue<'a>>,
preserve_unchanged: bool,
result: Any,
}
@@ -569,7 +662,7 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
}
}
fn transfer(
- value: MutateValue<'_>,
+ value: MutationValue<'_>,
generated: bool,
preserve: bool,
retain: bool,
@@ -590,7 +683,7 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
let mut callbacks = MutateCallbacks::new(
inner,
(
- |_: bool, ctx: &mut MutateContext<'_, Inner<'_>>| ->
Result<Any> {
+ |_: bool, ctx: &mut MutationContext<'_, Inner<'_>>| ->
Result<Any> {
let value = ctx.state_mut().value.take().unwrap();
let result = if ctx.state().preserve_unchanged {
ctx.default_maybe_inplace_mutate_result(value)?.into()
@@ -600,7 +693,7 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
ctx.state_mut().result = result;
Ok(Any::new())
},
- |value: i64, _: &mut MutateContext<'_, Inner<'_>>| value +
1,
+ |value: i64, _: &mut MutationContext<'_, Inner<'_>>| value
+ 1,
),
);
structural_mutate(true, &mut callbacks)?;
@@ -617,7 +710,7 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
}
#[dispatch(mutate)]
impl Outer {
- fn mutate_any(&mut self, value: MutateValue<'_>) -> Result<Any> {
+ fn mutate_any(&mut self, value: MutationValue<'_>) -> Result<Any> {
transfer(value, true, self.preserve, self.retain)
}
}
@@ -629,9 +722,12 @@ fn
consuming_default_descent_transfers_between_contexts_without_node_borrows() {
let result = if generated {
structural_mutate(root, &mut Outer { preserve, retain })
} else {
- structural_mutate(root, |value: MutateValue<'_>, _: &mut
MutateContext<'_>| {
- transfer(value, false, preserve, retain)
- })
+ structural_mutate(
+ root,
+ |value: MutationValue<'_>, _: &mut
MutationContext<'_>| {
+ transfer(value, false, preserve, retain)
+ },
+ )
}
.and_then(Array::<i64>::try_from)
.unwrap();
@@ -649,7 +745,7 @@ fn
consuming_default_descent_preserves_unchanged_and_propagates_errors() {
let pointer = array_pointer(&root);
let result = structural_mutate(
root,
- |value: MutateValue<'_>, ctx: &mut MutateContext<'_>| ->
Result<UnchangedOr<Any>> {
+ |value: MutationValue<'_>, ctx: &mut MutationContext<'_>| ->
Result<UnchangedOr<Any>> {
if value.as_value().try_as::<i64>().is_some() {
return if fail {
Err(Error::new(RUNTIME_ERROR, "child failed", ""))
@@ -759,9 +855,9 @@ fn
callback_errors_preserve_message_and_add_object_context() {
self.default_visit_children(value, kind)
}
}
- #[dispatch(mutate, policy = (DefaultMutContextPolicy,
DefaultMutContextPolicy))]
+ #[dispatch(mutate, policy = (DefaultMutationContextPolicy,
DefaultMutationContextPolicy))]
impl Delegate {
- fn mutate_any(&mut self, value: MutateValue<'_>, ctx: &mut Mutator) ->
Result<Any> {
+ fn mutate_any(&mut self, value: MutationValue<'_>, ctx: &mut Mutator)
-> Result<Any> {
if value.as_value().try_as::<i64>().is_some() {
return Err(self.0.clone());
}
@@ -827,7 +923,7 @@ fn
callback_errors_preserve_message_and_add_object_context() {
);
let mut mapper = MapWithContextPolicy::new(
(|_: i64| -> Result<i64> { Err(source.clone()) }).into_mapper(),
- (DefaultMutContextPolicy, DefaultMutContextPolicy),
+ (DefaultMutationContextPolicy, DefaultMutationContextPolicy),
);
errors.push(
structural_map(root.clone(), &mut mapper, order)
@@ -838,7 +934,7 @@ fn
callback_errors_preserve_message_and_add_object_context() {
errors.push(
structural_mutate(
root.clone(),
- |_value: i64, _: &mut MutateContext| -> Result<i64> {
Err(source.clone()) },
+ |_value: i64, _: &mut MutationContext| -> Result<i64> {
Err(source.clone()) },
)
.err()
.unwrap(),
@@ -861,13 +957,13 @@ 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: MutateValue<'_>, ctx: &mut
MutateContext| {
+ MutateCallbacks::new((), |value: MutationValue<'_>, ctx: &mut
MutationContext| {
if value.as_value().try_as::<i64>().is_some() {
return Err(source.clone());
}
ctx.default_maybe_inplace_mutate(value)
})
- .with_policy((DefaultMutContextPolicy, DefaultMutContextPolicy));
+ .with_policy((DefaultMutationContextPolicy,
DefaultMutationContextPolicy));
errors.push(structural_mutate(root.clone(), &mut mutator).err().unwrap());
let mut delegate = Delegate(source.clone());
errors.push(structural_visit(&root, &mut delegate).err().unwrap());
@@ -1298,11 +1394,11 @@ fn
generated_mutate_dispatch_can_default_recurse_from_a_typed_handler() {
#[test]
fn pre_order_mapping_preserves_inplace_permission() {
struct Observe<'a>(&'a Cell<Option<InplaceMode>>);
- impl<State> MutContextPolicy<State> for Observe<'_> {
+ impl<State> MutationContextPolicy<State> for Observe<'_> {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut tvm_ffi::MutateContext<'_, State>,
+ value: MutationValue<'_>,
+ ctx: &mut tvm_ffi::MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
if value.as_value().type_index() >=
TypeIndex::kTVMFFIStaticObjectBegin as i32 {
self.0.set(Some(value.inplace_mode()));
@@ -1434,7 +1530,7 @@ fn callbacks_return_values_convertible_into_any() {
let mutated = structural_mutate(
Array::new(vec![1i64, 2]),
- |integer: i64, _mutator: &mut MutateContext<'_>| integer * 2,
+ |integer: i64, _mutator: &mut MutationContext<'_>| integer * 2,
)
.and_then(Array::<i64>::try_from)
.unwrap();
@@ -1445,7 +1541,7 @@ fn callbacks_return_values_convertible_into_any() {
fn recursive_mutate_returns_unchanged_or_a_replacement() {
fn clamp_negative_integers(
value: AnyView<'_>,
- mutator: &mut MutateContext<'_>,
+ mutator: &mut MutationContext<'_>,
) -> Result<UnchangedOr<Any>> {
if let Some(integer) = value.try_as::<i64>() {
if integer >= 0 {
@@ -1533,7 +1629,10 @@ fn post_order_unchanged_preserves_descendant_rewrites() {
let mapped = if with_policy {
structural_map(
root,
- MapWithContextPolicy::new(callbacks.into_mapper(),
DefaultMutContextPolicy),
+ MapWithContextPolicy::new(
+ callbacks.into_mapper(),
+ DefaultMutationContextPolicy,
+ ),
WalkOrder::PostOrder,
)
} else {
@@ -1700,7 +1799,7 @@ fn map_keys_are_anchors_and_object_leaves_are_preserved()
{
fn callback_mutate_defaults_unmatched_values_and_preserves_root_permit() {
let root = Array::new(vec![1i64, 2]);
let root_pointer = array_pointer(&root);
- let mutated = structural_mutate(root, |value: i64, _mutator: &mut
MutateContext<'_>| {
+ let mutated = structural_mutate(root, |value: i64, _mutator: &mut
MutationContext<'_>| {
Any::from(value + 1)
})
.and_then(Array::<i64>::try_from)
@@ -1717,7 +1816,7 @@ struct CallbackMutateStats {
fn stateful_mutate_integer(
value: i64,
- mutator: &mut MutateContext<'_, CallbackMutateStats>,
+ mutator: &mut MutationContext<'_, CallbackMutateStats>,
) -> Any {
mutator.state_mut().integers.push(value);
Any::from(value + 1)
@@ -1725,7 +1824,7 @@ fn stateful_mutate_integer(
fn stateful_mutate_default(
value: tvm_ffi::AnyView<'_>,
- mutator: &mut MutateContext<'_, CallbackMutateStats>,
+ mutator: &mut MutationContext<'_, CallbackMutateStats>,
) -> Result<Any> {
mutator.state_mut().defaults += 1;
mutator.default_mutate(&value)
@@ -1764,7 +1863,7 @@ struct CallbackMutateDepth {
fn stateful_mutate_recursive(
value: AnyView<'_>,
- mutator: &mut MutateContext<'_, CallbackMutateDepth>,
+ mutator: &mut MutationContext<'_, CallbackMutateDepth>,
) -> Result<Any> {
{
let state = mutator.state_mut();
@@ -1806,8 +1905,8 @@ fn
callback_mutate_explicit_default_is_repeatable_copy_path() {
let mutated = structural_mutate(
root,
(
- |value: i64, _mutator: &mut MutateContext<'_>| Any::from(value +
1),
- |value: AnyView<'_>, mutator: &mut MutateContext<'_>| ->
Result<Any> {
+ |value: i64, _mutator: &mut MutationContext<'_>| Any::from(value +
1),
+ |value: AnyView<'_>, mutator: &mut MutationContext<'_>| ->
Result<Any> {
defaults.set(defaults.get() + 1);
let first = mutator.default_mutate(&value)?;
let second = mutator.default_mutate(&value)?;
@@ -1829,10 +1928,10 @@ fn
callback_mutate_match_is_final_and_same_fn_can_reenter() {
let mutated = structural_mutate(
Array::new(vec![1i64]),
(
- |_array: Array<i64>, _mutator: &mut MutateContext<'_>| {
+ |_array: Array<i64>, _mutator: &mut MutationContext<'_>| {
Any::from(Array::new(vec![10i64]))
},
- |value: i64, _mutator: &mut MutateContext<'_>| {
+ |value: i64, _mutator: &mut MutationContext<'_>| {
integer_calls.set(integer_calls.get() + 1);
Any::from(value + 1)
},
@@ -1846,7 +1945,7 @@ fn
callback_mutate_match_is_final_and_same_fn_can_reenter() {
let calls = Cell::new(0);
let mutated = structural_mutate(
Array::new(vec![1i64, 2]),
- |value: AnyView<'_>, mutator: &mut MutateContext<'_>| {
+ |value: AnyView<'_>, mutator: &mut MutationContext<'_>| {
calls.set(calls.get() + 1);
mutator.default_mutate(&value)
},
@@ -1871,10 +1970,10 @@ fn
callback_mutate_supports_node_links_nested_tuples_and_reflection() {
root,
(
(
- |_value: bool, _mutator: &mut MutateContext<'_>| Any::new(),
- |_node: &FunctionObj, _mutator: &mut MutateContext<'_>|
Any::from(7i64),
+ |_value: bool, _mutator: &mut MutationContext<'_>| Any::new(),
+ |_node: &FunctionObj, _mutator: &mut MutationContext<'_>|
Any::from(7i64),
),
- |value: i64, mutator: &mut MutateContext<'_>| {
+ |value: i64, mutator: &mut MutationContext<'_>| {
regions.borrow_mut().push(mutator.def_region_kind());
Any::from(value + 1)
},
@@ -1900,8 +1999,8 @@ fn
callback_mutate_distinguishes_borrowed_and_owned_children() {
let mutated = structural_mutate(
true,
(
- |_value: bool, mutator: &mut MutateContext<'_>|
mutator.mutate(&borrowed_child),
- |value: i64, _mutator: &mut MutateContext<'_>| Any::from(value +
1),
+ |_value: bool, mutator: &mut MutationContext<'_>|
mutator.mutate(&borrowed_child),
+ |value: i64, _mutator: &mut MutationContext<'_>| Any::from(value +
1),
),
)
.and_then(Array::<i64>::try_from)
@@ -1914,12 +2013,12 @@ fn
callback_mutate_distinguishes_borrowed_and_owned_children() {
let mutated = structural_mutate(
true,
(
- |_value: bool, mutator: &mut MutateContext<'_>| {
+ |_value: bool, mutator: &mut MutationContext<'_>| {
let child = Array::new(vec![1i64]);
owned_pointer.set(array_pointer(&child) as usize);
mutator.maybe_inplace_mutate(child)
},
- |value: i64, _mutator: &mut MutateContext<'_>| Any::from(value +
1),
+ |value: i64, _mutator: &mut MutationContext<'_>| Any::from(value +
1),
),
)
.and_then(Array::<i64>::try_from)
@@ -1932,13 +2031,14 @@ fn
callback_mutate_distinguishes_borrowed_and_owned_children() {
fn nested_callback_mutate_restores_the_outer_active_mutator() {
let mutated = structural_mutate(
1i64,
- |value: i64, mutator: &mut MutateContext<'_>| -> Result<Any> {
+ |value: i64, mutator: &mut MutationContext<'_>| -> Result<Any> {
if value != 1 {
return Ok(Any::from(value + 1));
}
- let inner = structural_mutate(2i64, |value: i64, _mutator: &mut
MutateContext<'_>| {
- Any::from(value + 10)
- })?;
+ let inner =
+ structural_mutate(2i64, |value: i64, _mutator: &mut
MutationContext<'_>| {
+ Any::from(value + 10)
+ })?;
assert_eq!(i64::try_from(inner).unwrap(), 12);
mutator.mutate(&3i64)
},
@@ -1953,7 +2053,7 @@ fn
callback_mutate_panics_resume_and_leave_the_next_run_usable() {
let panic = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(||
{
structural_mutate(
Array::new(vec![1i64]),
- |_value: i64, _mutator: &mut MutateContext<'_>| -> Any {
+ |_value: i64, _mutator: &mut MutationContext<'_>| -> Any {
panic!("callback mutator panic")
},
)
@@ -1968,7 +2068,7 @@ fn
callback_mutate_panics_resume_and_leave_the_next_run_usable() {
let mutated = structural_mutate(
Array::new(vec![1i64]),
- |value: i64, _mutator: &mut MutateContext<'_>| Any::from(value + 1),
+ |value: i64, _mutator: &mut MutationContext<'_>| Any::from(value + 1),
)
.and_then(Array::<i64>::try_from)
.unwrap();
@@ -1993,11 +2093,11 @@ impl PolicyState {
}
struct ArrayPolicy;
-impl MutContextPolicy<PolicyState> for ArrayPolicy {
+impl MutationContextPolicy<PolicyState> for ArrayPolicy {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, PolicyState>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, PolicyState>,
) -> Result<UnchangedOr<Any>> {
if value
.as_value()
@@ -2017,11 +2117,11 @@ impl MutContextPolicy<PolicyState> for ArrayPolicy {
}
}
struct RecordPolicy;
-impl MutContextPolicy<PolicyState> for RecordPolicy {
+impl MutationContextPolicy<PolicyState> for RecordPolicy {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, PolicyState>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, PolicyState>,
) -> Result<UnchangedOr<Any>> {
if value
.as_value()
@@ -2072,7 +2172,7 @@ fn
mutation_policies_share_state_and_preserve_callback_order() {
for order in [WalkOrder::PreOrder, WalkOrder::PostOrder] {
let mut mapper = MapWithContextPolicy::new(
PolicyState::default(),
- (ArrayPolicy, (RecordPolicy, DefaultMutContextPolicy)),
+ (ArrayPolicy, (RecordPolicy, DefaultMutationContextPolicy)),
);
let output = structural_map(root(), &mut mapper, order).unwrap();
assert_eq!(i64::try_from(array_item(&output, 1)).unwrap(), 3);
@@ -2093,12 +2193,12 @@ fn
mutation_policies_share_state_and_preserve_callback_order() {
let mut mutator = MutateCallbacks::new(
PolicyState::default(),
(
- |x: i64, ctx: &mut MutateContext<'_, PolicyState>| {
+ |x: i64, ctx: &mut MutationContext<'_, PolicyState>| {
let depth = ctx.state().depth;
ctx.state_mut().events.push(("integer", depth));
x + 1
},
- |value: MutateValue<'_>, ctx: &mut MutateContext<'_, PolicyState>|
{
+ |value: MutationValue<'_>, ctx: &mut MutationContext<'_,
PolicyState>| {
let depth = ctx.state().depth;
ctx.state_mut().events.push(("callback", depth));
ctx.default_maybe_inplace_mutate_result(value)
@@ -2130,11 +2230,11 @@ fn
mutation_policies_share_state_and_preserve_callback_order() {
#[test]
fn map_policy_entries_preserve_descent_and_callback_composition() {
struct Stop;
- impl<State> MutContextPolicy<State> for Stop {
+ impl<State> MutationContextPolicy<State> for Stop {
fn default_mutate(
&self,
- _: MutateValue<'_>,
- _: &mut MutateContext<'_, State>,
+ _: MutationValue<'_>,
+ _: &mut MutationContext<'_, State>,
) -> Result<UnchangedOr<Any>> {
Ok(UnchangedOr::unchanged())
}
@@ -2147,7 +2247,7 @@ fn
map_policy_entries_preserve_descent_and_callback_composition() {
let mut state = PolicyState::default();
let output = {
let mut mapper =
- MapWithContextPolicy::new(&mut state,
(DefaultMutContextPolicy, Stop));
+ MapWithContextPolicy::new(&mut state,
(DefaultMutationContextPolicy, Stop));
match entry {
0 => structural_map(root(), mapper, order),
_ => structural_map(root(), &mut mapper, order),
@@ -2191,11 +2291,11 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
mode: InplaceMode,
retain: bool,
}
- impl MutContextPolicy<Ownership> for Control {
+ impl MutationContextPolicy<Ownership> for Control {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, Ownership>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, Ownership>,
) -> Result<UnchangedOr<Any>> {
let array = value
.as_value()
@@ -2213,7 +2313,7 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
}
#[dispatch(mutate, policy = (
Control { mode: self.mode, retain: self.retain },
- DefaultMutContextPolicy,
+ DefaultMutationContextPolicy,
))]
impl Ownership {
fn mutate_integer(&mut self, value: i64) -> UnchangedOr<i64> {
@@ -2221,7 +2321,7 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
}
fn mutate_array(
&mut self,
- value: MutateValue<'_, Array<i64>>,
+ value: MutationValue<'_, Array<i64>>,
mutator: &mut Mutator,
) -> Result<UnchangedOr<Any>> {
mutator.default_maybe_inplace_mutate_result(self, value)
@@ -2244,7 +2344,7 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
},
retain: case == 2,
},
- DefaultMutContextPolicy,
+ DefaultMutationContextPolicy,
);
let state = Ownership {
increment,
@@ -2273,10 +2373,10 @@ fn
mutation_policy_continuations_preserve_ownership_and_markers() {
let mut mutator = MutateCallbacks::new(
state,
(
- |x: i64, ctx: &mut MutateContext<'_, Ownership>| {
+ |x: i64, ctx: &mut MutationContext<'_, Ownership>|
{
ctx.state_mut().map_integer(x)
},
- |value: MutateValue<'_>, ctx: &mut
MutateContext<'_, Ownership>| {
+ |value: MutationValue<'_>, ctx: &mut
MutationContext<'_, Ownership>| {
ctx.default_maybe_inplace_mutate_result(value)
},
),
@@ -2316,11 +2416,11 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
}
}
struct Redirect(DefRegionKind);
- impl MutContextPolicy<Regions> for Redirect {
+ impl MutationContextPolicy<Regions> for Redirect {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, Regions>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, Regions>,
) -> Result<UnchangedOr<Any>> {
if value.as_value().try_as::<bool>() == Some(false) {
// Bypass this container's callback, but enter the next policy
and redispatch its children.
@@ -2343,11 +2443,11 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
}
}
struct Observe;
- impl MutContextPolicy<Regions> for Observe {
+ impl MutationContextPolicy<Regions> for Observe {
fn default_mutate(
&self,
- value: MutateValue<'_>,
- ctx: &mut MutateContext<'_, Regions>,
+ value: MutationValue<'_>,
+ ctx: &mut MutationContext<'_, Regions>,
) -> Result<UnchangedOr<Any>> {
if value
.as_value()
@@ -2365,7 +2465,7 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
impl Regions {
fn mutate_any(
&mut self,
- value: MutateValue<'_>,
+ value: MutationValue<'_>,
mutator: &mut Mutator,
) -> Result<UnchangedOr<Any>> {
if let Some(x) = value.as_value().try_as::<i64>() {
@@ -2411,7 +2511,7 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
}
let mut mutator = MutateCallbacks::new(
Regions::default(),
- |value: MutateValue<'_>, ctx: &mut MutateContext<'_, Regions>| {
+ |value: MutationValue<'_>, ctx: &mut MutationContext<'_, Regions>|
{
if let Some(x) = value.as_value().try_as::<i64>() {
let kind = ctx.def_region_kind();
ctx.state_mut().0.push((x, kind));
@@ -2461,11 +2561,11 @@ fn
mutation_policy_regions_retargeting_and_error_restore() {
#[test]
fn mutation_policy_halts_restore_state_and_skip_later_policies() {
struct Halt(bool);
- impl MutContextPolicy<PolicyState> for Halt {
+ impl MutationContextPolicy<PolicyState> for Halt {
fn default_mutate(
&self,
- _: MutateValue<'_>,
- _: &mut MutateContext<'_, PolicyState>,
+ _: MutationValue<'_>,
+ _: &mut MutationContext<'_, PolicyState>,
) -> Result<UnchangedOr<Any>> {
if self.0 {
Err(Error::new(RUNTIME_ERROR, "stop descent", ""))
@@ -2494,7 +2594,7 @@ fn
mutation_policy_halts_restore_state_and_skip_later_policies() {
}
let mut mutator = MutateCallbacks::new(
PolicyState::default(),
- |x: i64, _: &mut MutateContext<'_, PolicyState>| x + 1,
+ |x: i64, _: &mut MutationContext<'_, PolicyState>| x + 1,
)
.with_policy((ArrayPolicy, (Halt(fail), RecordPolicy)));
assert_eq!(