Unverified Commit 515d9c1e authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Update turbopack to syn2 (#78385)

Update turbopack to syn2

This delivers a number of basic API improvements and is required for us to adopt later rust editions.

I confirmed correctness by diffing `cargo expand` on the turbopack  crate across this change. 

Most of the changes are trivial updating to new names and ast structures, the more interesting ones were some changes to the `self` types, which improves consistency but broke a number of places were were working around the prior inconsistency (previously bare `self` or `&self` declarations were represented as `FnArg::Receiver` but a _typed_ receiver like `self: Vc<Self>` was a `FnArg::Typed`, now `self` declarations are always `FnArg::Receiver`)

Closes PACK-4383
parent 952450fe
...@@ -8593,6 +8593,12 @@ version = "0.12.16" ...@@ -8593,6 +8593,12 @@ version = "0.12.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "target-triple"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ac9aa371f599d22256307c24a9d748c041e548cbf599f35d890f9d365361790"
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.14.0" version = "3.14.0"
...@@ -9167,14 +9173,15 @@ checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed" ...@@ -9167,14 +9173,15 @@ checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
[[package]] [[package]]
name = "trybuild" name = "trybuild"
version = "1.0.99" version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "207aa50d36c4be8d8c6ea829478be44a372c6a77669937bb39c698e52f1491e8" checksum = "6ae08be68c056db96f0e6c6dd820727cca756ced9e1f4cc7fdd20e2a55e23898"
dependencies = [ dependencies = [
"glob", "glob",
"serde", "serde",
"serde_derive", "serde_derive",
"serde_json", "serde_json",
"target-triple",
"termcolor", "termcolor",
"toml 0.8.19", "toml 0.8.19",
] ]
...@@ -9386,7 +9393,7 @@ dependencies = [ ...@@ -9386,7 +9393,7 @@ dependencies = [
"glob", "glob",
"quote", "quote",
"rustc-hash 2.1.0", "rustc-hash 2.1.0",
"syn 1.0.109", "syn 2.0.100",
"turbo-tasks-macros-shared", "turbo-tasks-macros-shared",
] ]
...@@ -9513,7 +9520,7 @@ dependencies = [ ...@@ -9513,7 +9520,7 @@ dependencies = [
"quote", "quote",
"regex", "regex",
"rustc-hash 2.1.0", "rustc-hash 2.1.0",
"syn 1.0.109", "syn 2.0.100",
"turbo-tasks-macros-shared", "turbo-tasks-macros-shared",
] ]
...@@ -9523,7 +9530,7 @@ version = "0.1.0" ...@@ -9523,7 +9530,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 1.0.109", "syn 2.0.100",
] ]
[[package]] [[package]]
......
...@@ -410,7 +410,7 @@ sourcemap = "9.0.0" ...@@ -410,7 +410,7 @@ sourcemap = "9.0.0"
strsim = "0.11.1" strsim = "0.11.1"
shrink-to-fit = "0.2.10" shrink-to-fit = "0.2.10"
swc-rustc-hash = { package = "rustc-hash", version = "1.1.0" } # used with swc swc-rustc-hash = { package = "rustc-hash", version = "1.1.0" } # used with swc
syn = "1.0.107" syn = "2.0.100"
tempfile = "3.3.0" tempfile = "3.3.0"
thread_local = "1.1.8" thread_local = "1.1.8"
thiserror = "1.0.48" thiserror = "1.0.48"
......
...@@ -12,7 +12,7 @@ use quote::ToTokens; ...@@ -12,7 +12,7 @@ use quote::ToTokens;
use rustc_hash::{FxHashMap, FxHashSet}; use rustc_hash::{FxHashMap, FxHashSet};
use syn::{ use syn::{
parse_quote, Attribute, Ident, Item, ItemEnum, ItemFn, ItemImpl, ItemMacro, ItemMod, parse_quote, Attribute, Ident, Item, ItemEnum, ItemFn, ItemImpl, ItemMacro, ItemMod,
ItemStruct, ItemTrait, TraitItem, TraitItemMethod, ItemStruct, ItemTrait, TraitItem, TraitItemFn,
}; };
use turbo_tasks_macros_shared::{ use turbo_tasks_macros_shared::{
get_impl_function_ident, get_native_function_ident, get_path_ident, get_impl_function_ident, get_native_function_ident, get_path_ident,
...@@ -286,7 +286,7 @@ impl RegisterContext<'_> { ...@@ -286,7 +286,7 @@ impl RegisterContext<'_> {
} }
for item in &impl_item.items { for item in &impl_item.items {
if let syn::ImplItem::Method(method_item) = item { if let syn::ImplItem::Fn(method_item) = item {
// TODO: if method_item.attrs.iter().any(|a| // TODO: if method_item.attrs.iter().any(|a|
// is_attribute(a, // is_attribute(a,
// "function")) { // "function")) {
...@@ -371,7 +371,7 @@ impl RegisterContext<'_> { ...@@ -371,7 +371,7 @@ impl RegisterContext<'_> {
let trait_ident = &trait_item.ident; let trait_ident = &trait_item.ident;
for item in &trait_item.items { for item in &trait_item.items {
if let TraitItem::Method(TraitItemMethod { if let TraitItem::Fn(TraitItemFn {
default: Some(_), default: Some(_),
sig, sig,
.. ..
...@@ -583,7 +583,7 @@ fn has_turbo_attribute(attrs: &[Attribute], name: &str) -> bool { ...@@ -583,7 +583,7 @@ fn has_turbo_attribute(attrs: &[Attribute], name: &str) -> bool {
} }
fn is_turbo_attribute(attr: &Attribute, name: &str) -> bool { fn is_turbo_attribute(attr: &Attribute, name: &str) -> bool {
let path = &attr.path; let path = attr.path();
if path.leading_colon.is_some() { if path.leading_colon.is_some() {
return false; return false;
} }
...@@ -598,7 +598,7 @@ fn is_turbo_attribute(attr: &Attribute, name: &str) -> bool { ...@@ -598,7 +598,7 @@ fn is_turbo_attribute(attr: &Attribute, name: &str) -> bool {
} }
fn is_cfg_attribute(attr: &Attribute) -> bool { fn is_cfg_attribute(attr: &Attribute) -> bool {
attr.path attr.path()
.get_ident() .get_ident()
.is_some_and(|ident| ident == "cfg" || ident == "cfg_attr") .is_some_and(|ident| ident == "cfg" || ident == "cfg_attr")
} }
use proc_macro2::Span; use proc_macro2::Span;
use syn::{ use syn::{
parse::{Parse, ParseStream}, parse::{Parse, ParseStream},
punctuated::Punctuated,
spanned::Spanned, spanned::Spanned,
Meta, Result, Token, Type, Meta, Result, Token, Type,
}; };
...@@ -20,7 +19,7 @@ impl Parse for PrimitiveInput { ...@@ -20,7 +19,7 @@ impl Parse for PrimitiveInput {
manual_shrink_to_fit: None, manual_shrink_to_fit: None,
}; };
if input.parse::<Option<Token![,]>>()?.is_some() { if input.parse::<Option<Token![,]>>()?.is_some() {
let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?; let punctuated = input.parse_terminated(Meta::parse, Token![,])?;
for meta in punctuated { for meta in punctuated {
match ( match (
meta.path() meta.path()
......
use proc_macro2::Span; use proc_macro2::Span;
use syn::{ use syn::{
parse::{Parse, ParseStream}, parse::{Parse, ParseStream},
punctuated::Punctuated,
spanned::Spanned, spanned::Spanned,
Meta, Token, Meta, Token,
}; };
...@@ -32,7 +31,7 @@ impl Parse for ValueTraitArguments { ...@@ -32,7 +31,7 @@ impl Parse for ValueTraitArguments {
return Ok(result); return Ok(result);
} }
let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?; let punctuated = input.parse_terminated(Meta::parse, Token![,])?;
for meta in punctuated { for meta in punctuated {
match meta.path().get_ident().map(ToString::to_string).as_deref() { match meta.path().get_ident().map(ToString::to_string).as_deref() {
Some("no_debug") => { Some("no_debug") => {
......
...@@ -9,7 +9,7 @@ edition = "2021" ...@@ -9,7 +9,7 @@ edition = "2021"
anyhow = { workspace = true } anyhow = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
tokio = { workspace = true } tokio = { workspace = true }
trybuild = { version = "1.0.97" } trybuild = { version = "1.0.104" }
turbo-tasks = { workspace = true } turbo-tasks = { workspace = true }
turbo-tasks-testing = { workspace = true } turbo-tasks-testing = { workspace = true }
turbo-tasks-memory = { workspace = true } turbo-tasks-memory = { workspace = true }
......
...@@ -13,7 +13,7 @@ error[E0307]: invalid `self` parameter type: `OperationVc<Foobar>` ...@@ -13,7 +13,7 @@ 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(...) -> ... {...::arbitrary_self_type_turbo_tasks_function_inline}: 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::IntoTaskFnWithThis<_, _, _>` is not satisfied
--> tests/function/fail_operation_method_self_type.rs:10:1 --> tests/function/fail_operation_method_self_type.rs:10:1
| |
10 | #[turbo_tasks::value_impl] 10 | #[turbo_tasks::value_impl]
...@@ -29,5 +29,4 @@ note: required by a bound in `NativeFunction::new_method` ...@@ -29,5 +29,4 @@ note: required by a bound in `NativeFunction::new_method`
... ...
| I: IntoTaskFnWithThis<Mode, This, Inputs>, | I: IntoTaskFnWithThis<Mode, This, Inputs>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `NativeFunction::new_method` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `NativeFunction::new_method`
= note: consider using `--verbose` to print the full type name to the console
= 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)
...@@ -3,25 +3,3 @@ error: methods taking `self` are not supported with `operation` ...@@ -3,25 +3,3 @@ error: methods taking `self` are not supported with `operation`
| |
13 | fn arbitrary_self_type_base_vc(self: Vc<Self>) -> Vc<()> { 13 | fn arbitrary_self_type_base_vc(self: Vc<Self>) -> Vc<()> {
| ^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^
error[E0277]: the trait bound `Vc<Foobar>: NonLocalValue` is not satisfied
--> tests/function/fail_operation_method_self_type_base_vc.rs:13:42
|
13 | fn arbitrary_self_type_base_vc(self: Vc<Self>) -> Vc<()> {
| ^^^^^^^^ the trait `NonLocalValue` is not implemented for `Vc<Foobar>`
|
= help: the following other types implement trait `NonLocalValue`:
&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 `assert_argument_is_non_local_value`
--> $WORKSPACE/turbopack/crates/turbo-tasks/src/macro_helpers.rs
|
| pub fn assert_argument_is_non_local_value<Argument: NonLocalValue>() {}
| ^^^^^^^^^^^^^ required by this bound in `assert_argument_is_non_local_value`
...@@ -11,7 +11,7 @@ pub use deterministic_hash_macro::derive_deterministic_hash; ...@@ -11,7 +11,7 @@ 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 non_local_value_macro::derive_non_local_value; pub use non_local_value_macro::derive_non_local_value;
pub use operation_value_macro::derive_operation_value; pub use operation_value_macro::derive_operation_value;
use syn::{spanned::Spanned, Attribute, Meta, MetaList, NestedMeta}; use syn::{punctuated::Punctuated, spanned::Spanned, Attribute, Meta, Token};
pub use task_input_macro::derive_task_input; pub use task_input_macro::derive_task_input;
pub use trace_raw_vcs_macro::derive_trace_raw_vcs; pub use trace_raw_vcs_macro::derive_trace_raw_vcs;
pub use value_debug_format_macro::derive_value_debug_format; pub use value_debug_format_macro::derive_value_debug_format;
...@@ -31,34 +31,48 @@ impl From<&[Attribute]> for FieldAttributes { ...@@ -31,34 +31,48 @@ impl From<&[Attribute]> for FieldAttributes {
for attr in attrs { for attr in attrs {
if !attr if !attr
.path .path()
.get_ident() .get_ident()
.map(|ident| *ident == "turbo_tasks") .map(|ident| *ident == "turbo_tasks")
.unwrap_or_default() .unwrap_or_default()
{ {
continue; continue;
} }
if let Ok(Meta::List(MetaList { nested, .. })) = attr let nested = match attr.parse_args_with(Punctuated::<Meta, Token![,]>::parse_terminated)
.parse_meta()
.map_err(|err| err.span().unwrap().error(err.to_string()).emit())
{ {
for meta in nested { Ok(punctuated) => punctuated,
if let NestedMeta::Meta(Meta::Path(path)) = &meta { Err(e) => {
match path.get_ident().map(|ident| ident.to_string()).as_deref() { attr.meta
Some("trace_ignore") => result.trace_ignore = true,
Some("debug_ignore") => result.debug_ignore = true,
_ => path
.span() .span()
.unwrap() .unwrap()
.error("expected `trace_ignore` or `debug_ignore`") .error(format!(
.emit(), "expected `trace_ignore` or `debug_ignore`, got: {e}"
))
.emit();
Punctuated::default()
} }
};
for meta in nested {
match meta {
Meta::Path(path) => {
if path.is_ident("trace_ignore") {
result.trace_ignore = true;
} else if path.is_ident("debug_ignore") {
result.debug_ignore = true;
} else { } else {
meta.span() path.span()
.span()
.unwrap() .unwrap()
.error("expected `trace_ignore` or `debug_ignore`") .error("expected `trace_ignore` or `debug_ignore`")
.emit(); .emit()
}
} }
_ => meta
.path()
.span()
.unwrap()
.error("expected `trace_ignore` or `debug_ignore`")
.emit(),
} }
} }
} }
......
...@@ -4,16 +4,15 @@ use proc_macro2::{Ident, Span, TokenStream}; ...@@ -4,16 +4,15 @@ use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens}; use quote::{quote, quote_spanned, ToTokens};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use syn::{ use syn::{
parenthesized,
parse::{Parse, ParseStream}, parse::{Parse, ParseStream},
parse_quote, parse_quote_spanned, parse_quote, parse_quote_spanned,
punctuated::{Pair, Punctuated}, punctuated::{Pair, Punctuated},
spanned::Spanned, spanned::Spanned,
token::Paren,
visit_mut::VisitMut, visit_mut::VisitMut,
AngleBracketedGenericArguments, Attribute, Block, Expr, ExprBlock, ExprPath, FnArg, AngleBracketedGenericArguments, Attribute, Block, Expr, ExprBlock, ExprPath, FnArg,
GenericArgument, Local, Meta, Pat, PatIdent, PatType, Path, PathArguments, PathSegment, GenericArgument, Local, LocalInit, Meta, Pat, PatIdent, PatType, Path, PathArguments,
Receiver, ReturnType, Signature, Stmt, Token, Type, TypeGroup, TypePath, TypeTuple, PathSegment, Receiver, ReturnType, Signature, Stmt, Token, Type, TypeGroup, TypePath,
TypeTuple,
}; };
#[derive(Debug)] #[derive(Debug)]
...@@ -84,8 +83,8 @@ impl TurboFn<'_> { ...@@ -84,8 +83,8 @@ impl TurboFn<'_> {
receiver @ Receiver { receiver @ Receiver {
attrs, attrs,
self_token, self_token,
reference, ty: self_type,
mutability, ..
}, },
) => { ) => {
if !attrs.is_empty() { if !attrs.is_empty() {
...@@ -93,7 +92,7 @@ impl TurboFn<'_> { ...@@ -93,7 +92,7 @@ impl TurboFn<'_> {
.span() .span()
.unwrap() .unwrap()
.error(format!( .error(format!(
"{} do not support attributes on arguments", "{} do not support attributes on self",
definition_context.function_type(), definition_context.function_type(),
)) ))
.emit(); .emit();
...@@ -109,61 +108,53 @@ impl TurboFn<'_> { ...@@ -109,61 +108,53 @@ impl TurboFn<'_> {
_ => &definition_context, _ => &definition_context,
}; };
if !attrs.is_empty() { match self_type.as_ref() {
receiver // we allow `&Self` but not `&mut Self`
.span() syn::Type::Reference(type_reference) => {
if let Some(m) = type_reference.mutability {
m.span()
.unwrap() .unwrap()
.error(format!( .error(format!(
"{} do not support attributes on self", "{} cannot take self by mutable reference, use &self or \
self: Vc<Self> instead",
definition_context.function_type(), definition_context.function_type(),
)) ))
.emit(); .emit();
return None; return None;
} }
if mutability.is_some() { match type_reference.elem.as_ref() {
receiver syn::Type::Path(TypePath { qself: None, path })
if path.is_ident("Self") => {}
_ => {
self_type
.span() .span()
.unwrap() .unwrap()
.error(format!( .error(
"{} cannot take self by mutable reference, use &self or self: \ "Unexpected `self` type, use `&self` or `self: \
Vc<Self> instead", Vc<Self>",
definition_context.function_type(), )
))
.emit(); .emit();
return None; return None;
} }
match &reference {
None => {
receiver
.span()
.unwrap()
.error(format!(
"{} cannot take self by value, use &self or self: Vc<Self> \
instead",
definition_context.function_type(),
))
.emit();
return None;
} }
Some((_, Some(lifetime))) => { }
lifetime syn::Type::Path(_) => {}
_ => {
self_type
.span() .span()
.unwrap() .unwrap()
.error(format!( .error("Unexpected `self` type, use `&self` or `self: Vc<Self>")
"{} cannot take self by reference with a custom lifetime, use \
&self or self: Vc<Self> instead",
definition_context.function_type(),
))
.emit(); .emit();
return None; return None;
} }
_ => {}
} }
// We don't validate that the user provided a valid `turbo_tasks::Vc<Self>`
// here. We'll rely on the compiler to emit an error if the user provided an
// invalid receiver type
this = Some(Input { this = Some(Input {
ident: Ident::new("self", self_token.span()), ident: Ident::from(*self_token),
ty: parse_quote! { turbo_tasks::Vc<Self> }, ty: parse_quote! { turbo_tasks::Vc<Self> },
}); });
} }
...@@ -181,30 +172,9 @@ impl TurboFn<'_> { ...@@ -181,30 +172,9 @@ impl TurboFn<'_> {
} }
if let Pat::Ident(ident) = &*typed.pat { if let Pat::Ident(ident) = &*typed.pat {
if ident.ident == "self" {
if let DefinitionContext::NakedFn = definition_context {
// The function is not associated. The compiler will emit an error
// on its own.
return None;
};
// We don't validate that the user provided a valid
// `turbo_tasks::Vc<Self>` here.
// We'll rely on the compiler to emit an error
// if the user provided an invalid receiver type
let ident = ident.ident.clone();
this = Some(Input {
ident,
ty: parse_quote! { turbo_tasks::Vc<Self> },
});
} else {
match definition_context { match definition_context {
DefinitionContext::NakedFn DefinitionContext::NakedFn | DefinitionContext::ValueInherentImpl => {}
| DefinitionContext::ValueInherentImpl => {} DefinitionContext::ValueTraitImpl | DefinitionContext::ValueTrait => {
DefinitionContext::ValueTraitImpl
| DefinitionContext::ValueTrait => {
typed typed
.span() .span()
.unwrap() .unwrap()
...@@ -223,7 +193,6 @@ impl TurboFn<'_> { ...@@ -223,7 +193,6 @@ impl TurboFn<'_> {
ident, ident,
ty: (*typed.ty).clone(), ty: (*typed.ty).clone(),
}); });
}
} else { } else {
// We can't support destructuring patterns (or other kinds of patterns). // We can't support destructuring patterns (or other kinds of patterns).
let ident = Ident::new("arg1", typed.pat.span()); let ident = Ident::new("arg1", typed.pat.span());
...@@ -359,19 +328,74 @@ impl TurboFn<'_> { ...@@ -359,19 +328,74 @@ impl TurboFn<'_> {
inline_inputs_identifier_filter(&pat_id.ident) inline_inputs_identifier_filter(&pat_id.ident)
}) })
.enumerate() .enumerate()
.map(|(idx, arg)| match arg { .map(|(idx, arg)| {
FnArg::Receiver(_) => (arg.clone(), None),
FnArg::Typed(pat_type) => {
if self.operation { if self.operation {
// operations shouldn't have their arguments rewritten, they require all // operations shouldn't have their arguments rewritten, they require all
// arguments are explicitly `NonLocalValue`s // arguments are explicitly `NonLocalValue`s
return (arg.clone(), None); return (arg.clone(), None);
} }
let Cow::Owned(expanded_ty) = expand_task_input_type(&pat_type.ty) else { let (FnArg::Receiver(Receiver { ty, .. }) | FnArg::Typed(PatType { ty, .. })) = arg;
let Cow::Owned(expanded_ty) = expand_task_input_type(ty) else {
// common-case: skip if no type conversion is needed // common-case: skip if no type conversion is needed
return (arg.clone(), None); return (arg.clone(), None);
}; };
// Helper to produce the transform statement
let transform_from_task_input = |arg_id: Cow<'_, Ident>, pat: Pat| {
Stmt::Local(Local {
attrs: Vec::new(),
let_token: Default::default(),
pat,
init: Some(LocalInit {
eq_token: Default::default(),
// we know the argument implements `FromTaskInput` because
// `expand_task_input_type` returned `Cow::Owned`
expr: parse_quote_spanned! {
arg.span() =>
<#ty as turbo_tasks::task::FromTaskInput>::from_task_input(
#arg_id
)
},
diverge: None,
}),
semi_token: Default::default(),
})
};
match arg {
FnArg::Receiver(
receiver @ Receiver {
attrs, self_token, ..
},
) => {
let arg = FnArg::Receiver(Receiver {
attrs: Vec::new(),
mutability: None,
ty: Box::new(expanded_ty),
..receiver.clone()
});
// We can't shadow `self` variables, so it this argument is a `self`
// argument, generate a new identifier, and rewrite
// the body of the function later to use
// that new identifier.
let shadow_self_id = Ident::new(
"turbo_tasks_self",
Span::mixed_site().located_at(self_token.span()),
);
shadow_self = Some(shadow_self_id.clone());
let shadow_self_pattern = Pat::Ident(PatIdent {
ident: shadow_self_id,
attrs: attrs.clone(),
mutability: None,
by_ref: None,
subpat: None,
});
let self_ident = Cow::Owned(Ident::new("self", self_token.span()));
let transform_stmt =
transform_from_task_input(self_ident, shadow_self_pattern);
(arg, Some(transform_stmt))
}
FnArg::Typed(pat_type) => {
let arg_id = if let Pat::Ident(pat_id) = &*pat_type.pat { let arg_id = if let Pat::Ident(pat_id) = &*pat_type.pat {
// common case: argument is just an identifier // common case: argument is just an identifier
Cow::Borrowed(&pat_id.ident) Cow::Borrowed(&pat_id.ident)
...@@ -395,47 +419,13 @@ impl TurboFn<'_> { ...@@ -395,47 +419,13 @@ impl TurboFn<'_> {
..pat_type.clone() ..pat_type.clone()
}); });
// We can't shadow `self` variables, so it this argument is a `self` argument,
// generate a new identifier, and rewrite the body of the function later to use
// that new identifier.
// NOTE: arbitrary self types aren't `FnArg::Receiver` on syn 1.x (fixed in 2.x)
let transform_pat = match &*pat_type.pat {
Pat::Ident(pat_id) if pat_id.ident == "self" => {
let shadow_self_id = Ident::new(
"turbo_tasks_self",
Span::mixed_site().located_at(pat_id.ident.span()),
);
shadow_self = Some(shadow_self_id.clone());
Pat::Ident(PatIdent {
ident: shadow_self_id,
..pat_id.clone()
})
}
pat => pat.clone(),
};
// convert an argument of type `FromTaskInput<T>::TaskInput` into `T`. // convert an argument of type `FromTaskInput<T>::TaskInput` into `T`.
// essentially, replace any instances of `Vc` with `ResolvedVc`. // essentially, replace any instances of `Vc` with `ResolvedVc`.
let orig_ty = &*pat_type.ty; let pat = (*pat_type.pat).clone();
let transform_stmt = Some(Stmt::Local(Local { let transform_stmt = transform_from_task_input(arg_id, pat);
attrs: Vec::new(),
let_token: Default::default(),
pat: transform_pat,
init: Some((
Default::default(),
// we know the argument implements `FromTaskInput` because
// `expand_task_input_type` returned `Cow::Owned`
parse_quote_spanned! {
pat_type.span() =>
<#orig_ty as turbo_tasks::task::FromTaskInput>::from_task_input(
#arg_id
)
},
)),
semi_token: Default::default(),
}));
(arg, transform_stmt) (arg, Some(transform_stmt))
}
} }
}) })
.unzip(); .unzip();
...@@ -452,11 +442,13 @@ impl TurboFn<'_> { ...@@ -452,11 +442,13 @@ impl TurboFn<'_> {
Cow::Borrowed(orig_block) Cow::Borrowed(orig_block)
} else { } else {
let mut stmts = transform_stmts; let mut stmts = transform_stmts;
stmts.push(Stmt::Expr(Expr::Block(ExprBlock { stmts.push(Stmt::Expr(
Expr::Block(ExprBlock {
attrs: Vec::new(), attrs: Vec::new(),
label: None, label: None,
block: if let Some(shadow_self) = shadow_self { block: if let Some(shadow_self) = shadow_self {
// if `self` is a `ResolvedVc<Self>`, we need to rewrite references to `self` // if `self` is a `ResolvedVc<Self>`, we need to rewrite references to
// `self`
let mut block = orig_block.clone(); let mut block = orig_block.clone();
RewriteSelfVisitMut { RewriteSelfVisitMut {
self_ident: shadow_self, self_ident: shadow_self,
...@@ -466,7 +458,9 @@ impl TurboFn<'_> { ...@@ -466,7 +458,9 @@ impl TurboFn<'_> {
} else { } else {
orig_block.clone() orig_block.clone()
}, },
}))); }),
None,
));
Cow::Owned(Block { Cow::Owned(Block {
brace_token: Default::default(), brace_token: Default::default(),
stmts, stmts,
...@@ -706,42 +700,15 @@ enum IoMarker { ...@@ -706,42 +700,15 @@ enum IoMarker {
Network, Network,
} }
/// Unwraps a parenthesized set of tokens. // Optionally parses `T` from a parethensized attributes, returns `T::default` otherwise.
/// pub fn parse_with_optional_parens<T: Parse + Default>(attr: &Attribute) -> syn::Result<T> {
/// Syn's lower-level [`parenthesized`] macro which this uses requires a match &attr.meta {
/// [`ParseStream`] and cannot be used with [`parse_macro_input`], Meta::Path(_) => Ok(T::default()),
/// [`syn::parse2`] or anything else accepting a [`TokenStream`]. This can be Meta::List(meta) => meta.parse_args_with(T::parse),
/// used with those [`TokenStream`]-based parsing APIs. Meta::NameValue(meta) => Err(syn::Error::new(
pub struct Parenthesized<T: Parse> { meta.eq_token.span,
pub _paren_token: Paren, "Expected parenthized parameters",
pub inner: T, )),
}
impl<T: Parse> Parse for Parenthesized<T> {
fn parse(input: ParseStream) -> syn::Result<Self> {
let inner;
Ok(Self {
_paren_token: parenthesized!(inner in input),
inner: <T>::parse(&inner)?,
})
}
}
/// A newtype wrapper for [`Option<Parenthesized>`][Parenthesized] that
/// implements [`Parse`].
pub struct MaybeParenthesized<T: Parse> {
pub parenthesized: Option<Parenthesized<T>>,
}
impl<T: Parse> Parse for MaybeParenthesized<T> {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(Self {
parenthesized: if input.peek(Paren) {
Some(Parenthesized::<T>::parse(input)?)
} else {
None
},
})
} }
} }
...@@ -769,7 +736,7 @@ pub struct FunctionArguments { ...@@ -769,7 +736,7 @@ pub struct FunctionArguments {
impl Parse for FunctionArguments { impl Parse for FunctionArguments {
fn parse(input: ParseStream) -> syn::Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
let mut parsed_args = FunctionArguments::default(); let mut parsed_args = FunctionArguments::default();
let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?; let punctuated = input.parse_terminated(Meta::parse, Token![,])?;
for meta in punctuated { for meta in punctuated {
match ( match (
meta.path() meta.path()
...@@ -1166,7 +1133,7 @@ pub fn filter_inline_attributes<'a>( ...@@ -1166,7 +1133,7 @@ pub fn filter_inline_attributes<'a>(
// inline functions use #[doc(hidden)], so it's not useful to preserve/duplicate docs // inline functions use #[doc(hidden)], so it's not useful to preserve/duplicate docs
attrs attrs
.into_iter() .into_iter()
.filter(|attr| attr.path.get_ident().is_none_or(|id| id != "doc")) .filter(|attr| attr.path().get_ident().is_none_or(|id| id != "doc"))
.collect() .collect()
} }
......
...@@ -4,10 +4,9 @@ use quote::{quote, ToTokens}; ...@@ -4,10 +4,9 @@ use quote::{quote, ToTokens};
use syn::{ use syn::{
parse::{Parse, ParseStream}, parse::{Parse, ParseStream},
parse_macro_input, parse_quote, parse_macro_input, parse_quote,
punctuated::Punctuated,
spanned::Spanned, spanned::Spanned,
Attribute, Error, Generics, ImplItem, ImplItemMethod, ItemImpl, Lit, LitStr, Meta, Attribute, Error, Expr, ExprLit, Generics, ImplItem, ImplItemFn, ItemImpl, Lit, LitStr, Meta,
MetaNameValue, Path, Result, Token, Type, MetaNameValue, Path, Token, Type,
}; };
use turbo_tasks_macros_shared::{ use turbo_tasks_macros_shared::{
get_inherent_impl_function_id_ident, get_inherent_impl_function_ident, get_path_ident, get_inherent_impl_function_id_ident, get_inherent_impl_function_ident, get_path_ident,
...@@ -16,12 +15,12 @@ use turbo_tasks_macros_shared::{ ...@@ -16,12 +15,12 @@ use turbo_tasks_macros_shared::{
}; };
use crate::func::{ use crate::func::{
filter_inline_attributes, DefinitionContext, FunctionArguments, MaybeParenthesized, NativeFn, filter_inline_attributes, parse_with_optional_parens, DefinitionContext, FunctionArguments,
TurboFn, NativeFn, TurboFn,
}; };
fn is_attribute(attr: &Attribute, name: &str) -> bool { fn is_attribute(attr: &Attribute, name: &str) -> bool {
let path = &attr.path; let path = &attr.path();
if path.leading_colon.is_some() { if path.leading_colon.is_some() {
return false; return false;
} }
...@@ -45,8 +44,7 @@ fn split_function_attributes<'a>( ...@@ -45,8 +44,7 @@ fn split_function_attributes<'a>(
.partition(|attr| is_attribute(attr, "function")); .partition(|attr| is_attribute(attr, "function"));
let func_args = if let Some(func_attr) = func_attrs_vec.first() { let func_args = if let Some(func_attr) = func_attrs_vec.first() {
if func_attrs_vec.len() == 1 { if func_attrs_vec.len() == 1 {
syn::parse2::<MaybeParenthesized<FunctionArguments>>(func_attr.tokens.clone()) parse_with_optional_parens::<FunctionArguments>(func_attr)
.map(|a| a.parenthesized.map(|a| a.inner).unwrap_or_default())
} else { } else {
Err(syn::Error::new( Err(syn::Error::new(
func_attr.span(), func_attr.span(),
...@@ -67,9 +65,9 @@ struct ValueImplArguments { ...@@ -67,9 +65,9 @@ struct ValueImplArguments {
} }
impl Parse for ValueImplArguments { impl Parse for ValueImplArguments {
fn parse(input: ParseStream) -> Result<Self> { fn parse(input: ParseStream) -> syn::Result<Self> {
let mut result = ValueImplArguments { ident: None }; let mut result = ValueImplArguments { ident: None };
let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?; let punctuated = input.parse_terminated(Meta::parse, Token![,])?;
for meta in punctuated { for meta in punctuated {
match ( match (
meta.path() meta.path()
...@@ -82,8 +80,12 @@ impl Parse for ValueImplArguments { ...@@ -82,8 +80,12 @@ impl Parse for ValueImplArguments {
( (
"ident", "ident",
Meta::NameValue(MetaNameValue { Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(lit), .. lit: Lit::Str(lit), ..
}), }),
..
}),
) => { ) => {
result.ident = Some(lit); result.ident = Some(lit);
} }
...@@ -109,7 +111,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -109,7 +111,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
let mut errors = Vec::new(); let mut errors = Vec::new();
for item in items.iter() { for item in items.iter() {
if let ImplItem::Method(ImplItemMethod { if let ImplItem::Fn(ImplItemFn {
attrs, attrs,
vis, vis,
defaultness: _, defaultness: _,
...@@ -212,7 +214,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -212,7 +214,7 @@ pub fn value_impl(args: TokenStream, input: TokenStream) -> TokenStream {
let mut errors = Vec::new(); let mut errors = Vec::new();
for item in items.iter() { for item in items.iter() {
if let ImplItem::Method(ImplItemMethod { if let ImplItem::Fn(ImplItemFn {
sig, attrs, block, .. sig, attrs, block, ..
}) = item }) = item
{ {
......
...@@ -7,10 +7,9 @@ use regex::Regex; ...@@ -7,10 +7,9 @@ use regex::Regex;
use syn::{ use syn::{
parse::{Parse, ParseStream}, parse::{Parse, ParseStream},
parse_macro_input, parse_quote, parse_macro_input, parse_quote,
punctuated::Punctuated,
spanned::Spanned, spanned::Spanned,
Error, Fields, FieldsUnnamed, Generics, Item, ItemEnum, ItemStruct, Lit, LitStr, Meta, Error, Expr, ExprLit, Fields, FieldsUnnamed, Generics, Item, ItemEnum, ItemStruct, Lit, LitStr,
MetaNameValue, Result, Token, Meta, MetaNameValue, Result, Token,
}; };
use turbo_tasks_macros_shared::{ use turbo_tasks_macros_shared::{
get_register_value_type_ident, get_value_type_id_ident, get_value_type_ident, get_register_value_type_ident, get_value_type_id_ident, get_value_type_ident,
...@@ -124,7 +123,7 @@ impl Parse for ValueArguments { ...@@ -124,7 +123,7 @@ impl Parse for ValueArguments {
transparent: false, transparent: false,
operation: None, operation: None,
}; };
let punctuated: Punctuated<Meta, Token![,]> = input.parse_terminated(Meta::parse)?; let punctuated = input.parse_terminated(Meta::parse, Token![,])?;
for meta in punctuated { for meta in punctuated {
match ( match (
meta.path() meta.path()
...@@ -141,32 +140,48 @@ impl Parse for ValueArguments { ...@@ -141,32 +140,48 @@ impl Parse for ValueArguments {
( (
"into", "into",
Meta::NameValue(MetaNameValue { Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(str), .. lit: Lit::Str(str), ..
}), }),
..
}),
) => { ) => {
result.into_mode = IntoMode::try_from(str)?; result.into_mode = IntoMode::try_from(str)?;
} }
( (
"serialization", "serialization",
Meta::NameValue(MetaNameValue { Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(str), .. lit: Lit::Str(str), ..
}), }),
..
}),
) => { ) => {
result.serialization_mode = SerializationMode::try_from(str)?; result.serialization_mode = SerializationMode::try_from(str)?;
} }
( (
"cell", "cell",
Meta::NameValue(MetaNameValue { Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(str), .. lit: Lit::Str(str), ..
}), }),
..
}),
) => { ) => {
result.cell_mode = CellMode::try_from(str)?; result.cell_mode = CellMode::try_from(str)?;
} }
( (
"eq", "eq",
Meta::NameValue(MetaNameValue { Meta::NameValue(MetaNameValue {
value:
Expr::Lit(ExprLit {
lit: Lit::Str(str), .. lit: Lit::Str(str), ..
}), }),
..
}),
) => { ) => {
result.manual_eq = if str.value() == "manual" { result.manual_eq = if str.value() == "manual" {
true true
......
use proc_macro::TokenStream; use proc_macro::TokenStream;
use proc_macro2::{Ident, TokenStream as TokenStream2}; use proc_macro2::{Ident, TokenStream as TokenStream2};
use quote::{quote, quote_spanned}; use quote::{quote, quote_spanned};
use syn::{ use syn::{parse_macro_input, parse_quote, spanned::Spanned, ItemTrait, TraitItem, TraitItemFn};
parse_macro_input, parse_quote, spanned::Spanned, ItemTrait, TraitItem, TraitItemMethod,
};
use turbo_tasks_macros_shared::{ use turbo_tasks_macros_shared::{
get_trait_default_impl_function_id_ident, get_trait_default_impl_function_ident, get_trait_default_impl_function_id_ident, get_trait_default_impl_function_ident,
get_trait_type_id_ident, get_trait_type_ident, ValueTraitArguments, get_trait_type_id_ident, get_trait_type_ident, ValueTraitArguments,
...@@ -30,6 +28,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -30,6 +28,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
auto_token, auto_token,
generics, generics,
brace_token: _, brace_token: _,
restriction: _,
} = &item; } = &item;
if unsafety.is_some() { if unsafety.is_some() {
...@@ -70,7 +69,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -70,7 +69,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
let mut items = Vec::with_capacity(raw_items.len()); let mut items = Vec::with_capacity(raw_items.len());
for item in raw_items.iter() { for item in raw_items.iter() {
let TraitItem::Method(TraitItemMethod { let TraitItem::Fn(TraitItemFn {
sig, sig,
default, default,
attrs, attrs,
...@@ -177,7 +176,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream { ...@@ -177,7 +176,7 @@ pub fn value_trait(args: TokenStream, input: TokenStream) -> TokenStream {
None None
}; };
items.push(TraitItem::Method(TraitItemMethod { items.push(TraitItem::Fn(TraitItemFn {
sig: turbo_fn.trait_signature(), sig: turbo_fn.trait_signature(),
default, default,
attrs: attrs.clone(), attrs: attrs.clone(),
......
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