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