Commit f0fe0cb0 authored by Luke Sandberg's avatar Luke Sandberg Committed by Jiachi Liu

[turbopack] Remove LocalTaskType::Native, it is dead (#85480)

### What
Remove `LocalTaskType::Native` and supporting infrastructure.  Simplify schedule_local_task to remove an allocation and `CaptureFuture`.

### Why?
local tasks for things other than 'resolve' tasks have been proven to not be a very useful idea.  However, for resolve tasks they do still make sense.  We can use the small amount of indirection provided by `LocalTask` to optimize how we launch other turbotasks.

Now that the local task implementation is clearly just about turbo-tasks infrastructure (rather than calling arbitrary 'user code') we can simplify dispatching a bit.
parent 4b79b55b
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
#![allow(clippy::needless_return)] // tokio macro-generated code doesn't respect this
use anyhow::Result;
use turbo_tasks::{Vc, test_helpers::current_task_for_testing};
use turbo_tasks_testing::{Registration, register, run_once};
static REGISTRATION: Registration = register!();
fn task_id() -> u32 {
if let Some(id) = current_task_for_testing() {
*id
} else {
0
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_local_task_id() -> Result<()> {
run_once(&REGISTRATION, || async {
let local_vc = get_local_task_id();
assert!(local_vc.is_local());
assert_eq!(*local_vc.await.unwrap(), task_id());
let local_trait_vc = Foo {}.cell().get_local_task_id();
assert!(local_trait_vc.is_local());
assert_eq!(*local_trait_vc.await.unwrap(), task_id());
let non_local_vc = get_non_local_task_id();
assert!(!non_local_vc.is_local());
assert_ne!(*non_local_vc.await.unwrap(), task_id());
let non_local_trait_vc = Foo {}.cell().get_non_local_task_id();
assert!(!non_local_trait_vc.is_local());
assert_ne!(*non_local_trait_vc.await.unwrap(), task_id());
Ok(())
})
.await
}
#[turbo_tasks::function(local)]
fn get_local_task_id() -> Vc<u32> {
Vc::cell(task_id())
}
#[turbo_tasks::function]
fn get_non_local_task_id() -> Vc<u32> {
Vc::cell(task_id())
}
#[turbo_tasks::value_trait]
trait SomeTrait {
#[turbo_tasks::function]
fn get_local_task_id(self: Vc<Self>) -> Vc<u32>;
#[turbo_tasks::function]
fn get_non_local_task_id(self: Vc<Self>) -> Vc<u32>;
}
#[turbo_tasks::value(shared)]
struct Foo {}
#[turbo_tasks::value_impl]
impl SomeTrait for Foo {
#[turbo_tasks::function(local)]
fn get_local_task_id(self: Vc<Self>) -> Vc<u32> {
Vc::cell(task_id())
}
#[turbo_tasks::function]
fn get_non_local_task_id(self: Vc<Self>) -> Vc<u32> {
Vc::cell(task_id())
}
}
error: unexpected token, expected one of: "fs", "network", "operation", "local" error: unexpected token, expected one of: "fs", "network", or "operation"
--> tests/function/fail_attribute_invalid_args.rs:10:25 --> tests/function/fail_attribute_invalid_args.rs:10:25
| |
10 | #[turbo_tasks::function(invalid_argument)] 10 | #[turbo_tasks::function(invalid_argument)]
......
error: unexpected token, expected one of: "fs", "network", "operation", "local" error: unexpected token, expected one of: "fs", "network", or "operation"
--> tests/function/fail_attribute_invalid_args_inherent_impl.rs:15:29 --> tests/function/fail_attribute_invalid_args_inherent_impl.rs:15:29
| |
15 | #[turbo_tasks::function(invalid_argument)] 15 | #[turbo_tasks::function(invalid_argument)]
......
...@@ -30,8 +30,6 @@ pub struct TurboFn<'a> { ...@@ -30,8 +30,6 @@ pub struct TurboFn<'a> {
exposed_inputs: Vec<Input>, exposed_inputs: Vec<Input>,
/// Should we return `OperationVc` and require that all arguments are `NonLocalValue`s? /// Should we return `OperationVc` and require that all arguments are `NonLocalValue`s?
operation: bool, operation: bool,
/// Should this function use `TaskPersistence::LocalCells`?
local: bool,
} }
#[derive(Debug)] #[derive(Debug)]
...@@ -206,7 +204,6 @@ impl TurboFn<'_> { ...@@ -206,7 +204,6 @@ impl TurboFn<'_> {
this, this,
exposed_inputs, exposed_inputs,
operation: args.operation.is_some(), operation: args.operation.is_some(),
local: args.local.is_some(),
inline_ident, inline_ident,
}) })
} }
...@@ -494,26 +491,14 @@ impl TurboFn<'_> { ...@@ -494,26 +491,14 @@ impl TurboFn<'_> {
} }
pub fn persistence(&self) -> impl ToTokens { pub fn persistence(&self) -> impl ToTokens {
if self.local { quote! {
quote! { turbo_tasks::macro_helpers::get_persistence_from_inputs(&*inputs)
turbo_tasks::TaskPersistence::Local
}
} else {
quote! {
turbo_tasks::macro_helpers::get_non_local_persistence_from_inputs(&*inputs)
}
} }
} }
pub fn persistence_with_this(&self) -> impl ToTokens { pub fn persistence_with_this(&self) -> impl ToTokens {
if self.local { quote! {
quote! { turbo_tasks::macro_helpers::get_persistence_from_inputs_and_this(this, &*inputs)
turbo_tasks::TaskPersistence::Local
}
} else {
quote! {
turbo_tasks::macro_helpers::get_non_local_persistence_from_inputs_and_this(this, &*inputs)
}
} }
} }
...@@ -748,10 +733,6 @@ pub struct FunctionArguments { ...@@ -748,10 +733,6 @@ pub struct FunctionArguments {
/// ///
/// If there is an error due to this option being set, it should be reported to this span. /// If there is an error due to this option being set, it should be reported to this span.
pub operation: Option<Span>, pub operation: Option<Span>,
/// Does not run the function as a real 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: Option<Span>,
} }
impl Parse for FunctionArguments { impl Parse for FunctionArguments {
...@@ -776,24 +757,15 @@ impl Parse for FunctionArguments { ...@@ -776,24 +757,15 @@ impl Parse for FunctionArguments {
("operation", Meta::Path(_)) => { ("operation", Meta::Path(_)) => {
parsed_args.operation = Some(meta.span()); parsed_args.operation = Some(meta.span());
} }
("local", Meta::Path(_)) => {
parsed_args.local = Some(meta.span());
}
(_, meta) => { (_, meta) => {
return Err(syn::Error::new_spanned( return Err(syn::Error::new_spanned(
meta, meta,
"unexpected token, expected one of: \"fs\", \"network\", \"operation\", \ "unexpected token, expected one of: \"fs\", \"network\", or \"operation\"",
\"local\"",
)); ));
} }
} }
} }
if let (Some(_), Some(span)) = (parsed_args.local, parsed_args.operation) {
return Err(syn::Error::new(
span,
"\"operation\" is mutually exclusive with the \"local\" option",
));
}
Ok(parsed_args) Ok(parsed_args)
} }
} }
...@@ -1111,7 +1083,6 @@ pub struct NativeFn { ...@@ -1111,7 +1083,6 @@ pub struct NativeFn {
/// Used only if `is_method` is true. /// Used only if `is_method` is true.
pub is_self_used: bool, pub is_self_used: bool,
pub filter_trait_call_args: Option<FilterTraitCallArgsTokens>, pub filter_trait_call_args: Option<FilterTraitCallArgsTokens>,
pub local: bool,
} }
impl NativeFn { impl NativeFn {
...@@ -1127,7 +1098,6 @@ impl NativeFn { ...@@ -1127,7 +1098,6 @@ impl NativeFn {
is_method, is_method,
is_self_used, is_self_used,
filter_trait_call_args, filter_trait_call_args,
local,
} = self; } = self;
if *is_method { if *is_method {
...@@ -1153,9 +1123,6 @@ impl NativeFn { ...@@ -1153,9 +1123,6 @@ impl NativeFn {
turbo_tasks::macro_helpers::NativeFunction::new_method( turbo_tasks::macro_helpers::NativeFunction::new_method(
#function_path_string, #function_path_string,
#function_global_name, #function_global_name,
turbo_tasks::macro_helpers::FunctionMeta {
local: #local,
},
#arg_filter, #arg_filter,
#function_path, #function_path,
) )
...@@ -1168,9 +1135,6 @@ impl NativeFn { ...@@ -1168,9 +1135,6 @@ impl NativeFn {
turbo_tasks::macro_helpers::NativeFunction::new_method_without_this( turbo_tasks::macro_helpers::NativeFunction::new_method_without_this(
#function_path_string, #function_path_string,
#function_global_name, #function_global_name,
turbo_tasks::macro_helpers::FunctionMeta {
local: #local,
},
#arg_filter, #arg_filter,
#function_path, #function_path,
) )
...@@ -1184,9 +1148,6 @@ impl NativeFn { ...@@ -1184,9 +1148,6 @@ impl NativeFn {
turbo_tasks::macro_helpers::NativeFunction::new_function( turbo_tasks::macro_helpers::NativeFunction::new_function(
#function_path_string, #function_path_string,
#function_global_name, #function_global_name,
turbo_tasks::macro_helpers::FunctionMeta {
local: #local,
},
#function_path, #function_path,
) )
} }
......
...@@ -41,7 +41,6 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -41,7 +41,6 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream {
let args = syn::parse::<FunctionArguments>(args) let args = syn::parse::<FunctionArguments>(args)
.inspect_err(|err| errors.push(err.to_compile_error())) .inspect_err(|err| errors.push(err.to_compile_error()))
.unwrap_or_default(); .unwrap_or_default();
let local = args.local.is_some();
let is_self_used = args.operation.is_some() || is_self_used(&block); let is_self_used = args.operation.is_some() || is_self_used(&block);
let Some(turbo_fn) = TurboFn::new(&sig, DefinitionContext::NakedFn, args) else { let Some(turbo_fn) = TurboFn::new(&sig, DefinitionContext::NakedFn, args) else {
...@@ -66,7 +65,6 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -66,7 +65,6 @@ pub fn function(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(), is_method: turbo_fn.is_method(),
is_self_used, is_self_used,
filter_trait_call_args: None, // not a trait method filter_trait_call_args: None, // not a trait method
local,
}; };
let native_function_ident = get_native_function_ident(ident); let native_function_ident = get_native_function_ident(ident);
let native_function_ty = native_fn.ty(); let native_function_ty = native_fn.ty();
......
...@@ -97,7 +97,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -97,7 +97,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
FunctionArguments::default() FunctionArguments::default()
} }
}; };
let local = func_args.local.is_some();
let is_self_used = func_args.operation.is_some() || is_self_used(block); let is_self_used = func_args.operation.is_some() || is_self_used(block);
let Some(turbo_fn) = let Some(turbo_fn) =
...@@ -120,7 +119,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -120,7 +119,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(), is_method: turbo_fn.is_method(),
is_self_used, is_self_used,
filter_trait_call_args: None, // not a trait method filter_trait_call_args: None, // not a trait method
local,
}; };
let native_function_ident = get_inherent_impl_function_ident(ty_ident, ident); let native_function_ident = get_inherent_impl_function_ident(ty_ident, ident);
...@@ -209,7 +207,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -209,7 +207,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
continue; continue;
} }
}; };
let local = func_args.local.is_some();
let is_self_used = func_args.operation.is_some() || is_self_used(block); let is_self_used = func_args.operation.is_some() || is_self_used(block);
let Some(turbo_fn) = let Some(turbo_fn) =
...@@ -246,7 +243,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -246,7 +243,6 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(), is_method: turbo_fn.is_method(),
is_self_used, is_self_used,
filter_trait_call_args: turbo_fn.filter_trait_call_args(), filter_trait_call_args: turbo_fn.filter_trait_call_args(),
local,
}; };
let native_function_ident = let native_function_ident =
......
...@@ -212,11 +212,6 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -212,11 +212,6 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
is_method: turbo_fn.is_method(), is_method: turbo_fn.is_method(),
is_self_used, is_self_used,
filter_trait_call_args: turbo_fn.filter_trait_call_args(), filter_trait_call_args: turbo_fn.filter_trait_call_args(),
// `local` is currently unsupported here because:
// - The `#[turbo_tasks::function]` macro needs to be present for us to read this
// argument. (This could be fixed)
// - This only makes sense when a default implementation is present.
local: false,
}; };
let native_function_ident = get_trait_default_impl_function_ident(trait_ident, ident); let native_function_ident = get_trait_default_impl_function_ident(trait_ident, ident);
......
...@@ -16,7 +16,7 @@ pub use crate::{ ...@@ -16,7 +16,7 @@ pub use crate::{
magic_any::MagicAny, magic_any::MagicAny,
manager::{find_cell_by_type, spawn_detached_for_testing}, manager::{find_cell_by_type, spawn_detached_for_testing},
native_function::{ native_function::{
CollectableFunction, FunctionMeta, NativeFunction, downcast_args_owned, downcast_args_ref, CollectableFunction, NativeFunction, downcast_args_owned, downcast_args_ref,
}, },
value_type::{CollectableTrait, CollectableValueType}, value_type::{CollectableTrait, CollectableValueType},
}; };
...@@ -32,7 +32,7 @@ pub async fn value_debug_format_field(value: ValueDebugFormatString<'_>) -> Stri ...@@ -32,7 +32,7 @@ pub async fn value_debug_format_field(value: ValueDebugFormatString<'_>) -> Stri
} }
} }
pub fn get_non_local_persistence_from_inputs(inputs: &impl TaskInput) -> TaskPersistence { pub fn get_persistence_from_inputs(inputs: &impl TaskInput) -> TaskPersistence {
if inputs.is_transient() { if inputs.is_transient() {
TaskPersistence::Transient TaskPersistence::Transient
} else { } else {
...@@ -40,7 +40,7 @@ pub fn get_non_local_persistence_from_inputs(inputs: &impl TaskInput) -> TaskPer ...@@ -40,7 +40,7 @@ pub fn get_non_local_persistence_from_inputs(inputs: &impl TaskInput) -> TaskPer
} }
} }
pub fn get_non_local_persistence_from_inputs_and_this( pub fn get_persistence_from_inputs_and_this(
this: RawVc, this: RawVc,
inputs: &impl TaskInput, inputs: &impl TaskInput,
) -> TaskPersistence { ) -> TaskPersistence {
......
...@@ -279,16 +279,6 @@ pub enum TaskPersistence { ...@@ -279,16 +279,6 @@ pub enum TaskPersistence {
/// type [`TransientValue`][crate::value::TransientValue] or /// type [`TransientValue`][crate::value::TransientValue] or
/// [`TransientInstance`][crate::value::TransientInstance]. /// [`TransientInstance`][crate::value::TransientInstance].
Transient, Transient,
/// Tasks that are persisted only for the lifetime of the nearest non-`Local` parent caller.
///
/// This task does not have a unique task id, and is not shared with the backend. Instead it
/// uses the parent task's id.
///
/// This is useful for functions that have a low cache hit rate. Those functions could be
/// converted to non-task functions, but that would break their function signature. This
/// provides a mechanism for skipping caching without changing the function signature.
Local,
} }
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)] #[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
...@@ -620,42 +610,23 @@ impl<B: Backend + 'static> TurboTasks<B> { ...@@ -620,42 +610,23 @@ impl<B: Backend + 'static> TurboTasks<B> {
arg: Box<dyn MagicAny>, arg: Box<dyn MagicAny>,
persistence: TaskPersistence, persistence: TaskPersistence,
) -> RawVc { ) -> RawVc {
match persistence { let task_type = CachedTaskType {
TaskPersistence::Local => { native_fn,
let task_type = LocalTaskSpec { this,
task_type: LocalTaskType::Native { native_fn }, arg,
this, };
arg, RawVc::TaskOutput(match persistence {
}; TaskPersistence::Transient => self.backend.get_or_create_transient_task(
self.schedule_local_task(task_type, persistence) task_type,
} current_task_if_available("turbo_function calls"),
TaskPersistence::Transient => { self,
let task_type = CachedTaskType { ),
native_fn, TaskPersistence::Persistent => self.backend.get_or_create_persistent_task(
this, task_type,
arg, current_task_if_available("turbo_function calls"),
}; self,
),
RawVc::TaskOutput(self.backend.get_or_create_transient_task( })
task_type,
current_task_if_available("turbo_function calls"),
self,
))
}
TaskPersistence::Persistent => {
let task_type = CachedTaskType {
native_fn,
this,
arg,
};
RawVc::TaskOutput(self.backend.get_or_create_persistent_task(
task_type,
current_task_if_available("turbo_function calls"),
self,
))
}
}
} }
pub fn dynamic_call( pub fn dynamic_call(
...@@ -794,12 +765,6 @@ impl<B: Backend + 'static> TurboTasks<B> { ...@@ -794,12 +765,6 @@ impl<B: Backend + 'static> TurboTasks<B> {
&self, &self,
ty: LocalTaskSpec, ty: LocalTaskSpec,
// if this is a `LocalTaskType::Resolve*`, we may spawn another task with this persistence, // if this is a `LocalTaskType::Resolve*`, we may spawn another task with this persistence,
// if this is a `LocalTaskType::Native`, persistence is unused.
//
// TODO: In the rare case that we're crossing a transient->persistent boundary, we should
// force `LocalTaskType::Native` to be spawned as real tasks, so that any cells they create
// have the correct persistence. This is not an issue for resolution stub task, as they
// don't end up owning any cells.
persistence: TaskPersistence, persistence: TaskPersistence,
) -> RawVc { ) -> RawVc {
let task_type = ty.task_type; let task_type = ty.task_type;
...@@ -830,24 +795,43 @@ impl<B: Backend + 'static> TurboTasks<B> { ...@@ -830,24 +795,43 @@ impl<B: Backend + 'static> TurboTasks<B> {
let this = self.pin(); let this = self.pin();
let future = async move { let future = async move {
let TaskExecutionSpec { future, span } = let span = match &ty.task_type {
crate::task::local_task::get_local_task_execution_spec(&*this, &ty, persistence); LocalTaskType::ResolveNative { native_fn } => native_fn.resolve_span(),
LocalTaskType::ResolveTrait { trait_method } => trait_method.resolve_span(),
};
async move { async move {
let result = CaptureFuture::new(future).await; let result = match ty.task_type {
LocalTaskType::ResolveNative { native_fn } => {
let result = match result { LocalTaskType::run_resolve_native(
Ok(Ok(raw_vc)) => Ok(raw_vc), native_fn,
Ok(Err(err)) => Err(err.into()), ty.this,
Err(err) => Err(TurboTasksExecutionError::Panic(Arc::new(err))), &*ty.arg,
persistence,
this,
)
.await
}
LocalTaskType::ResolveTrait { trait_method } => {
LocalTaskType::run_resolve_trait(
trait_method,
ty.this.unwrap(),
&*ty.arg,
persistence,
this,
)
.await
}
}; };
let local_task = LocalTask::Done { let output = match result {
output: match result { Ok(raw_vc) => OutputContent::Link(raw_vc),
Ok(raw_vc) => OutputContent::Link(raw_vc), Err(err) => OutputContent::Error(
Err(err) => OutputContent::Error(err.with_task_context(task_type)), TurboTasksExecutionError::from(err).with_task_context(task_type),
}, ),
}; };
let local_task = LocalTask::Done { output };
let done_event = CURRENT_TASK_STATE.with(move |gts| { let done_event = CURRENT_TASK_STATE.with(move |gts| {
let mut gts_write = gts.write().unwrap(); let mut gts_write = gts.write().unwrap();
let scheduled_task = let scheduled_task =
......
...@@ -142,22 +142,12 @@ pub fn downcast_args_ref<T: MagicAny>(args: &dyn MagicAny) -> &T { ...@@ -142,22 +142,12 @@ pub fn downcast_args_ref<T: MagicAny>(args: &dyn MagicAny) -> &T {
.unwrap() .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 /// A native (rust) turbo-tasks function. It's used internally by
/// `#[turbo_tasks::function]`. /// `#[turbo_tasks::function]`.
pub struct NativeFunction { pub struct NativeFunction {
/// A readable name of the function that is used to reporting purposes. /// A readable name of the function that is used to reporting purposes.
pub(crate) name: &'static str, pub(crate) name: &'static str,
pub(crate) function_meta: FunctionMeta,
pub(crate) arg_meta: ArgMeta, pub(crate) arg_meta: ArgMeta,
/// The functor that creates a functor from inputs. The inner functor /// The functor that creates a functor from inputs. The inner functor
...@@ -173,7 +163,6 @@ impl Debug for NativeFunction { ...@@ -173,7 +163,6 @@ impl Debug for NativeFunction {
f.debug_struct("NativeFunction") f.debug_struct("NativeFunction")
.field("name", &self.name) .field("name", &self.name)
.field("global_name", &self.global_name) .field("global_name", &self.global_name)
.field("function_meta", &self.function_meta)
.finish_non_exhaustive() .finish_non_exhaustive()
} }
} }
...@@ -182,7 +171,6 @@ impl NativeFunction { ...@@ -182,7 +171,6 @@ impl NativeFunction {
pub fn new_function<Mode, Inputs>( pub fn new_function<Mode, Inputs>(
name: &'static str, name: &'static str,
global_name: &'static str, global_name: &'static str,
function_meta: FunctionMeta,
implementation: impl IntoTaskFn<Mode, Inputs>, implementation: impl IntoTaskFn<Mode, Inputs>,
) -> Self ) -> Self
where where
...@@ -191,7 +179,6 @@ impl NativeFunction { ...@@ -191,7 +179,6 @@ impl NativeFunction {
Self { Self {
name, name,
global_name, global_name,
function_meta,
arg_meta: ArgMeta::new::<Inputs>(), arg_meta: ArgMeta::new::<Inputs>(),
implementation: Box::new(implementation.into_task_fn()), implementation: Box::new(implementation.into_task_fn()),
} }
...@@ -200,7 +187,6 @@ impl NativeFunction { ...@@ -200,7 +187,6 @@ impl NativeFunction {
pub fn new_method_without_this<Mode, Inputs, I>( pub fn new_method_without_this<Mode, Inputs, I>(
name: &'static str, name: &'static str,
global_name: &'static str, global_name: &'static str,
function_meta: FunctionMeta,
arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>, arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>,
implementation: I, implementation: I,
) -> Self ) -> Self
...@@ -211,7 +197,6 @@ impl NativeFunction { ...@@ -211,7 +197,6 @@ impl NativeFunction {
Self { Self {
name, name,
global_name, global_name,
function_meta,
arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter { arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter {
ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve) ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve)
} else { } else {
...@@ -224,7 +209,6 @@ impl NativeFunction { ...@@ -224,7 +209,6 @@ impl NativeFunction {
pub fn new_method<Mode, This, Inputs, I>( pub fn new_method<Mode, This, Inputs, I>(
name: &'static str, name: &'static str,
global_name: &'static str, global_name: &'static str,
function_meta: FunctionMeta,
arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>, arg_filter: Option<(FilterOwnedArgsFunctor, FilterAndResolveFunctor)>,
implementation: I, implementation: I,
) -> Self ) -> Self
...@@ -236,7 +220,6 @@ impl NativeFunction { ...@@ -236,7 +220,6 @@ impl NativeFunction {
Self { Self {
name, name,
global_name, global_name,
function_meta,
arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter { arg_meta: if let Some((filter_owned, filter_and_resolve)) = arg_filter {
ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve) ArgMeta::with_filter_trait_call::<Inputs>(filter_owned, filter_and_resolve)
} else { } else {
...@@ -258,7 +241,6 @@ impl NativeFunction { ...@@ -258,7 +241,6 @@ impl NativeFunction {
let flags = match persistence { let flags = match persistence {
TaskPersistence::Persistent => "", TaskPersistence::Persistent => "",
TaskPersistence::Transient => "transient", TaskPersistence::Transient => "transient",
TaskPersistence::Local => "local",
}; };
tracing::trace_span!( tracing::trace_span!(
"turbo_tasks::function", "turbo_tasks::function",
...@@ -268,13 +250,8 @@ impl NativeFunction { ...@@ -268,13 +250,8 @@ impl NativeFunction {
) )
} }
pub fn resolve_span(&'static self, persistence: TaskPersistence) -> Span { pub fn resolve_span(&'static self) -> Span {
let flags = match persistence { tracing::trace_span!("turbo_tasks::resolve_call", name = self.name)
TaskPersistence::Persistent => "",
TaskPersistence::Transient => "transient",
TaskPersistence::Local => "local",
};
tracing::trace_span!("turbo_tasks::resolve_call", name = self.name, flags = flags)
} }
} }
impl PartialEq for NativeFunction { impl PartialEq for NativeFunction {
......
...@@ -241,16 +241,18 @@ impl RawVc { ...@@ -241,16 +241,18 @@ impl RawVc {
/// Convert a potentially local `RawVc` into a non-local `RawVc`. This is a subset of resolution /// Convert a potentially local `RawVc` into a non-local `RawVc`. This is a subset of resolution
/// resolution, because the returned `RawVc` can be a `TaskOutput`. /// resolution, because the returned `RawVc` can be a `TaskOutput`.
pub(crate) async fn to_non_local(self) -> Result<RawVc> { pub(crate) async fn to_non_local(self) -> Result<RawVc> {
let tt = turbo_tasks(); Ok(match self {
let mut current = self; RawVc::LocalOutput(execution_id, local_task_id, ..) => {
loop { let tt = turbo_tasks();
match current { let local_output = read_local_output(&*tt, execution_id, local_task_id).await?;
RawVc::LocalOutput(execution_id, local_task_id, ..) => { debug_assert!(
current = read_local_output(&*tt, execution_id, local_task_id).await?; !matches!(local_output, RawVc::LocalOutput(_, _, _)),
} "a LocalOutput cannot point at other LocalOutputs"
non_local => return Ok(non_local), );
local_output
} }
} non_local => non_local,
})
} }
pub(crate) fn connect(&self) { pub(crate) fn connect(&self) {
......
...@@ -186,10 +186,6 @@ fn get_args<T: MagicAny + Clone>(arg: &dyn MagicAny) -> Result<T> { ...@@ -186,10 +186,6 @@ fn get_args<T: MagicAny + Clone>(arg: &dyn MagicAny) -> Result<T> {
// Helper function for `task_fn_impl!()` // Helper function for `task_fn_impl!()`
async fn output_try_into_non_local_raw_vc(output: impl TaskOutput) -> Result<RawVc> { async fn output_try_into_non_local_raw_vc(output: impl TaskOutput) -> Result<RawVc> {
// TODO: Potential future optimization: If we know we're inside a local task, we can avoid
// calling `to_non_local()` here, which might let us avoid constructing a non-local cell for the
// local task's return value. Flattening chains of `RawVc::LocalOutput` may still be useful to
// reduce traversal later.
output.try_into_raw_vc()?.to_non_local().await output.try_into_raw_vc()?.to_non_local().await
} }
......
...@@ -3,9 +3,9 @@ use std::{fmt, sync::Arc}; ...@@ -3,9 +3,9 @@ use std::{fmt, sync::Arc};
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use crate::{ use crate::{
MagicAny, OutputContent, RawVc, TaskExecutionReason, TaskPersistence, TraitMethod, MagicAny, OutputContent, RawVc, TaskPersistence, TraitMethod, TurboTasksBackendApi,
TurboTasksBackendApi, ValueTypeId, ValueTypeId,
backend::{Backend, TaskExecutionSpec, TypedCellContent}, backend::{Backend, TypedCellContent},
event::Event, event::Event,
macro_helpers::NativeFunction, macro_helpers::NativeFunction,
registry, registry,
...@@ -17,50 +17,6 @@ pub enum LocalTask { ...@@ -17,50 +17,6 @@ pub enum LocalTask {
Done { output: OutputContent }, Done { output: OutputContent },
} }
pub fn get_local_task_execution_spec<'a>(
turbo_tasks: &'_ dyn TurboTasksBackendApi<impl Backend + 'static>,
ty: &'a LocalTaskSpec,
// if this is a `LocalTaskType::Resolve*`, we'll spawn another task with this persistence, if
// this is a `LocalTaskType::Native`, this refers to the parent non-local task.
persistence: TaskPersistence,
) -> TaskExecutionSpec<'a> {
match ty.task_type {
LocalTaskType::Native { native_fn } => {
let span = native_fn.span(TaskPersistence::Local, TaskExecutionReason::Local);
let entered = span.enter();
let future = native_fn.execute(ty.this, &*ty.arg);
drop(entered);
TaskExecutionSpec { future, span }
}
LocalTaskType::ResolveNative { native_fn } => {
let span = native_fn.resolve_span(TaskPersistence::Local);
let entered = span.enter();
let future = Box::pin(LocalTaskType::run_resolve_native(
native_fn,
ty.this,
&*ty.arg,
persistence,
turbo_tasks.pin(),
));
drop(entered);
TaskExecutionSpec { future, span }
}
LocalTaskType::ResolveTrait { trait_method } => {
let span = trait_method.resolve_span();
let entered = span.enter();
let future = Box::pin(LocalTaskType::run_resolve_trait(
trait_method,
ty.this.unwrap(),
&*ty.arg,
persistence,
turbo_tasks.pin(),
));
drop(entered);
TaskExecutionSpec { future, span }
}
}
}
pub struct LocalTaskSpec { pub struct LocalTaskSpec {
/// The self value, will always be present for `ResolveTrait` tasks and is optional otherwise /// The self value, will always be present for `ResolveTrait` tasks and is optional otherwise
pub(crate) this: Option<RawVc>, pub(crate) this: Option<RawVc>,
...@@ -71,11 +27,8 @@ pub struct LocalTaskSpec { ...@@ -71,11 +27,8 @@ pub struct LocalTaskSpec {
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub enum LocalTaskType { pub enum LocalTaskType {
/// A normal task execution a native (rust) function
Native { native_fn: &'static NativeFunction },
/// A resolve task, which resolves arguments and calls the function with resolve arguments. The /// A resolve task, which resolves arguments and calls the function with resolve arguments. The
/// inner function call will be a `PersistentTaskType` or `LocalTaskType::Native`. /// inner function call will be a `PersistentTaskType`.
ResolveNative { native_fn: &'static NativeFunction }, ResolveNative { native_fn: &'static NativeFunction },
/// A trait method resolve task. It resolves the first (`self`) argument and looks up the trait /// A trait method resolve task. It resolves the first (`self`) argument and looks up the trait
...@@ -87,7 +40,6 @@ pub enum LocalTaskType { ...@@ -87,7 +40,6 @@ pub enum LocalTaskType {
impl fmt::Display for LocalTaskType { impl fmt::Display for LocalTaskType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
LocalTaskType::Native { native_fn } => f.write_str(native_fn.name),
LocalTaskType::ResolveNative { native_fn } => write!(f, "*{}", native_fn.name), LocalTaskType::ResolveNative { native_fn } => write!(f, "*{}", native_fn.name),
LocalTaskType::ResolveTrait { trait_method } => write!( LocalTaskType::ResolveTrait { trait_method } => write!(
f, f,
...@@ -101,7 +53,7 @@ impl fmt::Display for LocalTaskType { ...@@ -101,7 +53,7 @@ impl fmt::Display for LocalTaskType {
impl LocalTaskType { impl LocalTaskType {
/// Implementation of the LocalTaskType::ResolveNative task. /// Implementation of the LocalTaskType::ResolveNative task.
/// Resolves all the task inputs and then calls the given function. /// Resolves all the task inputs and then calls the given function.
async fn run_resolve_native<B: Backend + 'static>( pub(crate) async fn run_resolve_native<B: Backend + 'static>(
native_fn: &'static NativeFunction, native_fn: &'static NativeFunction,
mut this: Option<RawVc>, mut this: Option<RawVc>,
arg: &dyn MagicAny, arg: &dyn MagicAny,
...@@ -115,7 +67,7 @@ impl LocalTaskType { ...@@ -115,7 +67,7 @@ impl LocalTaskType {
Ok(turbo_tasks.native_call(native_fn, this, arg, persistence)) Ok(turbo_tasks.native_call(native_fn, this, arg, persistence))
} }
/// Implementation of the LocalTaskType::ResolveTrait task. /// Implementation of the LocalTaskType::ResolveTrait task.
async fn run_resolve_trait<B: Backend + 'static>( pub(crate) async fn run_resolve_trait<B: Backend + 'static>(
trait_method: &'static TraitMethod, trait_method: &'static TraitMethod,
this: RawVc, this: RawVc,
arg: &dyn MagicAny, arg: &dyn MagicAny,
...@@ -164,11 +116,11 @@ pub(crate) mod tests { ...@@ -164,11 +116,11 @@ pub(crate) mod tests {
#[test] #[test]
fn test_fmt() { fn test_fmt() {
assert_eq!( assert_eq!(
LocalTaskType::Native { LocalTaskType::ResolveNative {
native_fn: &MOCK_FUNC_TASK_FUNCTION, native_fn: &MOCK_FUNC_TASK_FUNCTION,
} }
.to_string(), .to_string(),
"mock_func_task", "*mock_func_task",
); );
assert_eq!( assert_eq!(
LocalTaskType::ResolveTrait { LocalTaskType::ResolveTrait {
......
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