Unverified Commit 5719439f authored by Matt Mastracci's avatar Matt Mastracci Committed by GitHub

[turbotask] Make turbotask function registration const (#90797)

# What 

Make turbotask function registration const -- all function registration
blocks are true &'static items, compiled directly into the binary.
Removes a few thousand allocations of type names and boxed impls of
TaskFn.

# Why

We have approx 2k functions, so the cost of Lazy construction +
temporary allocations adds up (even with compiler optimization). This
also unlocks the opportunity for further startup optimizations (in later
PRs).

# How

The `#[turbo_tasks::function]` macro now generates static items
initialized directly with const fn constructors instead of `Lazy::new(||
...)`, using `const { &into_task_fn(f) as &dyn TaskFn }` blocks to
produce `&'static dyn TaskFn` trait objects at compile time from
zero-sized function items.

Global names that previously required runtime format!() + Box::leak()
are now computed at compile time via `const_type_name()` (a const
wrapper around `std::any::type_name`) and a `const_concat!` macro that
concatenates string slices into a fixed-size byte array.

The NativeFunction struct, ArgMeta, and the
into_task_fn/into_task_fn_with_this wrappers are all const
fn-constructible, with input types inferred through a TaskFnInputs trait
that maps wrapper types to their argument tuples (we use a non-allocated
and non-compiled temporary "duplicate" `TaskFn` instance that is only
useful for type inference in a const context).

# Next Steps

I believe we can remove the const `type_name` in favour of the const
`type_id` and instead pull function names only when needed for display
purposes. This will show up in a future PR.

We can also remove non-const registration for things that aren't
functions as well, though I believe this is less important.
parent 4c379cad
...@@ -13,20 +13,19 @@ error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>` ...@@ -13,20 +13,19 @@ error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>`
= note: type of `self` must be `Self` or some type implementing `Receiver` = note: type of `self` must be `Self` or some type implementing `Receiver`
= help: consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>` = help: consider changing to `self`, `&self`, `&mut self`, or a type implementing `Receiver` such as `self: Box<Self>`, `self: Rc<Self>`, or `self: Arc<Self>`
error[E0277]: the trait bound `fn(OperationVc<Foobar>) -> Vc<()> {Foobar::arbitrary_self_type_turbo_tasks_function_inline}: turbo_tasks::task::function::IntoTaskFnWithThis<_, _, _>` is not satisfied error[E0277]: the trait bound `fn(OperationVc<Foobar>) -> Vc<()> {Foobar::arbitrary_self_type_turbo_tasks_function_inline}: turbo_tasks::task::function::TaskFnInputFunctionWithThis<_, _, _>` is not satisfied
--> tests/function/fail_operation_method_self_type.rs:11:1 --> tests/function/fail_operation_method_self_type.rs:11:1
| |
11 | #[turbo_tasks::value_impl] 11 | #[turbo_tasks::value_impl]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound | ^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound
| |
= help: the trait `turbo_tasks::task::function::TaskFnInputFunctionWithThis<_, _, _>` is not implemented for fn item `fn(OperationVc<Foobar>) -> Vc<()> {Foobar::arbitrary_self_type_turbo_tasks_function_inline}` = help: the trait `turbo_tasks::task::function::TaskFnInputFunctionWithThis<_, _, _>` is not implemented for fn item `fn(OperationVc<Foobar>) -> Vc<()> {Foobar::arbitrary_self_type_turbo_tasks_function_inline}`
= note: required for `fn(OperationVc<Foobar>) -> Vc<()> {Foobar::arbitrary_self_type_turbo_tasks_function_inline}` to implement `turbo_tasks::task::function::IntoTaskFnWithThis<_, _, _>` note: required by a bound in `turbo_tasks::macro_helpers::into_task_fn_with_this`
note: required by a bound in `turbo_tasks::macro_helpers::NativeFunction::new_method` --> $WORKSPACE/turbopack/crates/turbo-tasks/src/task/function.rs
--> $WORKSPACE/turbopack/crates/turbo-tasks/src/native_function.rs
| |
| pub fn new_method<Mode, This, Inputs, I>( | pub const fn into_task_fn_with_this<
| ---------- required by a bound in this associated function | ---------------------- required by a bound in this function
... ...
| I: IntoTaskFnWithThis<Mode, This, Inputs>, | F: TaskFnInputFunctionWithThis<Mode, This, Inputs>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `NativeFunction::new_method` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `into_task_fn_with_this`
= note: this error originates in the attribute macro `turbo_tasks::value_impl` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the attribute macro `turbo_tasks::value_impl` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -1104,60 +1104,43 @@ impl NativeFn { ...@@ -1104,60 +1104,43 @@ impl NativeFn {
is_root, is_root,
} = self; } = self;
if *is_method { let task_fn = if *is_method && *is_self_used {
let arg_filter = if let Some(filter) = filter_trait_call_args { quote! { turbo_tasks::macro_helpers::into_task_fn_with_this(#function_path) }
let FilterTraitCallArgsTokens { } else {
filter_owned, quote! { turbo_tasks::macro_helpers::into_task_fn(#function_path) }
filter_and_resolve, };
} = filter;
quote! {
::std::option::Option::Some((
#filter_owned,
#filter_and_resolve,
))
}
} else {
quote! { ::std::option::Option::None }
};
if *is_self_used { let arg_meta = if let Some(filter) = filter_trait_call_args {
quote! { let FilterTraitCallArgsTokens {
{ filter_owned,
#[allow(deprecated)] filter_and_resolve,
turbo_tasks::macro_helpers::NativeFunction::new_method( } = filter;
#function_path_string, quote! {
#function_global_name, turbo_tasks::macro_helpers::ArgMeta::with_filter_trait_call_from(
#arg_filter, &#task_fn,
#function_path, #filter_owned,
#is_root, #filter_and_resolve,
) )
}
}
} else {
quote! {
{
#[allow(deprecated)]
turbo_tasks::macro_helpers::NativeFunction::new_method_without_this(
#function_path_string,
#function_global_name,
#arg_filter,
#function_path,
#is_root,
)
}
}
} }
} else { } else {
quote! { quote! {
{ turbo_tasks::macro_helpers::ArgMeta::new_from(&#task_fn)
#[allow(deprecated)] }
turbo_tasks::macro_helpers::NativeFunction::new_function( };
#function_path_string,
#function_global_name, quote! {
#function_path, {
#is_root, #[allow(deprecated)]
) const IMPL: &dyn turbo_tasks::task::TaskFn =
} const { &#task_fn as &dyn turbo_tasks::task::TaskFn };
#[allow(deprecated)]
turbo_tasks::macro_helpers::NativeFunction::new(
#function_path_string,
#function_global_name,
#arg_meta,
IMPL,
#is_root,
)
} }
} }
} }
......
...@@ -58,8 +58,8 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -58,8 +58,8 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream {
let inline_attrs = filter_inline_attributes(&attrs[..]); let inline_attrs = filter_inline_attributes(&attrs[..]);
let native_fn = NativeFn { let native_fn = NativeFn {
// depth = 2, this strips off a closure and a static item from the name // depth = 1, this strips off the static item name
function_global_name: global_name_for_scope(2, ident), function_global_name: global_name_for_scope(1, ident),
function_path_string: ident.to_string(), function_path_string: ident.to_string(),
function_path: quote! { #inline_function_ident }, function_path: quote! { #inline_function_ident },
is_method: turbo_fn.is_method(), is_method: turbo_fn.is_method(),
...@@ -82,9 +82,7 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -82,9 +82,7 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream {
#[doc(hidden)] #[doc(hidden)]
#inline_signature #inline_block #inline_signature #inline_block
static #native_function_ident: static #native_function_ident: #native_function_ty = #native_function_def;
turbo_tasks::macro_helpers::Lazy<#native_function_ty> =
turbo_tasks::macro_helpers::Lazy::new(|| #native_function_def);
// Register the function for deserialization // Register the function for deserialization
turbo_tasks::macro_helpers::inventory_submit! { turbo_tasks::macro_helpers::inventory_submit! {
......
...@@ -149,9 +149,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -149,9 +149,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
pub(self) #inline_signature #inline_block pub(self) #inline_signature #inline_block
} }
static #native_function_ident: static #native_function_ident: #native_function_ty = #native_function_def;
turbo_tasks::macro_helpers::Lazy<#native_function_ty> =
turbo_tasks::macro_helpers::Lazy::new(|| #native_function_def);
// Register the function for deserialization // Register the function for deserialization
turbo_tasks::macro_helpers::inventory_submit! { turbo_tasks::macro_helpers::inventory_submit! {
...@@ -278,9 +276,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -278,9 +276,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
#inline_signature #inline_block #inline_signature #inline_block
} }
static #native_function_ident: static #native_function_ident: #native_function_ty = #native_function_def;
turbo_tasks::macro_helpers::Lazy<#native_function_ty> =
turbo_tasks::macro_helpers::Lazy::new(|| #native_function_def);
// Register the function for deserialization // Register the function for deserialization
turbo_tasks::macro_helpers::inventory_submit! { turbo_tasks::macro_helpers::inventory_submit! {
......
...@@ -239,9 +239,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -239,9 +239,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
#inline_signature #inline_block #inline_signature #inline_block
} }
static #native_function_ident: static #native_function_ident: #native_function_ty = #native_function_def;
turbo_tasks::macro_helpers::Lazy<#native_function_ty> =
turbo_tasks::macro_helpers::Lazy::new(|| #native_function_def);
// Register the function for deserialization // Register the function for deserialization
turbo_tasks::macro_helpers::inventory_submit! { turbo_tasks::macro_helpers::inventory_submit! {
......
...@@ -39,6 +39,7 @@ ...@@ -39,6 +39,7 @@
#![feature(sync_unsafe_cell)] #![feature(sync_unsafe_cell)]
#![feature(async_fn_traits)] #![feature(async_fn_traits)]
#![feature(impl_trait_in_assoc_type)] #![feature(impl_trait_in_assoc_type)]
#![feature(const_type_name)]
pub mod backend; pub mod backend;
mod capture_future; mod capture_future;
......
...@@ -19,8 +19,9 @@ pub use crate::{ ...@@ -19,8 +19,9 @@ pub use crate::{
magic_any::MagicAny, magic_any::MagicAny,
manager::{find_cell_by_id, find_cell_by_type, spawn_detached_for_testing}, manager::{find_cell_by_id, find_cell_by_type, spawn_detached_for_testing},
native_function::{ native_function::{
CollectableFunction, NativeFunction, downcast_args_owned, downcast_args_ref, ArgMeta, CollectableFunction, NativeFunction, downcast_args_owned, downcast_args_ref,
}, },
task::function::{into_task_fn, into_task_fn_with_this},
value_type::{CollectableTrait, CollectableValueType}, value_type::{CollectableTrait, CollectableValueType},
}; };
...@@ -71,6 +72,91 @@ pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as std::ptr::Pointee>::Met ...@@ -71,6 +72,91 @@ pub const fn metadata<T: ?Sized>(ptr: *const T) -> <T as std::ptr::Pointee>::Met
std::ptr::metadata(ptr) std::ptr::metadata(ptr)
} }
/// Const wrapper around `std::any::type_name` so downstream crates don't need to enable the
/// unstable `const_type_name` feature.
#[doc(hidden)]
pub const fn const_type_name<T: ?Sized>() -> &'static str {
std::any::type_name::<T>()
}
/// Compute the total byte length of all string slices.
#[doc(hidden)]
pub const fn const_concat_len(slices: &[&str]) -> usize {
let mut total = 0;
let mut i = 0;
while i < slices.len() {
total += slices[i].len();
i += 1;
}
total
}
/// Copy all string slices into a fixed-size byte array at compile time.
#[doc(hidden)]
pub const fn const_concat_into<const N: usize>(slices: &[&str]) -> [u8; N] {
let mut buf = [0u8; N];
let mut pos = 0;
let mut i = 0;
while i < slices.len() {
let bytes = slices[i].as_bytes();
let (_, rest) = buf.split_at_mut(pos);
let (dst, _) = rest.split_at_mut(bytes.len());
dst.copy_from_slice(bytes);
pos += bytes.len();
i += 1;
}
assert!(pos == N, "const_concat: length mismatch");
buf
}
/// Concatenate a const slice of `&str` into a single `&'static str` at compile time.
///
/// This is a macro only because const generics require the length to be a const expression
/// computed from the input. The call sites look like normal function calls:
///
/// ```ignore
/// const_concat!(&[type_name, "::", method_name])
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! const_concat {
($slices:expr) => {{
const SLICES: &[&str] = $slices;
const LEN: usize = $crate::macro_helpers::const_concat_len(SLICES);
const BYTES: [u8; LEN] = $crate::macro_helpers::const_concat_into(SLICES);
// SAFETY: all inputs are valid UTF-8 strings, concatenation preserves UTF-8
const STR: &str = unsafe { ::std::str::from_utf8_unchecked(&BYTES) };
STR
}};
}
/// Const fn that strips `count` trailing `::component` segments from a string.
/// Used by `global_name_for_scope!` to extract the module path from a `type_name`.
#[doc(hidden)]
pub const fn strip_trailing_segments(s: &str, count: usize) -> &str {
let mut remaining = s;
let mut i = 0;
while i < count {
let bytes = remaining.as_bytes();
if bytes.len() < 2 {
return s;
}
let mut pos = bytes.len();
loop {
if pos < 2 {
return s;
}
pos -= 1;
if bytes[pos] == b':' && bytes[pos - 1] == b':' {
(remaining, _) = remaining.split_at(pos - 1);
break;
}
}
i += 1;
}
remaining
}
/// A registry of all the impl vtables for a given VcValue trait /// A registry of all the impl vtables for a given VcValue trait
/// This is constructed in the macro gencode and populated by the registry. /// This is constructed in the macro gencode and populated by the registry.
#[derive(Default)] #[derive(Default)]
...@@ -201,19 +287,6 @@ macro_rules! inventory_submit { ...@@ -201,19 +287,6 @@ macro_rules! inventory_submit {
#[doc(hidden)] #[doc(hidden)]
pub use inventory::submit as inventory_submit_inner; pub use inventory::submit as inventory_submit_inner;
#[doc(hidden)]
#[macro_export]
macro_rules! debug_assert_runs_once {
() => {
#[cfg(debug_assertions)]
{
use ::std::sync::atomic::{AtomicBool, Ordering};
static ONLY_RUN_ONCE: AtomicBool = AtomicBool::new(false);
assert!(!AtomicBool::swap(&ONLY_RUN_ONCE, true, Ordering::AcqRel));
}
};
}
/// Use `type_name` to get globally unique identifier that's stable across multiple executions of /// Use `type_name` to get globally unique identifier that's stable across multiple executions of
/// the same Turbopack version, potentially allowing cache sharing across platforms/architectures. /// the same Turbopack version, potentially allowing cache sharing across platforms/architectures.
/// ///
...@@ -223,76 +296,63 @@ macro_rules! debug_assert_runs_once { ...@@ -223,76 +296,63 @@ macro_rules! debug_assert_runs_once {
#[macro_export] #[macro_export]
macro_rules! global_name_for_type { macro_rules! global_name_for_type {
($item:ty) => { ($item:ty) => {
::std::any::type_name::<$item>() $crate::macro_helpers::const_type_name::<$item>()
}; };
} }
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! global_name_for_method { macro_rules! global_name_for_method {
($ty:ty, $method:ident) => {{ ($ty:ty, $method:ident) => {
// We cannot use `concat!` because `type_name` is not const, so we leak the string instead $crate::const_concat!(&[
// to get a &'static str. $crate::macro_helpers::const_type_name::<$ty>(),
// "::",
// Assumption: the code that invokes this macro is only run once (e.g. part of an
// `inventory::submit!` callsite), so we're leaking a bounded number of strings.
$crate::debug_assert_runs_once!();
::std::boxed::Box::leak(::std::string::String::into_boxed_str(::std::format!(
"{}::{}",
::std::any::type_name::<$ty>(),
::std::stringify!($method), ::std::stringify!($method),
))) ])
}}; };
} }
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! global_name_for_trait_method { macro_rules! global_name_for_trait_method {
($trait:path, $method:ident) => {{ ($trait:path, $method:ident) => {
$crate::debug_assert_runs_once!(); $crate::const_concat!(&[
::std::boxed::Box::leak(::std::string::String::into_boxed_str(::std::format!( "<",
"<{}>::{}", $crate::macro_helpers::const_type_name::<dyn $trait>(),
::std::any::type_name::<dyn $trait>(), ">::",
::std::stringify!($method), ::std::stringify!($method),
))) ])
}}; };
} }
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! global_name_for_trait_method_impl { macro_rules! global_name_for_trait_method_impl {
($ty:ty, $trait:path, $method:ident) => {{ ($ty:ty, $trait:path, $method:ident) => {
$crate::debug_assert_runs_once!(); $crate::const_concat!(&[
::std::boxed::Box::leak(::std::string::String::into_boxed_str(::std::format!( "<",
"<{} as {}>::{}", $crate::macro_helpers::const_type_name::<$ty>(),
::std::any::type_name::<$ty>(), " as ",
::std::any::type_name::<dyn $trait>(), $crate::macro_helpers::const_type_name::<dyn $trait>(),
">::",
::std::stringify!($method), ::std::stringify!($method),
))) ])
}}; };
} }
/// Get a globally unique name for an identifier a current or parent scope. /// Get a globally unique name for an identifier in a current or parent scope.
#[doc(hidden)] #[doc(hidden)]
#[macro_export] #[macro_export]
macro_rules! global_name_for_scope { macro_rules! global_name_for_scope {
($depth:literal, $($item:tt)+) => {{ ($depth:literal, $($item:tt)+) => {{
$crate::debug_assert_runs_once!();
struct PlaceholderMarkerType; struct PlaceholderMarkerType;
let mut base = ::std::any::type_name::<PlaceholderMarkerType>(); $crate::const_concat!(&[
$crate::macro_helpers::strip_trailing_segments(
// strip a caller-defined number of ancestors from the end of the path $crate::macro_helpers::const_type_name::<PlaceholderMarkerType>(),
for _ in 0..($depth+1) { // add one to `depth` for the placeholder $depth + 1, // add one for the placeholder
base = ::std::option::Option::unwrap(
::std::primitive::str::rsplit_once(base, "::"),
).0;
}
::std::boxed::Box::leak(
::std::string::String::into_boxed_str(
::std::format!("{}::{}", base, ::std::stringify!($($item)+))
), ),
) "::",
::std::stringify!($($item)+),
])
}} }}
} }
...@@ -3,7 +3,6 @@ use std::{any::Any, fmt::Debug, hash::Hash, pin::Pin}; ...@@ -3,7 +3,6 @@ use std::{any::Any, fmt::Debug, hash::Hash, pin::Pin};
use anyhow::Result; use anyhow::Result;
use bincode::{Decode, Encode}; use bincode::{Decode, Encode};
use futures::Future; use futures::Future;
use once_cell::sync::Lazy;
use tracing::Span; use tracing::Span;
use turbo_bincode::{AnyDecodeFn, AnyEncodeFn, new_hash_encoder}; use turbo_bincode::{AnyDecodeFn, AnyEncodeFn, new_hash_encoder};
use turbo_tasks_hash::DeterministicHasher; use turbo_tasks_hash::DeterministicHasher;
...@@ -11,10 +10,7 @@ use turbo_tasks_hash::DeterministicHasher; ...@@ -11,10 +10,7 @@ use turbo_tasks_hash::DeterministicHasher;
use crate::{ use crate::{
RawVc, TaskExecutionReason, TaskInput, TaskPersistence, TaskPriority, RawVc, TaskExecutionReason, TaskInput, TaskPersistence, TaskPriority,
magic_any::{MagicAny, any_as_encode}, magic_any::{MagicAny, any_as_encode},
task::{ task::{TaskFn, TaskFnInputs, function::NativeTaskFuture},
IntoTaskFn, TaskFn,
function::{IntoTaskFnWithThis, NativeTaskFuture},
},
}; };
type ResolveFuture<'a> = Pin<Box<dyn Future<Output = Result<Box<dyn MagicAny>>> + Send + 'a>>; type ResolveFuture<'a> = Pin<Box<dyn Future<Output = Result<Box<dyn MagicAny>>> + Send + 'a>>;
...@@ -22,8 +18,10 @@ type ResolveFunctor = for<'a> fn(&'a dyn MagicAny) -> ResolveFuture<'a>; ...@@ -22,8 +18,10 @@ type ResolveFunctor = for<'a> fn(&'a dyn MagicAny) -> ResolveFuture<'a>;
type IsResolvedFunctor = fn(&dyn MagicAny) -> bool; type IsResolvedFunctor = fn(&dyn MagicAny) -> bool;
type FilterOwnedArgsFunctor = for<'a> fn(Box<dyn MagicAny>) -> Box<dyn MagicAny>; #[doc(hidden)]
type FilterAndResolveFunctor = ResolveFunctor; pub type FilterOwnedArgsFunctor = for<'a> fn(Box<dyn MagicAny>) -> Box<dyn MagicAny>;
#[doc(hidden)]
pub type FilterAndResolveFunctor = ResolveFunctor;
/// Function pointer that encodes a task argument directly to a hasher. /// Function pointer that encodes a task argument directly to a hasher.
/// ///
...@@ -51,7 +49,29 @@ pub struct ArgMeta { ...@@ -51,7 +49,29 @@ pub struct ArgMeta {
} }
impl ArgMeta { impl ArgMeta {
pub fn new<T>() -> Self /// Equivalent to `new`, but with type inference from a function.
#[doc(hidden)]
pub const fn new_from<T>(_t: &T) -> Self
where
T: TaskFnInputs,
{
Self::new::<T::INPUTS>()
}
/// Equivalent to `with_filter_trait_call`, but with type inference from a function.
#[doc(hidden)]
pub const fn with_filter_trait_call_from<T>(
_t: &T,
filter_owned: FilterOwnedArgsFunctor,
filter_and_resolve: FilterAndResolveFunctor,
) -> Self
where
T: TaskFnInputs,
{
Self::with_filter_trait_call::<T::INPUTS>(filter_owned, filter_and_resolve)
}
pub const fn new<T>() -> Self
where where
T: TaskInput + Encode + Decode<()> + 'static, T: TaskInput + Encode + Decode<()> + 'static,
{ {
...@@ -61,7 +81,7 @@ impl ArgMeta { ...@@ -61,7 +81,7 @@ impl ArgMeta {
Self::with_filter_trait_call::<T>(noop_filter_args, resolve_functor_impl::<T>) Self::with_filter_trait_call::<T>(noop_filter_args, resolve_functor_impl::<T>)
} }
pub fn with_filter_trait_call<T>( pub const fn with_filter_trait_call<T>(
filter_owned: FilterOwnedArgsFunctor, filter_owned: FilterOwnedArgsFunctor,
filter_and_resolve: FilterAndResolveFunctor, filter_and_resolve: FilterAndResolveFunctor,
) -> Self ) -> Self
...@@ -167,9 +187,9 @@ pub struct NativeFunction { ...@@ -167,9 +187,9 @@ pub struct NativeFunction {
/// The functor that creates a functor from inputs. The inner functor /// The functor that creates a functor from inputs. The inner functor
/// handles the task execution. /// handles the task execution.
pub(crate) implementation: Box<dyn TaskFn + Send + Sync + 'static>, pub(crate) implementation: &'static dyn TaskFn,
// The globally unique name for this function, used when persisting // The globally unique name for this function, used when persisting.
pub(crate) global_name: &'static str, pub(crate) global_name: &'static str,
/// Whether this function's tasks should be treated as root nodes in the aggregation graph. /// Whether this function's tasks should be treated as root nodes in the aggregation graph.
...@@ -187,69 +207,18 @@ impl Debug for NativeFunction { ...@@ -187,69 +207,18 @@ impl Debug for NativeFunction {
} }
impl NativeFunction { impl NativeFunction {
pub fn new_function<Mode, Inputs>( pub const fn new(
name: &'static str,
global_name: &'static str,
implementation: impl IntoTaskFn<Mode, Inputs>,
is_root: bool,
) -> Self
where
Inputs: TaskInput + Encode + Decode<()> + 'static,
{
Self {
name,
global_name,
arg_meta: ArgMeta::new::<Inputs>(),
implementation: Box::new(implementation.into_task_fn()),
is_root,
}
}
pub fn new_method_without_this<Mode, Inputs, I>(
name: &'static str, name: &'static str,
global_name: &'static str, global_name: &'static str,
arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>, arg_meta: ArgMeta,
implementation: I, implementation: &'static dyn TaskFn,
is_root: bool, is_root: bool,
) -> Self ) -> Self {
where
Inputs: TaskInput + Encode + Decode<()> + 'static,
I: IntoTaskFn<Mode, Inputs>,
{
Self { Self {
name, name,
global_name, global_name,
arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter { arg_meta,
ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve) implementation,
} else {
ArgMeta::new::<Inputs>()
},
implementation: Box::new(implementation.into_task_fn()),
is_root,
}
}
pub fn new_method<Mode, This, Inputs, I>(
name: &'static str,
global_name: &'static str,
arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>,
implementation: I,
is_root: bool,
) -> Self
where
This: Sync + Send + 'static,
Inputs: TaskInput + Encode + Decode<()> + 'static,
I: IntoTaskFnWithThis<Mode, This, Inputs>,
{
Self {
name,
global_name,
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()),
is_root, is_root,
} }
} }
...@@ -313,6 +282,6 @@ impl Ord for &'static NativeFunction { ...@@ -313,6 +282,6 @@ impl Ord for &'static NativeFunction {
} }
} }
pub struct CollectableFunction(pub &'static Lazy<NativeFunction>); pub struct CollectableFunction(pub &'static NativeFunction);
inventory::collect! {CollectableFunction} inventory::collect! {CollectableFunction}
...@@ -125,7 +125,7 @@ impl<T: RegistryItem> Registry<T> { ...@@ -125,7 +125,7 @@ impl<T: RegistryItem> Registry<T> {
static FUNCTIONS: Lazy<Registry<NativeFunction>> = Lazy::new(|| { static FUNCTIONS: Lazy<Registry<NativeFunction>> = Lazy::new(|| {
let functions = inventory::iter::<CollectableFunction> let functions = inventory::iter::<CollectableFunction>
.into_iter() .into_iter()
.map(|c| &**c.0) .map(|c| c.0)
.collect::<Vec<_>>(); .collect::<Vec<_>>();
Registry::new_from_items(functions) Registry::new_from_items(functions)
}); });
......
...@@ -34,51 +34,38 @@ pub trait TaskFn: Send + Sync + 'static { ...@@ -34,51 +34,38 @@ pub trait TaskFn: Send + Sync + 'static {
fn functor(&self, this: Option<RawVc>, arg: &dyn MagicAny) -> Result<NativeTaskFuture>; fn functor(&self, this: Option<RawVc>, arg: &dyn MagicAny) -> Result<NativeTaskFuture>;
} }
pub trait IntoTaskFn<Mode, Inputs> { /// A trait for `TaskFn` implementations that allows task inputs to be extracted as a type.
type TaskFn: TaskFn; pub trait TaskFnInputs: TaskFn {
type INPUTS: TaskInput + TaskInputs;
fn into_task_fn(self) -> Self::TaskFn;
} }
impl<F, Mode, Inputs> IntoTaskFn<Mode, Inputs> for F pub const fn into_task_fn<
where
F: TaskFnInputFunction<Mode, Inputs>,
Mode: TaskFnMode, Mode: TaskFnMode,
Inputs: TaskInputs, Inputs: TaskInputs,
{ F: TaskFnInputFunction<Mode, Inputs>,
type TaskFn = FunctionTaskFn<F, Mode, Inputs>; >(
f: F,
fn into_task_fn(self) -> Self::TaskFn { ) -> FunctionTaskFn<F, Mode, Inputs> {
FunctionTaskFn { FunctionTaskFn {
task_fn: self, task_fn: f,
mode: PhantomData, mode: PhantomData,
inputs: PhantomData, inputs: PhantomData,
}
} }
} }
pub trait IntoTaskFnWithThis<Mode, This, Inputs> { pub const fn into_task_fn_with_this<
type TaskFn: TaskFn;
fn into_task_fn_with_this(self) -> Self::TaskFn;
}
impl<F, Mode, This, Inputs> IntoTaskFnWithThis<Mode, This, Inputs> for F
where
F: TaskFnInputFunctionWithThis<Mode, This, Inputs>,
Mode: TaskFnMode, Mode: TaskFnMode,
This: Sync + Send + 'static, This: Send + Sync + 'static,
Inputs: TaskInputs, Inputs: TaskInputs,
{ F: TaskFnInputFunctionWithThis<Mode, This, Inputs>,
type TaskFn = FunctionTaskFnWithThis<F, Mode, This, Inputs>; >(
f: F,
fn into_task_fn_with_this(self) -> Self::TaskFn { ) -> FunctionTaskFnWithThis<F, Mode, This, Inputs> {
FunctionTaskFnWithThis { FunctionTaskFnWithThis {
task_fn: self, task_fn: f,
mode: PhantomData, mode: PhantomData,
this: PhantomData, this: PhantomData,
inputs: PhantomData, inputs: PhantomData,
}
} }
} }
...@@ -99,6 +86,15 @@ where ...@@ -99,6 +86,15 @@ where
} }
} }
impl<F, Mode, Inputs> TaskFnInputs for FunctionTaskFn<F, Mode, Inputs>
where
F: TaskFnInputFunction<Mode, Inputs>,
Mode: TaskFnMode,
Inputs: TaskInputs + TaskInput,
{
type INPUTS = Inputs;
}
pub struct FunctionTaskFnWithThis< pub struct FunctionTaskFnWithThis<
F, F,
Mode: TaskFnMode, Mode: TaskFnMode,
...@@ -126,12 +122,29 @@ where ...@@ -126,12 +122,29 @@ where
} }
} }
trait TaskFnInputFunction<Mode: TaskFnMode, Inputs: TaskInputs>: Send + Sync + Clone + 'static { impl<F, Mode, This, Inputs> TaskFnInputs for FunctionTaskFnWithThis<F, Mode, This, Inputs>
fn functor(&self, arg: &dyn MagicAny) -> Result<NativeTaskFuture>; where
F: TaskFnInputFunctionWithThis<Mode, This, Inputs>,
Mode: TaskFnMode,
This: Sync + Send + 'static,
Inputs: TaskInputs + TaskInput,
{
type INPUTS = Inputs;
} }
trait TaskFnInputFunctionWithThis<Mode: TaskFnMode, This: Sync + Send + 'static, Inputs: TaskInputs>: #[doc(hidden)]
pub trait TaskFnInputFunction<Mode: TaskFnMode, Inputs: TaskInputs>:
Send + Sync + Clone + 'static Send + Sync + Clone + 'static
{
fn functor(&self, arg: &dyn MagicAny) -> Result<NativeTaskFuture>;
}
#[doc(hidden)]
pub trait TaskFnInputFunctionWithThis<
Mode: TaskFnMode,
This: Sync + Send + 'static,
Inputs: TaskInputs,
>: Send + Sync + Clone + 'static
{ {
fn functor(&self, this: RawVc, arg: &dyn MagicAny) -> Result<NativeTaskFuture>; fn functor(&self, this: RawVc, arg: &dyn MagicAny) -> Result<NativeTaskFuture>;
} }
...@@ -453,25 +466,25 @@ mod tests { ...@@ -453,25 +466,25 @@ mod tests {
} }
*/ */
let _task_fn = no_args.into_task_fn(); let task_fn = into_task_fn(no_args);
accepts_task_fn(no_args.into_task_fn()); accepts_task_fn(task_fn);
let _task_fn = one_arg.into_task_fn(); let task_fn = into_task_fn(one_arg);
accepts_task_fn(one_arg.into_task_fn()); accepts_task_fn(task_fn);
let _task_fn = async_one_arg.into_task_fn(); let task_fn = into_task_fn(async_one_arg);
accepts_task_fn(async_one_arg.into_task_fn()); accepts_task_fn(task_fn);
let task_fn = with_recv.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(with_recv);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
let task_fn = async_with_recv.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(async_with_recv);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
let task_fn = with_recv_and_str.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(with_recv_and_str);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
let task_fn = async_with_recv_and_str.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(async_with_recv_and_str);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
let task_fn = async_with_recv_and_str_and_result.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(async_with_recv_and_str_and_result);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
let task_fn = <Struct as AsyncTrait>::async_method.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(<Struct as AsyncTrait>::async_method);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
let task_fn = Struct::inherent_method.into_task_fn_with_this(); let task_fn = into_task_fn_with_this(Struct::inherent_method);
accepts_task_fn(task_fn); accepts_task_fn(task_fn);
/* /*
......
...@@ -6,7 +6,7 @@ pub(crate) mod task_input; ...@@ -6,7 +6,7 @@ pub(crate) mod task_input;
pub(crate) mod task_output; pub(crate) mod task_output;
pub use from_task_input::FromTaskInput; pub use from_task_input::FromTaskInput;
pub use function::{AsyncFunctionMode, FunctionMode, IntoTaskFn, TaskFn}; pub use function::{TaskFn, TaskFnInputs};
pub use shared_reference::{SharedReference, TypedSharedReference}; pub use shared_reference::{SharedReference, TypedSharedReference};
pub use task_input::TaskInput; pub use task_input::TaskInput;
pub use task_output::TaskOutput; pub use task_output::TaskOutput;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment