File size: 10,579 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use core::panic;
use std::{fmt::Debug, hash::Hash, pin::Pin, sync::OnceLock};

use anyhow::Result;
use futures::Future;
use serde::{Deserialize, Serialize};
use tracing::Span;

use crate::{
    RawVc, TaskExecutionReason, TaskInput, TaskPersistence,
    magic_any::{MagicAny, MagicAnyDeserializeSeed, MagicAnySerializeSeed},
    registry::register_function,
    task::{
        IntoTaskFn, TaskFn,
        function::{IntoTaskFnWithThis, NativeTaskFuture},
    },
};

type ResolveFuture<'a> = Pin<Box<dyn Future<Output = Result<Box<dyn MagicAny>>> + Send + 'a>>;
type ResolveFunctor = for<'a> fn(&'a dyn MagicAny) -> ResolveFuture<'a>;

type IsResolvedFunctor = fn(&dyn MagicAny) -> bool;

type FilterOwnedArgsFunctor = for<'a> fn(Box<dyn MagicAny>) -> Box<dyn MagicAny>;
type FilterAndResolveFunctor = ResolveFunctor;

pub struct ArgMeta {
    serializer: MagicAnySerializeSeed,
    deserializer: MagicAnyDeserializeSeed,
    is_resolved: IsResolvedFunctor,
    resolve: ResolveFunctor,
    /// Used for trait methods, filters out unused arguments.
    filter_owned: FilterOwnedArgsFunctor,
    /// Accepts a reference (instead of ownership) of arguments, and does the filtering and
    /// resolution in a single operation.
    //
    // When filtering a `&dyn MagicAny` while running a resolution task, we can't return a filtered
    // `&dyn MagicAny`, we'd be forced to return a `Box<dyn MagicAny>`. However, the next thing we
    // do is resolution, which also accepts a `&dyn MagicAny` and returns a `Box<dyn MagicAny>`.
    // This functor combines the two operations to avoid extra cloning.
    filter_and_resolve: FilterAndResolveFunctor,
}

impl ArgMeta {
    pub fn new<T>() -> Self
    where
        T: TaskInput + Serialize + for<'de> Deserialize<'de> + 'static,
    {
        fn noop_filter_args(args: Box<dyn MagicAny>) -> Box<dyn MagicAny> {
            args
        }
        Self::with_filter_trait_call::<T>(noop_filter_args, resolve_functor_impl::<T>)
    }

    pub fn with_filter_trait_call<T>(
        filter_owned: FilterOwnedArgsFunctor,
        filter_and_resolve: FilterAndResolveFunctor,
    ) -> Self
    where
        T: TaskInput + Serialize + for<'de> Deserialize<'de> + 'static,
    {
        Self {
            serializer: MagicAnySerializeSeed::new::<T>(),
            deserializer: MagicAnyDeserializeSeed::new::<T>(),
            is_resolved: |value| downcast_args_ref::<T>(value).is_resolved(),
            resolve: resolve_functor_impl::<T>,
            filter_owned,
            filter_and_resolve,
        }
    }

    pub fn deserialization_seed(&self) -> MagicAnyDeserializeSeed {
        self.deserializer
    }

    pub fn as_serialize<'a>(&self, value: &'a dyn MagicAny) -> &'a dyn erased_serde::Serialize {
        self.serializer.as_serialize(value)
    }

    pub fn is_resolved(&self, value: &dyn MagicAny) -> bool {
        (self.is_resolved)(value)
    }

    pub async fn resolve(&self, value: &dyn MagicAny) -> Result<Box<dyn MagicAny>> {
        (self.resolve)(value).await
    }

    pub fn filter_owned(&self, args: Box<dyn MagicAny>) -> Box<dyn MagicAny> {
        (self.filter_owned)(args)
    }

    /// This will return `(None, _)` even if the target is a method, if the method does not use
    /// `self`.
    pub async fn filter_and_resolve(&self, args: &dyn MagicAny) -> Result<Box<dyn MagicAny>> {
        (self.filter_and_resolve)(args).await
    }
}

fn resolve_functor_impl<T: MagicAny + TaskInput>(value: &dyn MagicAny) -> ResolveFuture<'_> {
    Box::pin(async move {
        let value = downcast_args_ref::<T>(value);
        let resolved = value.resolve_input().await?;
        Ok(Box::new(resolved) as Box<dyn MagicAny>)
    })
}

#[cfg(debug_assertions)]
#[inline(never)]
pub fn debug_downcast_args_error_msg(expected: &str, actual: &dyn MagicAny) -> String {
    format!(
        "Invalid argument type, expected {expected} got {}",
        (*actual).magic_type_name()
    )
}

pub fn downcast_args_owned<T: MagicAny>(args: Box<dyn MagicAny>) -> Box<T> {
    #[allow(unused_variables)]
    args.downcast::<T>()
        .map_err(|args| {
            #[cfg(debug_assertions)]
            return debug_downcast_args_error_msg(std::any::type_name::<T>(), &*args);
            #[cfg(not(debug_assertions))]
            return anyhow::anyhow!("Invalid argument type");
        })
        .unwrap()
}

