Skip to main content

structural_map

Function structural_map 

Source
pub fn structural_map<R, M, H, D, O>(
    root: R,
    mapper: H,
    order: WalkOrder,
) -> Result<Any>
where R: Into<Any>, O: BorrowMut<D>, for<'v> H: IntoDispatcher<(AnyView<'v>, DefRegionKind), Option<Result<UnchangedOr<Any>>>, M, Target = D, Output = O>, for<'s, 'v> &'s mut D: Dispatcher<(AnyView<'v>, DefRegionKind), Option<Result<UnchangedOr<Any>>>>,
Expand description

Transform a structured value graph with ordered replacement callbacks.

The root is consumed. A uniquely owned built-in container may therefore be reused in place, while passing root.clone() keeps the original shared and selects copy-on-write behavior. Map and Dict keys are anchors and are not mapped. Their registered structural hooks own container traversal.

Callbacks run at every occurrence. Default reflected descent handles FreeVar and DAG-node remapping; registered hooks own their type’s remapping policy. Callback replacements are not automatically recorded as substitutions.

In-place changes completed before an error are not rolled back. Because this function consumes root, an error does not return the partly mapped root to the caller.

Callbacks must report failures through Result and must not panic: a panic reaching the non-unwinding native callback boundary aborts the process.

A callback must not modify an ffi.List or ffi.Dict that holds the value it receives or one of that value’s ancestors: the traversal borrows their cells while the callback runs. A callback that returns an Error object as its value fails the traversal with a TypeError.

§Arguments

  • root - Owned value to transform, convertible into an Any. Clone it first to preserve the original through copy-on-write behavior.
  • mapper - Mutable dispatcher, closure, or first-match callback tuple implementing IntoDispatcher. Callbacks return replacements; unmatched values retain their value while default traversal maps their children.
  • order - WalkOrder::PreOrder applies the callback before traversing the replacement’s children; WalkOrder::PostOrder maps children before applying the callback to their parent.

§Examples

Increment integer leaves while keeping a shared original unchanged:

use tvm_ffi::{structural_map, Array, WalkOrder};

let root = Array::from_vec(vec![1_i64, 2, 3]);
let mapped = structural_map(root.clone(), |value: i64| value + 1, WalkOrder::PostOrder)?;
let mapped = Array::<i64>::try_from(mapped)?;
assert_eq!(mapped.iter().copied().collect::<Vec<_>>(), vec![2, 3, 4]);
assert_eq!(root.iter().copied().collect::<Vec<_>>(), vec![1, 2, 3]);