Attribute Macro dispatch
#[dispatch]Expand description
Generate runtime type dispatch from the prefix_* methods of an impl.
#[dispatch(prefix, (First, Args...), Ret)] on an inherent impl makes its
prefix_* methods handlers and adds a dispatch(first, args...) -> Option<Ret> method. dispatch calls the first handler, in source order,
whose first parameter matches the runtime type of first, and returns
None when no handler matches. The macro also implements Dispatcher
for &Self or &mut Self, so the type can drive structural_walk and
the other traversals, whose engines call it and run their own default
recursion; no prefix has a reserved meaning. Handlers without an inline
attribute are marked #[inline(always)].
§Arguments
prefix- The handler name prefix;describeselectsdescribe_int,describe_strand so on.(First, Args...)- The complete input tuple.First, the value to match, isAnyView<'_>orMutationView<'_>, including aliases.Argsare passed through: each handler takes a leading prefix of them without cloning, and need not take all of them.Ret- The result type. A handler’s result is converted withInto<Ret>. When both the handler’s result andRetare writtenResult<..>, the success value is converted instead, so aResult<UnchangedOr<MyPair>>handler fits aResult<UnchangedOr<Any>>dispatcher.
§Handlers
A handler’s first parameter selects what it matches, as for
match_any!: an owned FFI value such as i64 or Array<Any>, converted
strictly; &Type (such as &Array<i64> or &tvm_ffi::String) or
&NodeObj, which borrow the value or the object node in place without
changing a reference count; MutationView<'_, T>,
which keeps the in-place mode; or AnyView<'_>, which
matches every value and must be the last handler.
Only the outer None means that no handler matched: a handler error, or a
None inside Ret, is final. Handlers share one receiver, &self or
&mut self, and the same method generics and bounds; shared generics must
occur in the receiver, the input tuple or Ret. Use the same lifetime name
in an input and Ret to return a borrow of that input; elided output
lifetimes borrow the receiver. Handler-level cfg attributes are not
supported; configure the whole impl instead. Generate one dispatcher per
type; when inference is ambiguous, give the expected result type.
§Examples
use tvm_ffi::{dispatch, AnyView};
struct Describer;
#[dispatch(describe, (AnyView<'_>,), String)]
impl Describer {
fn describe_int(&self, value: i64) -> String {
format!("integer {value}")
}
fn describe_str(&self, value: &tvm_ffi::String) -> String {
format!("string {}", value.as_str())
}
}
let text = tvm_ffi::String::from("hi");
assert_eq!(Describer.dispatch(AnyView::from(&1_i64)).as_deref(), Some("integer 1"));
assert_eq!(Describer.dispatch(AnyView::from(&text)).as_deref(), Some("string hi"));
assert_eq!(Describer.dispatch(AnyView::from(&1.5_f64)), None);