pub fn downcast_args_ref<T: MagicAny>(args: &dyn MagicAny) -> &T {
    args.downcast_ref::<T>()
        .ok_or_else(|| {
            #[cfg(debug_assertions)]
            return anyhow::anyhow!(debug_downcast_args_error_msg(
                std::any::type_name::<T>(),
                args
            ));
            #[cfg(not(debug_assertions))]
            return anyhow::anyhow!("Invalid argument type");
        })
        .unwrap()
}

#[derive(Debug)]
pub struct FunctionMeta {
    /// Does not run the function as a task, and instead runs it inside the parent task using
    /// task-local state. The function call itself will not be cached, but cells will be created on
    /// the parent task.
    pub local: bool,
}

/// A native (rust) turbo-tasks function. It's used internally by
/// `#[turbo_tasks::function]`.
pub struct NativeFunction {
    /// A readable name of the function that is used to reporting purposes.
    pub(crate) name: &'static str,

    pub(crate) function_meta: FunctionMeta,

    pub(crate) arg_meta: ArgMeta,

    /// The functor that creates a functor from inputs. The inner functor
    /// handles the task execution.
    pub(crate) implementation: Box<dyn TaskFn + Send + Sync + 'static>,

    global_name: OnceLock<&'static str>,
}

impl Debug for NativeFunction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NativeFunction")
            .field("name", &self.name)
            .field("function_meta", &self.function_meta)
            .finish_non_exhaustive()
    }
}

impl NativeFunction {
    pub fn new_function<Mode, Inputs>(
        name: &'static str,
        function_meta: FunctionMeta,
        implementation: impl IntoTaskFn<Mode, Inputs>,
    ) -> Self
    where
        Inputs: TaskInput + Serialize + for<'de> Deserialize<'de> + 'static,
    {
        Self {
            name,
            function_meta,
            arg_meta: ArgMeta::new::<Inputs>(),
            implementation: Box::new(implementation.into_task_fn()),
            global_name: Default::default(),
        }
    }

    pub fn new_method_without_this<Mode, Inputs, I>(
        name: &'static str,
        function_meta: FunctionMeta,
        arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>,
        implementation: I,
    ) -> Self
    where
        Inputs: TaskInput + Serialize + for<'de> Deserialize<'de> + 'static,
        I: IntoTaskFn<Mode, Inputs>,
    {
        Self {
            name,
            function_meta,
            arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter {
                ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve)
            } else {
                ArgMeta::new::<Inputs>()
            },
            implementation: Box::new(implementation.into_task_fn()),
            global_name: Default::default(),
        }
    }

    pub fn new_method<Mode, This, Inputs, I>(
        name: &'static str,
        function_meta: FunctionMeta,
        arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>,
        implementation: I,
    ) -> Self
    where
        This: Sync + Send + 'static,
        Inputs: TaskInput + Serialize + for<'de> Deserialize<'de> + 'static,
        I: IntoTaskFnWithThis<Mode, This, Inputs>,
    {
        Self {
            name,
            function_meta,
            arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter {
                ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve)
            } else {
                ArgMeta::new::<Inputs>()
            },
            implementation: Box::new(implementation.into_task_fn_with_this()),
            global_name: Default::default(),
        }
    }

    /// Executed the function
    pub fn execute(&'static self, this: Option<RawVc>, arg: &dyn MagicAny) -> NativeTaskFuture {
        match (self.implementation).functor(this, arg) {
            Ok(functor) => functor,
            Err(err) => Box::pin(async { Err(err) }),
        }
    }

    pub fn span(&'static self, persistence: TaskPersistence, reason: TaskExecutionReason) -> Span {
        let flags = match persistence {
            TaskPersistence::Persistent => "",
            TaskPersistence::Transient => "transient",
            TaskPersistence::Local => "local",
        };
        tracing::trace_span!(
            "turbo_tasks::function",
            name = self.name,
            flags = flags,
            reason = reason.as_str()
        )
    }

    pub fn resolve_span(&'static self, persistence: TaskPersistence) -> Span {
        let flags = match persistence {
            TaskPersistence::Persistent => "",
            TaskPersistence::Transient => "transient",
            TaskPersistence::Local => "local",
        };
        tracing::trace_span!("turbo_tasks::resolve_call", name = self.name, flags = flags)
    }

    /// Returns the global name for this object
    pub fn global_name(&self) -> &'static str {
        self.global_name
            .get()
            .expect("cannot call `global_name` unless `register` has already been called")
    }

    pub fn register(&'static self, global_name: &'static str) {
        match self.global_name.set(global_name) {
            Ok(_) => {}
            Err(prev) => {
                panic!("function {global_name} registered twice, previously with {prev}");
            }
        }
        register_function(global_name, self);
    }
}

impl PartialEq for &'static NativeFunction {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(*self, *other)
    }
}

impl Eq for &'static NativeFunction {}

impl Hash for &'static NativeFunction {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        Hash::hash(&(*self as *const NativeFunction), state);
    }
}

impl PartialOrd for &'static NativeFunction {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for &'static NativeFunction {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        Ord::cmp(
            &(*self as *const NativeFunction),
            &(*other as *const NativeFunction),
        )
    }
}