Skip to main content

tvm_ffi/extra/
dispatch.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Runtime type dispatch indexed by its tuple of arguments.
21
22/// A handler that the structural traversals call with a tuple of arguments.
23///
24/// See also [`#[dispatch]`](crate::dispatch).
25#[diagnostic::on_unimplemented(
26    message = "this receiver does not implement Dispatcher for the requested argument tuple",
27    note = "use #[dispatch(prefix, (Carrier, ...), Ret)] with compatible typed handlers"
28)]
29pub trait Dispatcher<Args, Ret> {
30    /// Dispatch on `args.0` with the complete argument tuple `args`.
31    ///
32    /// # Arguments
33    ///
34    /// * `args` - The argument tuple, whose first element is the value to dispatch on.
35    ///
36    /// # Returns
37    ///
38    /// `Some` of the matched handler's result, or `None` when no handler matches.
39    fn dispatch_tuple(self, args: Args) -> Ret;
40}
41
42use crate::AnyView;
43
44/// Compile-time source metadata for the supported dispatch carriers.
45#[doc(hidden)]
46#[diagnostic::on_unimplemented(
47    message = "the first dispatch argument must be AnyView or MutationView"
48)]
49pub trait DispatchInput {
50    type Source;
51}
52impl<'a> DispatchInput for AnyView<'a> {
53    type Source = crate::match_any_internal::ViewSource<'a>;
54}
55impl<'a, T> DispatchInput for crate::MutationView<'a, T> {
56    type Source = crate::match_any_internal::MutationSource<'a>;
57}
58
59use std::{borrow::BorrowMut, marker::PhantomData};
60
61/// Inferred selectors for dispatcher normalization.
62///
63/// Entry points infer one marker from the input. Callback markers select argument
64/// matching and a leading argument count; tuple markers contain each link's marker.
65/// Normalization stores the input once, before traversal, without cloning it.
66#[doc(hidden)]
67pub mod marker {
68    use std::marker::PhantomData;
69    /// Store an owned dispatcher with the exact target argument and result types.
70    pub enum FromOwned {}
71    /// Store a mutable borrow of an exact-signature dispatcher.
72    pub enum FromBorrowed {}
73    /// Match a callback's first argument using `Shape`, then pass its first `N`
74    /// arguments. `N` ranges from one through four, including the matched value.
75    pub struct FromCallback<const N: usize, Shape>(PhantomData<fn() -> Shape>);
76    /// Try tuple links in order. `Markers` is their marker tuple, including nested
77    /// tuples; `Args` selects how arguments are reborrowed between links.
78    pub struct FromTuple<Markers, Args = CopyArgs>(PhantomData<fn() -> (Markers, Args)>);
79    /// Replay copyable observer arguments; this does not copy dispatcher storage.
80    pub enum CopyArgs {}
81    /// Sequentially reborrow a mutable second argument for each tuple link.
82    pub enum MutArg {}
83    /// Match and convert the first `AnyView` to the FFI value type `T`.
84    pub struct Value<T>(PhantomData<fn() -> T>);
85    /// Match a borrowed object node `&T` without retaining it, unlike the
86    /// by-value conversion selected by [`Value<T>`].
87    pub struct BorrowedObject<T>(PhantomData<fn() -> T>);
88    /// Pass the first `AnyView` without a runtime type filter.
89    pub enum AnyView {}
90    /// Match a mutation view for `T`, keeping its in-place mode.
91    pub struct Mutation<T = crate::Any>(PhantomData<fn() -> T>);
92}
93
94/// Convert a dispatcher, a callback, or a tuple of them, into a [`Dispatcher`]
95/// for the argument tuple `Args` and result `Ret`; the traversals take any of
96/// these inputs.
97///
98/// * An owned `D` or a borrowed `&mut D` keeps `D` as the
99///   [`Target`](Self::Target), and must have exactly that signature.
100/// * A callback takes a leading prefix of one to four of the arguments, and
101///   its first parameter selects what it matches, as for a `#[dispatch]`
102///   handler: an FFI value, a borrowed object node or `AnyView`, or a typed
103///   `MutationView` for mutation. It is passed by value, `&` or `&mut`.
104/// * A tuple, possibly nested, tries its links in order. Only an outer `None`
105///   moves on to the next link; an error or an inner `None` stops.
106///
107/// `M` marks the input form and is inferred; when calling `into_dispatcher`
108/// directly, give `Args` and `Ret`. See also [`#[dispatch]`](crate::dispatch).
109///
110/// ```
111/// use tvm_ffi::{Any, AnyView, Dispatcher, IntoDispatcher, Result};
112/// let callbacks = (|value: i64| Any::from(value + 1), |_value: AnyView<'_>| Any::new());
113/// let mut dispatcher = IntoDispatcher::<(AnyView<'_>,), Option<Result<Any>>, _>::into_dispatcher(callbacks);
114/// let result: Option<Result<Any>> = dispatcher.dispatch_tuple((AnyView::from(&41_i64),));
115/// let result = result.unwrap()?;
116/// assert_eq!(i64::try_from(result)?, 42);
117/// # Ok::<(), tvm_ffi::Error>(())
118/// ```
119pub trait IntoDispatcher<Args, Ret, M> {
120    /// Actual dispatcher type, independent of its owned or borrowed storage.
121    type Target;
122    /// Storage normalized once at entry, retaining the target's identity.
123    type Output: BorrowMut<Self::Target>;
124    /// Convert the input, once, before the traversal starts.
125    fn into_dispatcher(self) -> Self::Output;
126}
127
128/// Normalized callback or tuple storage; direct dispatchers retain their own type.
129#[doc(hidden)]
130pub struct DispatchAdapter<F, M> {
131    input: F,
132    marker: PhantomData<fn() -> M>,
133}
134
135impl<D, Args, Ret> IntoDispatcher<Args, Ret, marker::FromOwned> for D
136where
137    for<'s> &'s mut D: Dispatcher<Args, Ret>,
138{
139    type Target = D;
140    type Output = D;
141    #[inline(always)]
142    fn into_dispatcher(self) -> Self::Output {
143        self
144    }
145}
146
147impl<'d, D, Args, Ret> IntoDispatcher<Args, Ret, marker::FromBorrowed> for &'d mut D
148where
149    for<'s> &'s mut D: Dispatcher<Args, Ret>,
150{
151    type Target = D;
152    type Output = &'d mut D;
153    #[inline(always)]
154    fn into_dispatcher(self) -> Self::Output {
155        self
156    }
157}
158
159impl<F, Args, Ret, const N: usize, Shape> IntoDispatcher<Args, Ret, marker::FromCallback<N, Shape>>
160    for F
161where
162    F: DispatchLink<Args, Ret, marker::FromCallback<N, Shape>>,
163{
164    type Target = DispatchAdapter<F, marker::FromCallback<N, Shape>>;
165    type Output = Self::Target;
166    #[inline(always)]
167    fn into_dispatcher(self) -> Self::Output {
168        DispatchAdapter {
169            input: self,
170            marker: PhantomData,
171        }
172    }
173}
174
175impl<F, Args, Ret, Markers, Reborrow>
176    IntoDispatcher<Args, Ret, marker::FromTuple<Markers, Reborrow>> for F
177where
178    F: DispatchLink<Args, Ret, marker::FromTuple<Markers, Reborrow>>,
179{
180    type Target = DispatchAdapter<F, marker::FromTuple<Markers, Reborrow>>;
181    type Output = Self::Target;
182    #[inline(always)]
183    fn into_dispatcher(self) -> Self::Output {
184        DispatchAdapter {
185            input: self,
186            marker: PhantomData,
187        }
188    }
189}
190
191/// Implementation boundary shared by callback and tuple adapters.
192#[doc(hidden)]
193pub trait DispatchLink<Args, Ret, M> {
194    fn dispatch_link(&mut self, args: Args) -> Ret;
195}
196
197impl<F, Args, Ret, M> Dispatcher<Args, Ret> for &mut DispatchAdapter<F, M>
198where
199    F: DispatchLink<Args, Ret, M>,
200{
201    #[inline(always)]
202    fn dispatch_tuple(self, args: Args) -> Ret {
203        self.input.dispatch_link(args)
204    }
205}
206
207impl<D, Args, Ret> DispatchLink<Args, Ret, marker::FromOwned> for D
208where
209    for<'s> &'s mut D: Dispatcher<Args, Ret>,
210{
211    #[inline(always)]
212    fn dispatch_link(&mut self, args: Args) -> Ret {
213        self.dispatch_tuple(args)
214    }
215}
216impl<D, Args, Ret> DispatchLink<Args, Ret, marker::FromBorrowed> for &mut D
217where
218    for<'s> &'s mut D: Dispatcher<Args, Ret>,
219{
220    #[inline(always)]
221    fn dispatch_link(&mut self, args: Args) -> Ret {
222        (&mut **self).dispatch_tuple(args)
223    }
224}
225
226/// Operation-specific callback result conversion; matching and chaining are shared.
227#[doc(hidden)]
228pub trait CallbackResult<R> {
229    fn callback_result(self) -> R;
230}
231
232macro_rules! callback_prefix {
233    ($n:literal; ($($A:ident:$a:ident),*); ($($B:ident:$b:ident),*)) => {
234        impl<'v, F, T, O, R, $($A,)*>
235            DispatchLink<(AnyView<'v>, $($A,)*), Option<R>, marker::FromCallback<$n, marker::Value<T>>> for F
236        where F: FnMut(T, $($B,)*) -> O, T: crate::type_traits::AnyCompatible,
237              O: CallbackResult<R>,
238        {
239            #[inline(always)]
240            fn dispatch_link(&mut self, (value, $($a,)*): (AnyView<'v>, $($A,)*)) -> Option<R> {
241                $(let _ = &$a;)*
242                // Strict: a handler matches only values that fit its type as is (a
243                // `bool` handler never catches an int), so this does not convert.
244                let cell = value.as_raw_ffi_any();
245                // SAFETY: the view's cell is valid for the call, and the copy runs
246                // only after the strict check.
247                let typed = unsafe {
248                    (T::check_any_strict(cell) && T::match_constraints(cell))
249                        .then(|| T::copy_from_any_view_after_check(cell))
250                };
251                typed.map(|typed| self(typed, $($b,)*).callback_result())
252            }
253        }
254        impl<'v, F, T, O, R, $($A,)*>
255            DispatchLink<(AnyView<'v>, $($A,)*), Option<R>, marker::FromCallback<$n, marker::BorrowedObject<T>>> for F
256        where F: for<'node> FnMut(&'node T, $($B,)*) -> O,
257              T: crate::type_traits::DowncastRefFromAny + 'static,
258              O: CallbackResult<R>,
259        {
260            #[inline(always)]
261            fn dispatch_link(&mut self, (value, $($a,)*): (AnyView<'v>, $($A,)*)) -> Option<R> {
262                $(let _ = &$a;)*
263                value.downcast_ref::<T>().map(|node| self(node, $($b,)*).callback_result())
264            }
265        }
266        impl<'v, F, O, R, $($A,)*>
267            DispatchLink<(AnyView<'v>, $($A,)*), Option<R>, marker::FromCallback<$n, marker::AnyView>> for F
268        where F: FnMut(AnyView<'v>, $($B,)*) -> O, O: CallbackResult<R>,
269        {
270            #[inline(always)]
271            fn dispatch_link(&mut self, (value, $($a,)*): (AnyView<'v>, $($A,)*)) -> Option<R> {
272                $(let _ = &$a;)*
273                Some(self(value, $($b,)*).callback_result())
274            }
275        }
276    };
277}
278callback_prefix!(1; (); ());
279callback_prefix!(1; (A1:a1); ());
280callback_prefix!(2; (A1:a1); (A1:a1));
281callback_prefix!(1; (A1:a1, A2:a2); ());
282callback_prefix!(2; (A1:a1, A2:a2); (A1:a1));
283callback_prefix!(3; (A1:a1, A2:a2); (A1:a1, A2:a2));
284callback_prefix!(1; (A1:a1, A2:a2, A3:a3); ());
285callback_prefix!(2; (A1:a1, A2:a2, A3:a3); (A1:a1));
286callback_prefix!(3; (A1:a1, A2:a2, A3:a3); (A1:a1, A2:a2));
287callback_prefix!(4; (A1:a1, A2:a2, A3:a3); (A1:a1, A2:a2, A3:a3));
288
289macro_rules! mutation_callback_prefix {
290    ($n:literal; ($($A:ident:$a:ident),*); ($($B:ident:$b:ident),*)) => {
291        impl<'v, F, T, O, R, $($A,)*>
292            DispatchLink<(crate::MutationView<'v>, $($A,)*), Option<R>, marker::FromCallback<$n, marker::Mutation<T>>> for F
293        where F: FnMut(crate::MutationView<'v, T>, $($B,)*) -> O,
294              T: crate::type_traits::ContainerElement, O: CallbackResult<R>,
295        {
296            #[inline(always)]
297            fn dispatch_link(&mut self, (value, $($a,)*): (crate::MutationView<'v>, $($A,)*)) -> Option<R> {
298                $(let _ = &$a;)*
299                value.downcast::<T>().ok().map(|typed| self(typed, $($b,)*).callback_result())
300            }
301        }
302    };
303}
304mutation_callback_prefix!(1; (); ());
305mutation_callback_prefix!(1; (A1:a1); ());
306mutation_callback_prefix!(2; (A1:a1); (A1:a1));
307mutation_callback_prefix!(1; (A1:a1, A2:a2); ());
308mutation_callback_prefix!(2; (A1:a1, A2:a2); (A1:a1));
309mutation_callback_prefix!(3; (A1:a1, A2:a2); (A1:a1, A2:a2));
310mutation_callback_prefix!(1; (A1:a1, A2:a2, A3:a3); ());
311mutation_callback_prefix!(2; (A1:a1, A2:a2, A3:a3); (A1:a1));
312mutation_callback_prefix!(3; (A1:a1, A2:a2, A3:a3); (A1:a1, A2:a2));
313mutation_callback_prefix!(4; (A1:a1, A2:a2, A3:a3); (A1:a1, A2:a2, A3:a3));
314
315// Concrete tuple storage bounds keep trait inference from recursively inventing
316// unknown adapter receiver layers. Tuple arity is independent of callback arity.
317macro_rules! dispatch_tuple_links {
318    ($(($F:ident, $M:ident, $idx:tt)),+) => {
319        impl<Args: Copy, R, $($F, $M,)+>
320            DispatchLink<Args, Option<R>, marker::FromTuple<($($M,)+)>> for ($($F,)+)
321        where $($F: DispatchLink<Args, Option<R>, $M>,)+
322        {
323            #[inline(always)]
324            fn dispatch_link(&mut self, args: Args) -> Option<R> {
325                $(if let Some(result) = self.$idx.dispatch_link(args) { return Some(result); })+
326                None
327            }
328        }
329        impl<'v, 'c, C, R, $($F, $M,)+>
330            DispatchLink<(AnyView<'v>, &'c mut C), Option<R>, marker::FromTuple<($($M,)+), marker::MutArg>> for ($($F,)+)
331        where $(for<'borrow> $F: DispatchLink<(AnyView<'v>, &'borrow mut C), Option<R>, $M>,)+
332        {
333            #[inline(always)]
334            fn dispatch_link(&mut self, (value, context): (AnyView<'v>, &'c mut C)) -> Option<R> {
335                $(if let Some(result) = self.$idx.dispatch_link((value, &mut *context)) { return Some(result); })+
336                None
337            }
338        }
339        impl<'v, 'c, C, R, $($F, $M,)+>
340            DispatchLink<(crate::MutationView<'v>, &'c mut C), Option<R>, marker::FromTuple<($($M,)+), marker::MutArg>> for ($($F,)+)
341        where $(for<'value, 'borrow> $F: DispatchLink<(crate::MutationView<'value>, &'borrow mut C), Option<R>, $M>,)+
342        {
343            #[inline(always)]
344            fn dispatch_link(&mut self, (mut value, context): (crate::MutationView<'v>, &'c mut C)) -> Option<R> {
345                $(if let Some(result) = self.$idx.dispatch_link((value.reborrow(), &mut *context)) { return Some(result); })+
346                None
347            }
348        }
349    };
350}
351// Generate the tuple arities supported by the standard library (1 through 12).
352macro_rules! impl_callback_chain_tuple_arities {
353    ($impl_chain:ident) => {
354        impl_callback_chain_tuple_arities!(
355            @prefixes $impl_chain;
356            [];
357            (F0, M0, 0),
358            (F1, M1, 1),
359            (F2, M2, 2),
360            (F3, M3, 3),
361            (F4, M4, 4),
362            (F5, M5, 5),
363            (F6, M6, 6),
364            (F7, M7, 7),
365            (F8, M8, 8),
366            (F9, M9, 9),
367            (F10, M10, 10),
368            (F11, M11, 11)
369        );
370    };
371    (@prefixes $impl_chain:ident; [$($prefix:tt)*];) => {};
372    (
373        @prefixes $impl_chain:ident;
374        [$($prefix:tt)*];
375        $next:tt $(, $rest:tt)*
376    ) => {
377        $impl_chain!($($prefix)* $next);
378        impl_callback_chain_tuple_arities!(
379            @prefixes $impl_chain;
380            [$($prefix)* $next,];
381            $($rest),*
382        );
383    };
384}
385
386impl_callback_chain_tuple_arities!(dispatch_tuple_links);