Unverified Commit 1a62326f authored by Benjamin Woodruff's avatar Benjamin Woodruff Committed by GitHub

refactor(turbo-tasks): Introduce a OperationValue trait, generalized from the…

refactor(turbo-tasks): Introduce a OperationValue trait, generalized from the ResolvedValue trait (#72788)

Based on some discussion I had with @sokra, we determined that we should enforce that [`State<T>` types](https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/struct.State.html) should not contain `Vc` or `ResolvedVc`, and should only contain `OperationVc`.

This lays the groundwork for enforcing this using the type system by generalizing the logic I already had for the [`ResolvedValue`](https://turbopack-rust-docs.vercel.sh/rustdoc/turbo_tasks/trait.ResolvedValue.html) marker trait. We'll also probably want to follow this up with a PR that renames `ResolvedValue` to something like `NonLocalValue` and allow it to contain `OperationVc` as well. An `OperationVc` should be valid in a `#[turbo_tasks::value]`, we only care that there's sane equality and that there's no potentially-local `Vc` in there (`OperationVc` is not local).
parent affbe743
...@@ -16,6 +16,8 @@ pub struct ValueTraitArguments { ...@@ -16,6 +16,8 @@ pub struct ValueTraitArguments {
/// ///
/// `Some(...)` if enabled, containing the span that enabled the constraint. /// `Some(...)` if enabled, containing the span that enabled the constraint.
pub resolved: Option<Span>, pub resolved: Option<Span>,
/// Should the trait have a `turbo_tasks::OperationValue` constraint?
pub operation: Option<Span>,
} }
impl Default for ValueTraitArguments { impl Default for ValueTraitArguments {
...@@ -23,6 +25,7 @@ impl Default for ValueTraitArguments { ...@@ -23,6 +25,7 @@ impl Default for ValueTraitArguments {
Self { Self {
debug: true, debug: true,
resolved: None, resolved: None,
operation: None,
} }
} }
} }
...@@ -43,6 +46,9 @@ impl Parse for ValueTraitArguments { ...@@ -43,6 +46,9 @@ impl Parse for ValueTraitArguments {
Some("resolved") => { Some("resolved") => {
result.resolved = Some(meta.span()); result.resolved = Some(meta.span());
} }
Some("operation") => {
result.operation = Some(meta.span());
}
_ => { _ => {
return Err(syn::Error::new_spanned(meta, "unknown parameter")); return Err(syn::Error::new_spanned(meta, "unknown parameter"));
} }
......
#![allow(dead_code)]
use turbo_tasks::{OperationValue, ResolvedVc, Vc};
#[derive(OperationValue)]
struct ContainsVcAndResolvedVc {
a: Vc<i32>,
b: ResolvedVc<i32>,
}
fn main() {}
error[E0277]: the trait bound `Vc<i32>: OperationValue` is not satisfied
--> tests/derive_operation_value/fail_contains_vc_and_resolved_vc.rs:7:8
|
7 | a: Vc<i32>,
| ^^^^^^^ the trait `OperationValue` is not implemented for `Vc<i32>`
|
= help: the following other types implement trait `OperationValue`:
&T
&mut T
()
(A, Z, Y, X, W, V, U, T)
(B, A, Z, Y, X, W, V, U, T)
(C, B, A, Z, Y, X, W, V, U, T)
(D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others
note: required by a bound in `DeriveOperationValueAssertion::assert_impl_OperationValue`
--> tests/derive_operation_value/fail_contains_vc_and_resolved_vc.rs:5:10
|
5 | #[derive(OperationValue)]
| ^^^^^^^^^^^^^^ required by this bound in `DeriveOperationValueAssertion::assert_impl_OperationValue`
= note: this error originates in the derive macro `OperationValue` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0277]: the trait bound `ResolvedVc<i32>: OperationValue` is not satisfied
--> tests/derive_operation_value/fail_contains_vc_and_resolved_vc.rs:8:8
|
8 | b: ResolvedVc<i32>,
| ^^^^^^^^^^^^^^^ the trait `OperationValue` is not implemented for `ResolvedVc<i32>`
|
= help: the following other types implement trait `OperationValue`:
&T
&mut T
()
(A, Z, Y, X, W, V, U, T)
(B, A, Z, Y, X, W, V, U, T)
(C, B, A, Z, Y, X, W, V, U, T)
(D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others
note: required by a bound in `DeriveOperationValueAssertion::assert_impl_OperationValue`
--> tests/derive_operation_value/fail_contains_vc_and_resolved_vc.rs:5:10
|
5 | #[derive(OperationValue)]
| ^^^^^^^^^^^^^^ required by this bound in `DeriveOperationValueAssertion::assert_impl_OperationValue`
= note: this error originates in the derive macro `OperationValue` (in Nightly builds, run with -Z macro-backtrace for more info)
#![allow(dead_code)]
use turbo_tasks::{OperationValue, OperationVc};
#[derive(OperationValue)]
struct UnitStruct;
#[derive(OperationValue)]
struct ContainsOperationVcNamed {
a: i32,
b: OperationVc<i32>,
c: Vec<OperationVc<i32>>,
}
#[derive(OperationValue)]
struct ContainsOperationVcUnnamed(i32, OperationVc<i32>, Vec<OperationVc<i32>>);
fn main() {}
...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied ...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_contains_only_vc.rs:5:10 --> tests/derive_resolved_value/fail_contains_only_vc.rs:5:10
| |
5 | #[derive(ResolvedValue)] 5 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied ...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_contains_resolved_vc_and_vc.rs:5:10 --> tests/derive_resolved_value/fail_contains_resolved_vc_and_vc.rs:5:10
| |
5 | #[derive(ResolvedValue)] 5 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -17,9 +17,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied ...@@ -17,9 +17,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied
= note: required for `[Vc<i32>; 4]` to implement `ResolvedValue` = note: required for `[Vc<i32>; 4]` to implement `ResolvedValue`
= note: 2 redundant requirements hidden = note: 2 redundant requirements hidden
= note: required for `std::option::Option<Box<[Vc<i32>; 4]>>` to implement `ResolvedValue` = note: required for `std::option::Option<Box<[Vc<i32>; 4]>>` to implement `ResolvedValue`
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_contains_vc_inside_generic.rs:5:10 --> tests/derive_resolved_value/fail_contains_vc_inside_generic.rs:5:10
| |
5 | #[derive(ResolvedValue)] 5 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -14,11 +14,11 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied ...@@ -14,11 +14,11 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_simple_enum.rs:7:10 --> tests/derive_resolved_value/fail_simple_enum.rs:7:10
| |
7 | #[derive(ResolvedValue)] 7 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied
...@@ -37,9 +37,9 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied ...@@ -37,9 +37,9 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_simple_enum.rs:7:10 --> tests/derive_resolved_value/fail_simple_enum.rs:7:10
| |
7 | #[derive(ResolvedValue)] 7 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied ...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_simple_named_struct.rs:7:10 --> tests/derive_resolved_value/fail_simple_named_struct.rs:7:10
| |
7 | #[derive(ResolvedValue)] 7 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied ...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `UnresolvedValue: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_simple_unnamed_struct.rs:7:10 --> tests/derive_resolved_value/fail_simple_unnamed_struct.rs:7:10
| |
7 | #[derive(ResolvedValue)] 7 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
...@@ -4,11 +4,11 @@ error[E0277]: the trait bound `T: ResolvedValue` is not satisfied ...@@ -4,11 +4,11 @@ error[E0277]: the trait bound `T: ResolvedValue` is not satisfied
7 | value: T, 7 | value: T,
| ^ the trait `ResolvedValue` is not implemented for `T` | ^ the trait `ResolvedValue` is not implemented for `T`
| |
note: required by a bound in `DeriveResolvedValueAssertion::<T>::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::<T>::assert_impl_ResolvedValue`
--> tests/derive_resolved_value/fail_underconstrained_generic.rs:5:10 --> tests/derive_resolved_value/fail_underconstrained_generic.rs:5:10
| |
5 | #[derive(ResolvedValue)] 5 | #[derive(ResolvedValue)]
| ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::<T>::assert_impl_resolved_value` | ^^^^^^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::<T>::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider restricting type parameter `T` help: consider restricting type parameter `T`
| |
......
#[test]
fn derive_operation_value() {
let t = trybuild::TestCases::new();
t.pass("tests/derive_operation_value/pass_*.rs");
t.compile_fail("tests/derive_operation_value/fail_*.rs");
}
#[test] #[test]
fn derive_resolved_value() { fn derive_resolved_value() {
let t = trybuild::TestCases::new(); let t = trybuild::TestCases::new();
......
...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied ...@@ -14,9 +14,9 @@ error[E0277]: the trait bound `Vc<i32>: ResolvedValue` is not satisfied
(D, C, B, A, Z, Y, X, W, V, U, T) (D, C, B, A, Z, Y, X, W, V, U, T)
(E, D, C, B, A, Z, Y, X, W, V, U, T) (E, D, C, B, A, Z, Y, X, W, V, U, T)
and $N others and $N others
note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` note: required by a bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
--> tests/value/fail_resolved.rs:6:22 --> tests/value/fail_resolved.rs:6:22
| |
6 | #[turbo_tasks::value(resolved)] 6 | #[turbo_tasks::value(resolved)]
| ^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_resolved_value` | ^^^^^^^^ required by this bound in `DeriveResolvedValueAssertion::assert_impl_ResolvedValue`
= note: this error originates in the derive macro `turbo_tasks::ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info) = note: this error originates in the derive macro `turbo_tasks::ResolvedValue` (in Nightly builds, run with -Z macro-backtrace for more info)
use either::Either;
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::{spanned::Spanned, Data, Field, Generics, Ident, Path};
/// Generates tokens for a [`syn::ItemConst`] that asserts every field on the struct, enum, or union
/// (represented by [`Data`]) is an instance of `trait_path`.
///
/// A filter function can be passed to filter out fields, such as those with certain
/// [`Attribute`][syn::Attribute]s.
///
/// This uses a technique based on the trick used by
/// [`static_assertions::assert_impl_all`][assert_impl_all], but extended to support generics.
///
/// [assert_impl_all]: https://docs.rs/static_assertions/latest/static_assertions/macro.assert_impl_all.html
pub fn assert_fields_impl_trait(
trait_path: &Path,
generics: &Generics,
data: &Data,
mut filter_field: impl FnMut(&Field) -> bool,
) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let field_types = iter_data_fields(data).map(|field| &field.ty);
// generate internal identifiers (shown in error messages) from the trait name
let trait_name = trait_path.segments.last().unwrap().ident.to_string();
let assertion_struct_ident =
Ident::new(&format!("Derive{trait_name}Assertion"), Span::mixed_site());
let assertion_fn_ident = Ident::new(&format!("assert_impl_{trait_name}"), Span::mixed_site());
let assertion_calls = iter_data_fields(data)
.filter(|field| filter_field(field))
.map(|field| {
let ty = &field.ty;
quote_spanned! {
// attribute type assertion errors to the line where the field is defined
ty.span() =>
// this call is only valid if ty is a ResolvedValue
Self::#assertion_fn_ident::<#ty>();
}
});
quote! {
const _: fn() = || {
// create this struct just to hold onto our generics...
// we reproduce the field types here to ensure any generics get used
struct #assertion_struct_ident #impl_generics (#(#field_types),*) #where_clause;
impl #impl_generics #assertion_struct_ident #ty_generics #where_clause {
fn #assertion_fn_ident<
Expected: #trait_path + ?Sized
>() {}
#[allow(non_snake_case)]
fn field_types() {
#(#assertion_calls)*
}
}
};
}
}
fn iter_data_fields(data: &Data) -> impl Iterator<Item = &syn::Field> {
match data {
Data::Struct(ds) => Either::Left(ds.fields.iter()),
Data::Enum(de) => Either::Right(Either::Left(de.variants.iter().flat_map(|v| &v.fields))),
Data::Union(du) => Either::Right(Either::Right(du.fields.named.iter())),
}
}
mod deterministic_hash_macro; mod deterministic_hash_macro;
mod key_value_pair_macro; mod key_value_pair_macro;
mod operation_value_macro;
mod resolved_value_macro; mod resolved_value_macro;
mod shrink_to_fit_macro; mod shrink_to_fit_macro;
mod task_input_macro; mod task_input_macro;
...@@ -9,6 +10,7 @@ mod value_debug_macro; ...@@ -9,6 +10,7 @@ mod value_debug_macro;
pub use deterministic_hash_macro::derive_deterministic_hash; pub use deterministic_hash_macro::derive_deterministic_hash;
pub use key_value_pair_macro::derive_key_value_pair; pub use key_value_pair_macro::derive_key_value_pair;
pub use operation_value_macro::derive_operation_value;
pub use resolved_value_macro::derive_resolved_value; pub use resolved_value_macro::derive_resolved_value;
pub use shrink_to_fit_macro::derive_shrink_to_fit; pub use shrink_to_fit_macro::derive_shrink_to_fit;
use syn::{spanned::Spanned, Attribute, Meta, MetaList, NestedMeta}; use syn::{spanned::Spanned, Attribute, Meta, MetaList, NestedMeta};
......
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, DeriveInput};
use crate::{assert_fields::assert_fields_impl_trait, derive::trace_raw_vcs_macro::filter_field};
pub fn derive_operation_value(input: TokenStream) -> TokenStream {
let derive_input = parse_macro_input!(input as DeriveInput);
let ident = &derive_input.ident;
let assertions = assert_fields_impl_trait(
&parse_quote!(turbo_tasks::OperationValue),
&derive_input.generics,
&derive_input.data,
filter_field,
);
let (impl_generics, ty_generics, where_clause) = derive_input.generics.split_for_impl();
quote! {
unsafe impl #impl_generics turbo_tasks::OperationValue
for #ident #ty_generics #where_clause {}
#assertions
}
.into()
}
use either::Either;
use proc_macro::TokenStream; use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2; use quote::quote;
use quote::{quote, quote_spanned}; use syn::{parse_macro_input, parse_quote, DeriveInput};
use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput, Generics};
use crate::derive::trace_raw_vcs_macro::filter_field; use crate::{assert_fields::assert_fields_impl_trait, derive::trace_raw_vcs_macro::filter_field};
pub fn derive_resolved_value(input: TokenStream) -> TokenStream { pub fn derive_resolved_value(input: TokenStream) -> TokenStream {
let derive_input = parse_macro_input!(input as DeriveInput); let derive_input = parse_macro_input!(input as DeriveInput);
let ident = &derive_input.ident; let ident = &derive_input.ident;
let assertions = assert_fields_impl_resolved_value(&derive_input.generics, &derive_input.data); let assertions = assert_fields_impl_trait(
&parse_quote!(turbo_tasks::ResolvedValue),
&derive_input.generics,
&derive_input.data,
filter_field,
);
let (impl_generics, ty_generics, where_clause) = derive_input.generics.split_for_impl(); let (impl_generics, ty_generics, where_clause) = derive_input.generics.split_for_impl();
quote! { quote! {
...@@ -20,45 +23,3 @@ pub fn derive_resolved_value(input: TokenStream) -> TokenStream { ...@@ -20,45 +23,3 @@ pub fn derive_resolved_value(input: TokenStream) -> TokenStream {
} }
.into() .into()
} }
fn iter_data_fields(data: &Data) -> impl Iterator<Item = &syn::Field> {
match data {
Data::Struct(ds) => Either::Left(ds.fields.iter()),
Data::Enum(de) => Either::Right(Either::Left(de.variants.iter().flat_map(|v| &v.fields))),
Data::Union(du) => Either::Right(Either::Right(du.fields.named.iter())),
}
}
fn assert_fields_impl_resolved_value(generics: &Generics, data: &Data) -> TokenStream2 {
// this technique is based on the trick used by
// `static_assertions::assert_impl_all`, but extended to support generics.
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let field_types = iter_data_fields(data).map(|field| &field.ty);
let assertion_calls = iter_data_fields(data)
.filter(|field| filter_field(field))
.map(|field| {
let ty = &field.ty;
quote_spanned! {
// attribute type assertion errors to the line where the field is defined
ty.span() =>
// this call is only valid if ty is a ResolvedValue
Self::assert_impl_resolved_value::<#ty>();
}
});
quote! {
const _: fn() = || {
// create this struct just to hold onto our generics...
// we reproduce the field types here to ensure any generics get used
struct DeriveResolvedValueAssertion #impl_generics (#(#field_types),*) #where_clause;
impl #impl_generics DeriveResolvedValueAssertion #ty_generics #where_clause {
fn assert_impl_resolved_value<
ExpectedResolvedValue: turbo_tasks::ResolvedValue + ?Sized
>() {}
fn field_types() {
#(#assertion_calls)*
}
}
};
}
}
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
#![feature(allow_internal_unstable)] #![feature(allow_internal_unstable)]
#![feature(box_patterns)] #![feature(box_patterns)]
mod assert_fields;
mod derive; mod derive;
mod func; mod func;
mod function_macro; mod function_macro;
...@@ -32,6 +33,11 @@ pub fn derive_resolved_value_attr(input: TokenStream) -> TokenStream { ...@@ -32,6 +33,11 @@ pub fn derive_resolved_value_attr(input: TokenStream) -> TokenStream {
derive::derive_resolved_value(input) derive::derive_resolved_value(input)
} }
#[proc_macro_derive(OperationValue, attributes(turbo_tasks))]
pub fn derive_operation_value_attr(input: TokenStream) -> TokenStream {
derive::derive_operation_value(input)
}
#[proc_macro_derive(ValueDebug, attributes(turbo_tasks))] #[proc_macro_derive(ValueDebug, attributes(turbo_tasks))]
pub fn derive_value_debug_attr(input: TokenStream) -> TokenStream { pub fn derive_value_debug_attr(input: TokenStream) -> TokenStream {
derive::derive_value_debug(input) derive::derive_value_debug(input)
......
...@@ -114,6 +114,8 @@ struct ValueArguments { ...@@ -114,6 +114,8 @@ struct ValueArguments {
/// ///
/// `Some(...)` if enabled, containing the span that enabled the derive. /// `Some(...)` if enabled, containing the span that enabled the derive.
resolved: Option<Span>, resolved: Option<Span>,
/// Should we `#[derive(turbo_tasks::OperationValue)]`?
operation: Option<Span>,
} }
impl Parse for ValueArguments { impl Parse for ValueArguments {
...@@ -123,8 +125,9 @@ impl Parse for ValueArguments { ...@@ -123,8 +125,9 @@ impl Parse for ValueArguments {
into_mode: IntoMode::None, into_mode: IntoMode::None,
cell_mode: CellMode::Shared, cell_mode: CellMode::Shared,
manual_eq: false, manual_eq: false,
resolved: None,
transparent: false, transparent: false,
resolved: None,
operation: None,
}; };
let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?; let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?;
for meta in punctuated { for meta in punctuated {
...@@ -182,12 +185,15 @@ impl Parse for ValueArguments { ...@@ -182,12 +185,15 @@ impl Parse for ValueArguments {
("resolved", Meta::Path(path)) => { ("resolved", Meta::Path(path)) => {
result.resolved = Some(path.span()); result.resolved = Some(path.span());
} }
("operation", Meta::Path(path)) => {
result.operation = Some(path.span());
}
(_, meta) => { (_, meta) => {
return Err(Error::new_spanned( return Err(Error::new_spanned(
&meta, &meta,
format!( format!(
"unexpected {:?}, expected \"shared\", \"into\", \"serialization\", \ "unexpected {:?}, expected \"shared\", \"into\", \"serialization\", \
\"cell\", \"eq\", \"transparent\"", \"cell\", \"eq\", \"transparent\", \"resolved\", or \"operation\"",
meta meta
), ),
)) ))
...@@ -208,6 +214,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -208,6 +214,7 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
manual_eq, manual_eq,
transparent, transparent,
resolved, resolved,
operation,
} = parse_macro_input!(args as ValueArguments); } = parse_macro_input!(args as ValueArguments);
let mut inner_type = None; let mut inner_type = None;
...@@ -389,6 +396,12 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -389,6 +396,12 @@ pub fn value(args: TokenStream, input: TokenStream) -> TokenStream {
#[derive(turbo_tasks::ResolvedValue)] #[derive(turbo_tasks::ResolvedValue)]
}); });
} }
if let Some(span) = operation {
struct_attributes.push(quote_spanned! {
span =>
#[derive(turbo_tasks::OperationValue)]
});
}
let new_value_type = match serialization_mode { let new_value_type = match serialization_mode {
SerializationMode::None => quote! { SerializationMode::None => quote! {
......
...@@ -12,7 +12,11 @@ use turbo_tasks_macros_shared::{ ...@@ -12,7 +12,11 @@ use turbo_tasks_macros_shared::{
use crate::func::{DefinitionContext, FunctionArguments, NativeFn, TurboFn}; use crate::func::{DefinitionContext, FunctionArguments, NativeFn, TurboFn};
pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
let ValueTraitArguments { debug, resolved } = parse_macro_input!(args as ValueTraitArguments); let ValueTraitArguments {
debug,
resolved,
operation,
} = parse_macro_input!(args as ValueTraitArguments);
let item = parse_macro_input!(input as ItemTrait); let item = parse_macro_input!(input as ItemTrait);
...@@ -195,14 +199,17 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -195,14 +199,17 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
quote! {} quote! {}
}; };
let mut extended_supertraits = Vec::new(); let mut extended_supertraits = vec![quote!(::std::marker::Send), quote!(::std::marker::Sync)];
if let Some(span) = resolved { if let Some(span) = resolved {
extended_supertraits.push(quote_spanned! { extended_supertraits.push(quote_spanned! {
span => turbo_tasks::ResolvedValue span => turbo_tasks::ResolvedValue
}); });
} }
extended_supertraits.push(quote!(::std::marker::Send)); if let Some(span) = operation {
extended_supertraits.push(quote!(::std::marker::Sync)); extended_supertraits.push(quote_spanned! {
span => turbo_tasks::OperationValue
});
}
if debug { if debug {
extended_supertraits.push(quote!(turbo_tasks::debug::ValueDebug)); extended_supertraits.push(quote!(turbo_tasks::debug::ValueDebug));
} }
......
...@@ -55,6 +55,7 @@ mod key_value_pair; ...@@ -55,6 +55,7 @@ mod key_value_pair;
pub mod macro_helpers; pub mod macro_helpers;
mod magic_any; mod magic_any;
mod manager; mod manager;
mod marker_trait;
mod native_function; mod native_function;
mod no_move_vec; mod no_move_vec;
mod once_map; mod once_map;
...@@ -120,9 +121,9 @@ pub use turbo_tasks_macros::{function, value_impl, value_trait, KeyValuePair, Ta ...@@ -120,9 +121,9 @@ pub use turbo_tasks_macros::{function, value_impl, value_trait, KeyValuePair, Ta
pub use value::{TransientInstance, TransientValue, Value}; pub use value::{TransientInstance, TransientValue, Value};
pub use value_type::{TraitMethod, TraitType, ValueType}; pub use value_type::{TraitMethod, TraitType, ValueType};
pub use vc::{ pub use vc::{
Dynamic, OperationVc, ResolvedValue, ResolvedVc, TypedForInput, Upcast, ValueDefault, Vc, Dynamic, OperationValue, OperationVc, ResolvedValue, ResolvedVc, TypedForInput, Upcast,
VcCast, VcCellNewMode, VcCellSharedMode, VcDefaultRead, VcRead, VcTransparentRead, ValueDefault, Vc, VcCast, VcCellNewMode, VcCellSharedMode, VcDefaultRead, VcRead,
VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast, VcTransparentRead, VcValueTrait, VcValueTraitCast, VcValueType, VcValueTypeCast,
}; };
pub type FxIndexSet<T> = indexmap::IndexSet<T, BuildHasherDefault<FxHasher>>; pub type FxIndexSet<T> = indexmap::IndexSet<T, BuildHasherDefault<FxHasher>>;
......
/// Creates an empty trait implementation for all common types. For generic collections, a bound is
/// added that any type parameters implement the trait.
///
/// This requires that `$trait` is a marker trait, as no associated types or methods will be
/// implemented.
///
/// These marker traits should also include a derive proc-macro in `turbo-tasks-macros` to allow
/// easy implementation on structs or enums.
///
/// This should eventually be replace by the `auto_traits`, once stabilized:
/// https://doc.rust-lang.org/nightly/unstable-book/language-features/auto-traits.html
macro_rules! impl_auto_marker_trait {
($trait:ident) => {
$crate::marker_trait::impl_marker_trait!(
$trait: i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, char, bool, usize,
);
$crate::marker_trait::impl_marker_trait!(
$trait:
::std::sync::atomic::AtomicI8,
::std::sync::atomic::AtomicU8,
::std::sync::atomic::AtomicI16,
::std::sync::atomic::AtomicU16,
::std::sync::atomic::AtomicI32,
::std::sync::atomic::AtomicU32,
::std::sync::atomic::AtomicI64,
::std::sync::atomic::AtomicU64,
::std::sync::atomic::AtomicBool,
::std::sync::atomic::AtomicUsize,
);
$crate::marker_trait::impl_marker_trait!(
$trait:
(),
str,
::std::string::String,
::std::time::Duration,
::anyhow::Error,
::turbo_rcstr::RcStr,
);
$crate::marker_trait::impl_marker_trait!($trait: ::std::path::Path, ::std::path::PathBuf);
$crate::marker_trait::impl_marker_trait!($trait: ::serde_json::Value);
$crate::marker_trait::impl_marker_trait_tuple!($trait: E D C B A Z Y X W V U T);
unsafe impl<T: $trait> $trait for ::std::option::Option<T> {}
unsafe impl<T: $trait> $trait for ::std::vec::Vec<T> {}
unsafe impl<T: $trait, const N: usize> $trait for [T; N] {}
unsafe impl<T: $trait> $trait for [T] {}
unsafe impl<T: $trait, S> $trait for ::std::collections::HashSet<T, S> {}
unsafe impl<T: $trait, S, const I: usize> $trait for ::auto_hash_map::AutoSet<T, S, I> {}
unsafe impl<T: $trait> $trait for ::std::collections::BTreeSet<T> {}
unsafe impl<T: $trait, S> $trait for ::indexmap::IndexSet<T, S> {}
unsafe impl<K: $trait, V: $trait, S> $trait for ::std::collections::HashMap<K, V, S> {}
unsafe impl<K: $trait, V: $trait, S, const I: usize> $trait
for ::auto_hash_map::AutoMap<K, V, S, I> {}
unsafe impl<K: $trait, V: $trait> $trait for ::std::collections::BTreeMap<K, V> {}
unsafe impl<K: $trait, V: $trait, S> $trait for ::indexmap::IndexMap<K, V, S> {}
unsafe impl<T: $trait + ?Sized> $trait for ::std::boxed::Box<T> {}
unsafe impl<T: $trait + ?Sized> $trait for std::sync::Arc<T> {}
unsafe impl<T: $trait, E: $trait> $trait for ::std::result::Result<T, E> {}
unsafe impl<T: $trait + ?Sized> $trait for ::std::sync::Mutex<T> {}
unsafe impl<T: $trait + ?Sized> $trait for ::std::cell::RefCell<T> {}
unsafe impl<T: ?Sized> $trait for ::std::marker::PhantomData<T> {}
unsafe impl<T: $trait + ?Sized> $trait for &T {}
unsafe impl<T: $trait + ?Sized> $trait for &mut T {}
}
}
/// Create a trivial marker trait implementation for trivial types with no generic parameters.
///
/// Accepts a colon-separated `$trait` identifier followed by a comma-separated list of types to
/// implement the `$trait` on.
macro_rules! impl_marker_trait {
($trait:ident: $ty:ty $(,)?) => {
unsafe impl $trait for $ty {}
};
($trait:ident: $ty:ty, $($tys:ty),+ $(,)?) => {
$crate::marker_trait::impl_marker_trait!($trait: $ty);
$crate::marker_trait::impl_marker_trait!($trait: $($tys),+);
}
}
/// Create an implementation for every possible tuple where every element implements `$trait`.
///
/// Must be passed a sequence of identifier fo the tuple's generic parameters. This will only
/// generate implementations up to the length of the passed in sequence.
///
/// Based on stdlib's internal `tuple_impls!` macro.
macro_rules! impl_marker_trait_tuple {
($trait:ident: $T:ident) => {
$crate::marker_trait::impl_marker_trait_tuple!(@impl $trait: $T);
};
($trait:ident: $T:ident $( $U:ident )+) => {
$crate::marker_trait::impl_marker_trait_tuple!($trait: $( $U )+);
$crate::marker_trait::impl_marker_trait_tuple!(@impl $trait: $T $( $U )+);
};
(@impl $trait:ident: $( $T:ident )+) => {
unsafe impl<$($T: $trait),+> $trait for ($($T,)+) {}
};
}
pub(crate) use impl_auto_marker_trait;
pub(crate) use impl_marker_trait;
pub(crate) use impl_marker_trait_tuple;
...@@ -23,7 +23,7 @@ pub use self::{ ...@@ -23,7 +23,7 @@ pub use self::{
cast::{VcCast, VcValueTraitCast, VcValueTypeCast}, cast::{VcCast, VcValueTraitCast, VcValueTypeCast},
cell_mode::{VcCellMode, VcCellNewMode, VcCellSharedMode}, cell_mode::{VcCellMode, VcCellNewMode, VcCellSharedMode},
default::ValueDefault, default::ValueDefault,
operation::OperationVc, operation::{OperationValue, OperationVc},
read::{ReadVcFuture, VcDefaultRead, VcRead, VcTransparentRead}, read::{ReadVcFuture, VcDefaultRead, VcRead, VcTransparentRead},
resolved::{ResolvedValue, ResolvedVc}, resolved::{ResolvedValue, ResolvedVc},
traits::{Dynamic, TypedForInput, Upcast, VcValueTrait, VcValueType}, traits::{Dynamic, TypedForInput, Upcast, VcValueTrait, VcValueType},
......
...@@ -3,7 +3,10 @@ use std::{fmt::Debug, hash::Hash}; ...@@ -3,7 +3,10 @@ use std::{fmt::Debug, hash::Hash};
use auto_hash_map::AutoSet; use auto_hash_map::AutoSet;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use crate::{trace::TraceRawVcs, CollectiblesSource, RawVc, TaskInput, Upcast, Vc, VcValueTrait}; use crate::{
marker_trait::impl_auto_marker_trait, trace::TraceRawVcs, CollectiblesSource, RawVc, TaskInput,
Upcast, Vc, VcValueTrait,
};
#[must_use] #[must_use]
pub struct OperationVc<T> pub struct OperationVc<T>
...@@ -156,3 +159,18 @@ where ...@@ -156,3 +159,18 @@ where
self.node.node.peek_collectibles() self.node.node.peek_collectibles()
} }
} }
/// Indicates that a type does not contain any instances of [`Vc`] or
/// [`ResolvedVc`][crate::ResolvedVc]. It may contain [`OperationVc`].
///
/// # Safety
///
/// This trait is marked as unsafe. You should not derive it yourself, but instead you should rely
/// on [`#[derive(OperationValue)]`][macro@OperationValue] to do it for you.
pub unsafe trait OperationValue {}
unsafe impl<T: ?Sized + Send> OperationValue for OperationVc<T> {}
impl_auto_marker_trait!(OperationValue);
pub use turbo_tasks_macros::OperationValue;
use std::{ use std::{
any::Any, any::Any,
cell::RefCell,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
fmt::Debug, fmt::Debug,
future::IntoFuture, future::IntoFuture,
hash::{Hash, Hasher}, hash::{Hash, Hasher},
marker::PhantomData,
ops::Deref, ops::Deref,
path::{Path, PathBuf},
sync::{
atomic::{
AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicU16, AtomicU32, AtomicU64,
AtomicU8, AtomicUsize,
},
Arc, Mutex,
},
time::Duration,
}; };
use anyhow::Result; use anyhow::Result;
use auto_hash_map::{AutoMap, AutoSet};
use indexmap::{IndexMap, IndexSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use crate::{ use crate::{
debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString}, debug::{ValueDebug, ValueDebugFormat, ValueDebugFormatString},
marker_trait::impl_auto_marker_trait,
trace::{TraceRawVcs, TraceRawVcsContext}, trace::{TraceRawVcs, TraceRawVcsContext},
vc::Vc, vc::Vc,
ResolveTypeError, Upcast, VcRead, VcTransparentRead, VcValueTrait, VcValueType, ResolveTypeError, Upcast, VcRead, VcTransparentRead, VcValueTrait, VcValueType,
...@@ -42,8 +28,8 @@ where ...@@ -42,8 +28,8 @@ where
} }
impl<T> ResolvedVc<T> { impl<T> ResolvedVc<T> {
/// This function exists to intercept calls to Vc::to_resolved through dereferencing /// This function exists to intercept calls to Vc::to_resolved through dereferencing
/// a ResolvedVc. Converting to Vc and re-resolving it puts unnecessary stress on /// a ResolvedVc. Converting to Vc and re-resolving it puts unnecessary stress on
/// the turbo tasks engine. /// the turbo tasks engine.
#[deprecated(note = "No point in resolving a vc that is already resolved")] #[deprecated(note = "No point in resolving a vc that is already resolved")]
pub async fn to_resolved(self) -> Result<Self> { pub async fn to_resolved(self) -> Result<Self> {
...@@ -255,85 +241,17 @@ where ...@@ -255,85 +241,17 @@ where
} }
} }
/// Indicates that a type does not contain any instances of [`Vc`]. It may /// Indicates that a type does not contain any instances of [`Vc`] or
/// contain [`ResolvedVc`]. /// [`OperationVc`][crate::OperationVc]. It may contain [`ResolvedVc`].
/// ///
/// # Safety /// # Safety
/// ///
/// This trait is marked as unsafe. You should not derive it yourself, but /// This trait is marked as unsafe. You should not derive it yourself, but instead you should rely
/// instead you should rely on [`#[turbo_tasks::value(resolved)]`][macro@ /// on [`#[turbo_tasks::value(resolved)]`][macro@ crate::value] to do it for you.
/// crate::value] to do it for you.
pub unsafe trait ResolvedValue {} pub unsafe trait ResolvedValue {}
unsafe impl<T: ?Sized + ResolvedValue> ResolvedValue for ResolvedVc<T> {} unsafe impl<T: ?Sized + ResolvedValue> ResolvedValue for ResolvedVc<T> {}
macro_rules! impl_resolved { impl_auto_marker_trait!(ResolvedValue);
($ty:ty) => {
unsafe impl ResolvedValue for $ty {}
};
($ty:ty, $($tys:ty),+) => {
impl_resolved!($ty);
impl_resolved!($($tys),+);
}
}
impl_resolved!(i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, char, bool, usize);
impl_resolved!(
AtomicI8,
AtomicU8,
AtomicI16,
AtomicU16,
AtomicI32,
AtomicU32,
AtomicI64,
AtomicU64,
AtomicBool,
AtomicUsize
);
impl_resolved!((), str, String, Duration, anyhow::Error, RcStr);
impl_resolved!(Path, PathBuf);
impl_resolved!(serde_json::Value);
// based on stdlib's internal `tuple_impls!` macro
macro_rules! impl_resolved_tuple {
($T:ident) => {
impl_resolved_tuple!(@impl $T);
};
($T:ident $( $U:ident )+) => {
impl_resolved_tuple!($( $U )+);
impl_resolved_tuple!(@impl $T $( $U )+);
};
(@impl $( $T:ident )+) => {
unsafe impl<$($T: ResolvedValue),+> ResolvedValue for ($($T,)+) {}
};
}
impl_resolved_tuple!(E D C B A Z Y X W V U T);
unsafe impl<T: ResolvedValue> ResolvedValue for Option<T> {}
unsafe impl<T: ResolvedValue> ResolvedValue for Vec<T> {}
unsafe impl<T: ResolvedValue, const N: usize> ResolvedValue for [T; N] {}
unsafe impl<T: ResolvedValue> ResolvedValue for [T] {}
unsafe impl<T: ResolvedValue, S> ResolvedValue for HashSet<T, S> {}
unsafe impl<T: ResolvedValue, S, const I: usize> ResolvedValue for AutoSet<T, S, I> {}
unsafe impl<T: ResolvedValue> ResolvedValue for BTreeSet<T> {}
unsafe impl<T: ResolvedValue, S> ResolvedValue for IndexSet<T, S> {}
unsafe impl<K: ResolvedValue, V: ResolvedValue, S> ResolvedValue for HashMap<K, V, S> {}
unsafe impl<K: ResolvedValue, V: ResolvedValue, S, const I: usize> ResolvedValue
for AutoMap<K, V, S, I>
{
}
unsafe impl<K: ResolvedValue, V: ResolvedValue> ResolvedValue for BTreeMap<K, V> {}
unsafe impl<K: ResolvedValue, V: ResolvedValue, S> ResolvedValue for IndexMap<K, V, S> {}
unsafe impl<T: ResolvedValue + ?Sized> ResolvedValue for Box<T> {}
unsafe impl<T: ResolvedValue + ?Sized> ResolvedValue for Arc<T> {}
unsafe impl<T: ResolvedValue, E: ResolvedValue> ResolvedValue for Result<T, E> {}
unsafe impl<T: ResolvedValue + ?Sized> ResolvedValue for Mutex<T> {}
unsafe impl<T: ResolvedValue + ?Sized> ResolvedValue for RefCell<T> {}
unsafe impl<T: ?Sized> ResolvedValue for PhantomData<T> {}
unsafe impl<T: ResolvedValue + ?Sized> ResolvedValue for &T {}
unsafe impl<T: ResolvedValue + ?Sized> ResolvedValue for &mut T {}
pub use turbo_tasks_macros::ResolvedValue; pub use turbo_tasks_macros::ResolvedValue;
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