Dataset Viewer
Auto-converted to Parquet Duplicate
created_at
stringlengths
20
20
version
stringclasses
2 values
pull_number
int64
1.29k
1.76k
hints_text
stringclasses
5 values
issue_numbers
sequencelengths
1
1
base_commit
stringlengths
40
40
instance_id
stringlengths
17
17
test_patch
stringlengths
557
9.55k
patch
stringlengths
375
39.9k
problem_statement
stringlengths
78
1.88k
repo
stringclasses
1 value
environment_setup_commit
stringclasses
2 values
2024-10-20T06:16:50Z
2.0
1,759
[ "1710" ]
e011ba794aba6aaa0d5c96368bf6cf686581ee96
dtolnay__syn-1759
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index 6c367c944..9f8a418ab 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -25,13 +25,6 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/rustdoc/unsafe-extern-blocks.rs", "tests/ui/rust-2024/unsafe-extern-blocks/safe-items.rs", - // TODO: unsafe attributes: `#[unsafe(path::to)]` - // https://github.com/dtolnay/syn/issues/1710 - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0213_metas.rs", - "src/tools/rustfmt/tests/target/unsafe_attributes.rs", - "tests/ui/attributes/unsafe/unsafe-attributes.rs", - "tests/ui/rust-2024/unsafe-attributes/unsafe-attribute-marked.rs", - // TODO: non-lifetime binders: `where for<'a, T> &'a Struct<T>: Trait` // https://github.com/dtolnay/syn/issues/1435 "src/tools/rustfmt/tests/source/issue_5721.rs",
diff --git a/src/attr.rs b/src/attr.rs index 579452bbf..2bdf96ee7 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -653,6 +653,7 @@ pub(crate) mod parsing { use crate::parse::{Parse, ParseStream}; use crate::path::Path; use crate::{mac, token}; + use proc_macro2::Ident; use std::fmt::{self, Display}; pub(crate) fn parse_inner(input: ParseStream, attrs: &mut Vec<Attribute>) -> Result<()> { @@ -685,7 +686,7 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for Meta { fn parse(input: ParseStream) -> Result<Self> { - let path = input.call(Path::parse_mod_style)?; + let path = parse_outermost_meta_path(input)?; parse_meta_after_path(path, input) } } @@ -693,7 +694,7 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for MetaList { fn parse(input: ParseStream) -> Result<Self> { - let path = input.call(Path::parse_mod_style)?; + let path = parse_outermost_meta_path(input)?; parse_meta_list_after_path(path, input) } } @@ -701,11 +702,22 @@ pub(crate) mod parsing { #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for MetaNameValue { fn parse(input: ParseStream) -> Result<Self> { - let path = input.call(Path::parse_mod_style)?; + let path = parse_outermost_meta_path(input)?; parse_meta_name_value_after_path(path, input) } } + // Unlike meta::parse_meta_path which accepts arbitrary keywords in the path, + // only the `unsafe` keyword is accepted as an attribute's outermost path. + fn parse_outermost_meta_path(input: ParseStream) -> Result<Path> { + if input.peek(Token![unsafe]) { + let unsafe_token: Token![unsafe] = input.parse()?; + Ok(Path::from(Ident::new("unsafe", unsafe_token.span))) + } else { + Path::parse_mod_style(input) + } + } + pub(crate) fn parse_meta_after_path(path: Path, input: ParseStream) -> Result<Meta> { if input.peek(token::Paren) || input.peek(token::Bracket) || input.peek(token::Brace) { parse_meta_list_after_path(path, input).map(Meta::List)
Parse unsafe attributes - https://github.com/rust-lang/rust/issues/123757 - https://github.com/rust-lang/rfcs/pull/3325 ```console error: expected identifier, found keyword `unsafe` --> dev/main.rs:4:3 | 4 | #[unsafe(no_mangle)] | ^^^^^^ ```
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-09-27T18:09:33Z
2.0
1,741
Using 09d020f5, `#[r=6=r..1..]` seems to run into the same problem.
[ "1738" ]
09d020f5a10b3d3e4d54ec03290f773be91b9cac
dtolnay__syn-1741
diff --git a/tests/test_expr.rs b/tests/test_expr.rs index 399972c42..24d36aeb2 100644 --- a/tests/test_expr.rs +++ b/tests/test_expr.rs @@ -646,9 +646,17 @@ fn test_assign_range_precedence() { fn test_chained_comparison() { // https://github.com/dtolnay/syn/issues/1738 let _ = syn::parse_str::<Expr>("a = a < a <"); + let _ = syn::parse_str::<Expr>("a = a .. a .."); + let _ = syn::parse_str::<Expr>("a = a .. a +="); let err = syn::parse_str::<Expr>("a < a < a").unwrap_err(); assert_eq!("comparison operators cannot be chained", err.to_string()); + + let err = syn::parse_str::<Expr>("a .. a .. a").unwrap_err(); + assert_eq!("unexpected token", err.to_string()); + + let err = syn::parse_str::<Expr>("a .. a += a").unwrap_err(); + assert_eq!("unexpected token", err.to_string()); } #[test]
diff --git a/src/expr.rs b/src/expr.rs index 8216191c2..409131b4f 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1390,6 +1390,7 @@ pub(crate) mod parsing { loop { let next = peek_precedence(input); if next > precedence || next == precedence && precedence == Precedence::Assign { + let cursor = input.cursor(); rhs = parse_expr( input, rhs, @@ -1397,10 +1398,18 @@ pub(crate) mod parsing { allow_struct, next, )?; + if cursor == input.cursor() { + // Bespoke grammar restrictions separate from precedence can + // cause parsing to not advance, such as `..a` being + // disallowed in the left-hand side of binary operators, + // even ones that have lower precedence than `..`. + break; + } } else { - return Ok(Box::new(rhs)); + break; } } + Ok(Box::new(rhs)) } fn peek_precedence(input: ParseStream) -> Precedence {
Parsing apparently enters infinite loop Using `syn 2.0.77`, the following reduced examples seems to never return (at least not before I kill it after several minutes). Notice that `2.0.61` returns, while `2.0.62 ..` does not. ```rust fn main() { syn::parse_str::<syn::File>("#[a=a=a<a<]"); } ``` ```rust fn main() { syn::parse_str::<syn::GenericParam>("a=<a<{a=a<a<}"); } ```
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-09-27T17:30:37Z
2.0
1,739
[ "1738" ]
346efaec55d7a3865a42fcd1007f45a8a7549052
dtolnay__syn-1739
diff --git a/tests/test_expr.rs b/tests/test_expr.rs index d20cce8d6..399972c42 100644 --- a/tests/test_expr.rs +++ b/tests/test_expr.rs @@ -642,6 +642,15 @@ fn test_assign_range_precedence() { syn::parse_str::<Expr>("() .. () += ()").unwrap_err(); } +#[test] +fn test_chained_comparison() { + // https://github.com/dtolnay/syn/issues/1738 + let _ = syn::parse_str::<Expr>("a = a < a <"); + + let err = syn::parse_str::<Expr>("a < a < a").unwrap_err(); + assert_eq!("comparison operators cannot be chained", err.to_string()); +} + #[test] fn test_fixup() { struct FlattenParens;
diff --git a/src/expr.rs b/src/expr.rs index db8d5b921..8216191c2 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1284,7 +1284,7 @@ pub(crate) mod parsing { if precedence == Precedence::Compare { if let Expr::Binary(lhs) = &lhs { if Precedence::of_binop(&lhs.op) == Precedence::Compare { - break; + return Err(input.error("comparison operators cannot be chained")); } } } @@ -1346,7 +1346,7 @@ pub(crate) mod parsing { if precedence == Precedence::Compare { if let Expr::Binary(lhs) = &lhs { if Precedence::of_binop(&lhs.op) == Precedence::Compare { - break; + return Err(input.error("comparison operators cannot be chained")); } } }
Parsing apparently enters infinite loop Using `syn 2.0.77`, the following reduced examples seems to never return (at least not before I kill it after several minutes). Notice that `2.0.61` returns, while `2.0.62 ..` does not. ```rust fn main() { syn::parse_str::<syn::File>("#[a=a=a<a<]"); } ``` ```rust fn main() { syn::parse_str::<syn::GenericParam>("a=<a<{a=a<a<}"); } ```
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-08-11T16:18:11Z
2.0
1,719
[ "1718" ]
b5a5a8c17737ac7a7b3553ec202626035bfa779c
dtolnay__syn-1719
diff --git a/tests/test_iterators.rs b/tests/test_iterators.rs index 5f0eff59e..4090bcc8e 100644 --- a/tests/test_iterators.rs +++ b/tests/test_iterators.rs @@ -1,7 +1,7 @@ -#![allow(clippy::uninlined_format_args)] +#![allow(clippy::map_unwrap_or, clippy::uninlined_format_args)] use syn::punctuated::{Pair, Punctuated}; -use syn::Token; +use syn::{parse_quote, GenericParam, Generics, Lifetime, LifetimeParam, Token}; #[macro_use] mod macros; @@ -68,3 +68,22 @@ fn may_dangle() { } } } + +// Regression test for https://github.com/dtolnay/syn/issues/1718 +#[test] +fn no_opaque_drop() { + let mut generics = Generics::default(); + + let _ = generics + .lifetimes() + .next() + .map(|param| param.lifetime.clone()) + .unwrap_or_else(|| { + let lifetime: Lifetime = parse_quote!('a); + generics.params.insert( + 0, + GenericParam::Lifetime(LifetimeParam::new(lifetime.clone())), + ); + lifetime + }); +}
diff --git a/src/data.rs b/src/data.rs index 7f8a121c7..9e73f02d3 100644 --- a/src/data.rs +++ b/src/data.rs @@ -105,80 +105,45 @@ impl Fields { } } - /// Get an iterator over the fields of a struct or variant as [`Member`]s. - /// This iterator can be used to iterate over a named or unnamed struct or - /// variant's fields uniformly. - /// - /// # Example - /// - /// The following is a simplistic [`Clone`] derive for structs. (A more - /// complete implementation would additionally want to infer trait bounds on - /// the generic type parameters.) - /// - /// ``` - /// # use quote::quote; - /// # - /// fn derive_clone(input: &syn::ItemStruct) -> proc_macro2::TokenStream { - /// let ident = &input.ident; - /// let members = input.fields.members(); - /// let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); - /// quote! { - /// impl #impl_generics Clone for #ident #ty_generics #where_clause { - /// fn clone(&self) -> Self { - /// Self { - /// #(#members: self.#members.clone()),* - /// } - /// } - /// } - /// } - /// } - /// ``` - /// - /// For structs with named fields, it produces an expression like `Self { a: - /// self.a.clone() }`. For structs with unnamed fields, `Self { 0: - /// self.0.clone() }`. And for unit structs, `Self {}`. - pub fn members(&self) -> impl Iterator<Item = Member> + Clone + '_ { - struct Members<'a> { - fields: punctuated::Iter<'a, Field>, - index: u32, - } - - impl<'a> Iterator for Members<'a> { - type Item = Member; - - fn next(&mut self) -> Option<Self::Item> { - let field = self.fields.next()?; - let member = match &field.ident { - Some(ident) => Member::Named(ident.clone()), - None => { - #[cfg(all(feature = "parsing", feature = "printing"))] - let span = crate::spanned::Spanned::span(&field.ty); - #[cfg(not(all(feature = "parsing", feature = "printing")))] - let span = proc_macro2::Span::call_site(); - Member::Unnamed(Index { - index: self.index, - span, - }) - } - }; - self.index += 1; - Some(member) - } - } - - impl<'a> Clone for Members<'a> { - fn clone(&self) -> Self { - Members { - fields: self.fields.clone(), - index: self.index, - } + return_impl_trait! { + /// Get an iterator over the fields of a struct or variant as [`Member`]s. + /// This iterator can be used to iterate over a named or unnamed struct or + /// variant's fields uniformly. + /// + /// # Example + /// + /// The following is a simplistic [`Clone`] derive for structs. (A more + /// complete implementation would additionally want to infer trait bounds on + /// the generic type parameters.) + /// + /// ``` + /// # use quote::quote; + /// # + /// fn derive_clone(input: &syn::ItemStruct) -> proc_macro2::TokenStream { + /// let ident = &input.ident; + /// let members = input.fields.members(); + /// let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + /// quote! { + /// impl #impl_generics Clone for #ident #ty_generics #where_clause { + /// fn clone(&self) -> Self { + /// Self { + /// #(#members: self.#members.clone()),* + /// } + /// } + /// } + /// } + /// } + /// ``` + /// + /// For structs with named fields, it produces an expression like `Self { a: + /// self.a.clone() }`. For structs with unnamed fields, `Self { 0: + /// self.0.clone() }`. And for unit structs, `Self {}`. + pub fn members(&self) -> impl Iterator<Item = Member> + Clone + '_ [Members] { + Members { + fields: self.iter(), + index: 0, } } - - Members { - fields: self.iter(), - index: 0, - } } } @@ -234,6 +199,43 @@ ast_struct! { } } +pub struct Members<'a> { + fields: punctuated::Iter<'a, Field>, + index: u32, +} + +impl<'a> Iterator for Members<'a> { + type Item = Member; + + fn next(&mut self) -> Option<Self::Item> { + let field = self.fields.next()?; + let member = match &field.ident { + Some(ident) => Member::Named(ident.clone()), + None => { + #[cfg(all(feature = "parsing", feature = "printing"))] + let span = crate::spanned::Spanned::span(&field.ty); + #[cfg(not(all(feature = "parsing", feature = "printing")))] + let span = proc_macro2::Span::call_site(); + Member::Unnamed(Index { + index: self.index, + span, + }) + } + }; + self.index += 1; + Some(member) + } +} + +impl<'a> Clone for Members<'a> { + fn clone(&self) -> Self { + Members { + fields: self.fields.clone(), + index: self.index, + } + } +} + #[cfg(feature = "parsing")] pub(crate) mod parsing { use crate::attr::Attribute; diff --git a/src/generics.rs b/src/generics.rs index 81542279f..692ad5300 100644 --- a/src/generics.rs +++ b/src/generics.rs @@ -103,142 +103,46 @@ impl Default for Generics { } impl Generics { - /// Iterator over the lifetime parameters in `self.params`. - pub fn lifetimes(&self) -> impl Iterator<Item = &LifetimeParam> { - struct Lifetimes<'a>(Iter<'a, GenericParam>); - - impl<'a> Iterator for Lifetimes<'a> { - type Item = &'a LifetimeParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Lifetime(lifetime) = next { - Some(lifetime) - } else { - self.next() - } - } + return_impl_trait! { + /// Iterator over the lifetime parameters in `self.params`. + pub fn lifetimes(&self) -> impl Iterator<Item = &LifetimeParam> [Lifetimes] { + Lifetimes(self.params.iter()) } - - Lifetimes(self.params.iter()) } - /// Iterator over the lifetime parameters in `self.params`. - pub fn lifetimes_mut(&mut self) -> impl Iterator<Item = &mut LifetimeParam> { - struct LifetimesMut<'a>(IterMut<'a, GenericParam>); - - impl<'a> Iterator for LifetimesMut<'a> { - type Item = &'a mut LifetimeParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Lifetime(lifetime) = next { - Some(lifetime) - } else { - self.next() - } - } + return_impl_trait! { + /// Iterator over the lifetime parameters in `self.params`. + pub fn lifetimes_mut(&mut self) -> impl Iterator<Item = &mut LifetimeParam> [LifetimesMut] { + LifetimesMut(self.params.iter_mut()) } - - LifetimesMut(self.params.iter_mut()) } - /// Iterator over the type parameters in `self.params`. - pub fn type_params(&self) -> impl Iterator<Item = &TypeParam> { - struct TypeParams<'a>(Iter<'a, GenericParam>); - - impl<'a> Iterator for TypeParams<'a> { - type Item = &'a TypeParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Type(type_param) = next { - Some(type_param) - } else { - self.next() - } - } + return_impl_trait! { + /// Iterator over the type parameters in `self.params`. + pub fn type_params(&self) -> impl Iterator<Item = &TypeParam> [TypeParams] { + TypeParams(self.params.iter()) } - - TypeParams(self.params.iter()) } - /// Iterator over the type parameters in `self.params`. - pub fn type_params_mut(&mut self) -> impl Iterator<Item = &mut TypeParam> { - struct TypeParamsMut<'a>(IterMut<'a, GenericParam>); - - impl<'a> Iterator for TypeParamsMut<'a> { - type Item = &'a mut TypeParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Type(type_param) = next { - Some(type_param) - } else { - self.next() - } - } + return_impl_trait! { + /// Iterator over the type parameters in `self.params`. + pub fn type_params_mut(&mut self) -> impl Iterator<Item = &mut TypeParam> [TypeParamsMut] { + TypeParamsMut(self.params.iter_mut()) } - - TypeParamsMut(self.params.iter_mut()) } - /// Iterator over the constant parameters in `self.params`. - pub fn const_params(&self) -> impl Iterator<Item = &ConstParam> { - struct ConstParams<'a>(Iter<'a, GenericParam>); - - impl<'a> Iterator for ConstParams<'a> { - type Item = &'a ConstParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Const(const_param) = next { - Some(const_param) - } else { - self.next() - } - } + return_impl_trait! { + /// Iterator over the constant parameters in `self.params`. + pub fn const_params(&self) -> impl Iterator<Item = &ConstParam> [ConstParams] { + ConstParams(self.params.iter()) } - - ConstParams(self.params.iter()) } - /// Iterator over the constant parameters in `self.params`. - pub fn const_params_mut(&mut self) -> impl Iterator<Item = &mut ConstParam> { - struct ConstParamsMut<'a>(IterMut<'a, GenericParam>); - - impl<'a> Iterator for ConstParamsMut<'a> { - type Item = &'a mut ConstParam; - - fn next(&mut self) -> Option<Self::Item> { - let next = match self.0.next() { - Some(item) => item, - None => return None, - }; - if let GenericParam::Const(const_param) = next { - Some(const_param) - } else { - self.next() - } - } + return_impl_trait! { + /// Iterator over the constant parameters in `self.params`. + pub fn const_params_mut(&mut self) -> impl Iterator<Item = &mut ConstParam> [ConstParamsMut] { + ConstParamsMut(self.params.iter_mut()) } - - ConstParamsMut(self.params.iter_mut()) } /// Initializes an empty `where`-clause if there is not one present already. @@ -278,6 +182,114 @@ impl Generics { } } +pub struct Lifetimes<'a>(Iter<'a, GenericParam>); + +impl<'a> Iterator for Lifetimes<'a> { + type Item = &'a LifetimeParam; + + fn next(&mut self) -> Option<Self::Item> { + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Lifetime(lifetime) = next { + Some(lifetime) + } else { + self.next() + } + } +} + +pub struct LifetimesMut<'a>(IterMut<'a, GenericParam>); + +impl<'a> Iterator for LifetimesMut<'a> { + type Item = &'a mut LifetimeParam; + + fn next(&mut self) -> Option<Self::Item> { + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Lifetime(lifetime) = next { + Some(lifetime) + } else { + self.next() + } + } +} + +pub struct TypeParams<'a>(Iter<'a, GenericParam>); + +impl<'a> Iterator for TypeParams<'a> { + type Item = &'a TypeParam; + + fn next(&mut self) -> Option<Self::Item> { + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Type(type_param) = next { + Some(type_param) + } else { + self.next() + } + } +} + +pub struct TypeParamsMut<'a>(IterMut<'a, GenericParam>); + +impl<'a> Iterator for TypeParamsMut<'a> { + type Item = &'a mut TypeParam; + + fn next(&mut self) -> Option<Self::Item> { + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Type(type_param) = next { + Some(type_param) + } else { + self.next() + } + } +} + +pub struct ConstParams<'a>(Iter<'a, GenericParam>); + +impl<'a> Iterator for ConstParams<'a> { + type Item = &'a ConstParam; + + fn next(&mut self) -> Option<Self::Item> { + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Const(const_param) = next { + Some(const_param) + } else { + self.next() + } + } +} + +pub struct ConstParamsMut<'a>(IterMut<'a, GenericParam>); + +impl<'a> Iterator for ConstParamsMut<'a> { + type Item = &'a mut ConstParam; + + fn next(&mut self) -> Option<Self::Item> { + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Const(const_param) = next { + Some(const_param) + } else { + self.next() + } + } +} + /// Returned by `Generics::split_for_impl`. #[cfg(feature = "printing")] #[cfg_attr( diff --git a/src/macros.rs b/src/macros.rs index 2b6708d49..167f2cf26 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -164,3 +164,19 @@ macro_rules! check_keyword_matches { (pub pub) => {}; (struct struct) => {}; } + +#[cfg(any(feature = "full", feature = "derive"))] +macro_rules! return_impl_trait { + ( + $(#[$attr:meta])* + $vis:vis fn $name:ident $args:tt -> $impl_trait:ty [$concrete:ty] $body:block + ) => { + #[cfg(not(docsrs))] + $(#[$attr])* + $vis fn $name $args -> $concrete $body + + #[cfg(docsrs)] + $(#[$attr])* + $vis fn $name $args -> $impl_trait $body + }; +}
Breaking change to `Generics::lifetimes` in v2.0.73 The following (contrived extraction from `der_derive`, see https://github.com/RustCrypto/formats/issues/1471) compiles with `syn` v2.0.72 but not with v2.0.73: ```rust use syn::{Generics, GenericParam, Lifetime, LifetimeParam}; use proc_macro2::Span; pub fn process_generics(mut generics: Generics) { let _lifetime = generics .lifetimes() .next() .map(|lt| lt.lifetime.clone()) .unwrap_or_else(|| { let lt = Lifetime::new("'__default", Span::call_site()); generics .params .insert(0, GenericParam::Lifetime(LifetimeParam::new(lt.clone()))); lt }); } ``` It looks like it now assumes there could be a `Drop` impl where before it knew the concrete `Lifetimes` type did not have one: ``` error[E0502]: cannot borrow `generics.params` as mutable because it is also borrowed as immutable --> src/main.rs:9:25 | 5 | let _lifetime = generics | -------- | | | _____________________immutable borrow occurs here | | 6 | | .lifetimes() | |____________________- a temporary with access to the immutable borrow is created here ... ... 9 | .unwrap_or_else(|| { | ^^ mutable borrow occurs here 10 | let lt = Lifetime::new("'__default", Span::call_site()); 11 | / generics 12 | | .params | |_______________________- second borrow occurs due to use of `generics.params` in closure ... 15 | }); | - ... and the immutable borrow might be used here, when that temporary is dropped and runs the destructor for type `impl Iterator<Item = &LifetimeParam>` ``` The culprit seems to be ac9e1dd.
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-07-22T01:04:17Z
2.0
1,714
[ "1501" ]
4132a0ca1e80251460d947e0b34145cdced9043b
dtolnay__syn-1714
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index d7a1f5dc1..6c367c944 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -32,19 +32,6 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/attributes/unsafe/unsafe-attributes.rs", "tests/ui/rust-2024/unsafe-attributes/unsafe-attribute-marked.rs", - // TODO: explicit tail calls: `become _g()` - // https://github.com/dtolnay/syn/issues/1501 - "src/tools/miri/tests/fail/tail_calls/cc-mismatch.rs", - "src/tools/miri/tests/fail/tail_calls/signature-mismatch-arg.rs", - "src/tools/miri/tests/pass/tail_call.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0209_become_expr.rs", - "tests/mir-opt/tail_call_drops.rs", - "tests/ui/explicit-tail-calls/ctfe-arg-good-borrow.rs", - "tests/ui/explicit-tail-calls/ctfe-arg-move.rs", - "tests/ui/explicit-tail-calls/ctfe-collatz-multi-rec.rs", - "tests/ui/explicit-tail-calls/drop-order.rs", - "tests/ui/explicit-tail-calls/return-lifetime-sub.rs", - // TODO: non-lifetime binders: `where for<'a, T> &'a Struct<T>: Trait` // https://github.com/dtolnay/syn/issues/1435 "src/tools/rustfmt/tests/source/issue_5721.rs", diff --git a/tests/test_precedence.rs b/tests/test_precedence.rs index 07f913948..99c935f24 100644 --- a/tests/test_precedence.rs +++ b/tests/test_precedence.rs @@ -238,7 +238,7 @@ fn librustc_parenthesize(mut librustc_expr: P<ast::Expr>) -> P<ast::Expr> { fn noop_visit_expr<T: MutVisitor>(e: &mut Expr, vis: &mut T) { match &mut e.kind { - ExprKind::AddrOf(BorrowKind::Raw, ..) => {} + ExprKind::AddrOf(BorrowKind::Raw, ..) | ExprKind::Become(..) => {} ExprKind::Struct(expr) => { let StructExpr { qself,
diff --git a/src/expr.rs b/src/expr.rs index 62ebdad85..8e1e461d8 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1741,6 +1741,8 @@ pub(crate) mod parsing { input.parse().map(Expr::Continue) } else if input.peek(Token![return]) { input.parse().map(Expr::Return) + } else if input.peek(Token![become]) { + expr_become(input) } else if input.peek(token::Bracket) { array_or_repeat(input) } else if input.peek(Token![let]) { @@ -2393,6 +2395,16 @@ pub(crate) mod parsing { } } + #[cfg(feature = "full")] + fn expr_become(input: ParseStream) -> Result<Expr> { + let begin = input.fork(); + input.parse::<Token![become]>()?; + if can_begin_expr(input) { + input.parse::<Expr>()?; + } + Ok(Expr::Verbatim(verbatim::between(&begin, input))) + } + #[cfg(feature = "full")] #[cfg_attr(docsrs, doc(cfg(feature = "parsing")))] impl Parse for ExprTryBlock {
Parse explicit tail call syntax https://github.com/rust-lang/rust/pull/112887
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-07-22T00:11:13Z
2.0
1,712
[ "1711" ]
431784b90890e1f0c858b87e0339e27d853047ce
dtolnay__syn-1712
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index 4a774ff0a..d7a1f5dc1 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -32,10 +32,6 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/attributes/unsafe/unsafe-attributes.rs", "tests/ui/rust-2024/unsafe-attributes/unsafe-attribute-marked.rs", - // TODO: vararg in function pointer type: `extern fn(_: *mut _, _: ...)` - // https://github.com/dtolnay/syn/issues/1711 - "library/std/src/sys/pal/uefi/helpers.rs", - // TODO: explicit tail calls: `become _g()` // https://github.com/dtolnay/syn/issues/1501 "src/tools/miri/tests/fail/tail_calls/cc-mismatch.rs",
diff --git a/src/ty.rs b/src/ty.rs index fa9870e5a..a1543be05 100644 --- a/src/ty.rs +++ b/src/ty.rs @@ -669,7 +669,7 @@ pub(crate) mod parsing { if inputs.empty_or_trailing() && (args.peek(Token![...]) - || args.peek(Ident) + || (args.peek(Ident) || args.peek(Token![_])) && args.peek2(Token![:]) && args.peek3(Token![...])) {
Parse unnamed C varargs within function pointer types ```console error: expected one of: `for`, parentheses, `fn`, `unsafe`, `extern`, identifier, `::`, `<`, `dyn`, square brackets, `*`, `&`, `!`, `impl`, `_`, lifetime --> library/std/src/sys/pal/uefi/helpers.rs:24:103 | 24 | type BootInstallMultipleProtocolInterfaces = unsafe extern "efiapi" fn(_: *mut r_efi::efi::Handle, _: ...) -> r_efi::efi::Status; | ^ ```
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-05-16T06:34:39Z
2.0
1,662
[ "1527" ]
f4641931718f41ab0a81c173d8e4fc1f38fe772e
dtolnay__syn-1662
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index 4419b0d35..c8400288d 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -58,10 +58,6 @@ static EXCLUDE_FILES: &[&str] = &[ "tests/ui/higher-ranked/builtin-closure-like-bounds.rs", "tests/ui/sanitizer/cfi-coroutine.rs", - // TODO: struct literal in match guard - // https://github.com/dtolnay/syn/issues/1527 - "tests/ui/parser/struct-literal-in-match-guard.rs", - // TODO: `!` as a pattern // https://github.com/dtolnay/syn/issues/1546 "tests/ui/rfcs/rfc-0000-never_patterns/diverges.rs",
diff --git a/src/expr.rs b/src/expr.rs index 6a1e92dbc..8c8193e84 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1744,7 +1744,7 @@ pub(crate) mod parsing { } else if input.peek(token::Bracket) { array_or_repeat(input) } else if input.peek(Token![let]) { - input.parse().map(Expr::Let) + expr_let(input, allow_struct).map(Expr::Let) } else if input.peek(Token![if]) { input.parse().map(Expr::If) } else if input.peek(Token![while]) { @@ -2117,20 +2117,25 @@ pub(crate) mod parsing { #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprLet { fn parse(input: ParseStream) -> Result<Self> { - Ok(ExprLet { - attrs: Vec::new(), - let_token: input.parse()?, - pat: Box::new(Pat::parse_multi_with_leading_vert(input)?), - eq_token: input.parse()?, - expr: Box::new({ - let allow_struct = AllowStruct(false); - let lhs = unary_expr(input, allow_struct)?; - parse_expr(input, lhs, allow_struct, Precedence::Compare)? - }), - }) + let allow_struct = AllowStruct(false); + expr_let(input, allow_struct) } } + #[cfg(feature = "full")] + fn expr_let(input: ParseStream, allow_struct: AllowStruct) -> Result<ExprLet> { + Ok(ExprLet { + attrs: Vec::new(), + let_token: input.parse()?, + pat: Box::new(Pat::parse_multi_with_leading_vert(input)?), + eq_token: input.parse()?, + expr: Box::new({ + let lhs = unary_expr(input, allow_struct)?; + parse_expr(input, lhs, allow_struct, Precedence::Compare)? + }), + }) + } + #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ExprIf {
Parse struct literals in match guards Unlike `if` condition, `match` guards accept struct literals. Syn currently fails to parse it. ```rust #![feature(if_let_guard)] #[derive(PartialEq)] struct Foo { x: isize, } fn foo(f: Foo) { match () { () if f == Foo { x: 42 } => {} () if let Foo { x: 0.. } = Foo { x: 42 } => {} _ => {} } } ``` ```console error: expected `=>` --> dev/main.rs:11:40 | 11 | () if let Foo { x: 0.. } = Foo { x: 42 } => {} | ^ ``` Tracking issue: https://github.com/rust-lang/rust/issues/51114
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2024-04-15T00:54:08Z
2.0
1,622
Blocked on https://github.com/rust-lang/rust/issues/112820. Blocker appears to be resolved and `c"..."` and `cr"..."` string literals are stabilized in 1.77 `cbindgen` is not working with this now due to lack of support in syn
[ "1502" ]
121258603d22d60a0f419521ba5148f099b21405
dtolnay__syn-1622
diff --git a/tests/debug/gen.rs b/tests/debug/gen.rs index 1548d8b6b..9f726683a 100644 --- a/tests/debug/gen.rs +++ b/tests/debug/gen.rs @@ -2864,6 +2864,7 @@ impl Debug for Lite<syn::Lit> { match &self.value { syn::Lit::Str(_val) => write!(formatter, "{:?}", _val.value()), syn::Lit::ByteStr(_val) => write!(formatter, "{:?}", _val.value()), + syn::Lit::CStr(_val) => write!(formatter, "{:?}", _val.value()), syn::Lit::Byte(_val) => write!(formatter, "{:?}", _val.value()), syn::Lit::Char(_val) => write!(formatter, "{:?}", _val.value()), syn::Lit::Int(_val) => write!(formatter, "{}", _val), @@ -2901,6 +2902,11 @@ impl Debug for Lite<syn::LitByteStr> { write!(formatter, "{:?}", self.value.value()) } } +impl Debug for Lite<syn::LitCStr> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{:?}", self.value.value()) + } +} impl Debug for Lite<syn::LitChar> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "{:?}", self.value.value()) diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index 420cda694..cff69c26b 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -17,12 +17,6 @@ const REVISION: &str = "b10cfcd65fd7f7b1ab9beb34798b2108de003452"; #[rustfmt::skip] static EXCLUDE_FILES: &[&str] = &[ - // TODO: CStr literals: c"…", cr"…" - // https://github.com/dtolnay/syn/issues/1502 - "src/tools/clippy/tests/ui/needless_raw_string.rs", - "src/tools/clippy/tests/ui/needless_raw_string_hashes.rs", - "src/tools/rust-analyzer/crates/parser/test_data/parser/inline/ok/0085_expr_literals.rs", - // TODO: explicit tail calls: `become _g()` // https://github.com/dtolnay/syn/issues/1501 "tests/ui/explicit-tail-calls/return-lifetime-sub.rs", diff --git a/tests/test_lit.rs b/tests/test_lit.rs index 1d43999e8..07a6080da 100644 --- a/tests/test_lit.rs +++ b/tests/test_lit.rs @@ -11,6 +11,7 @@ mod macros; use proc_macro2::{Delimiter, Group, Literal, Span, TokenStream, TokenTree}; use quote::ToTokens; +use std::ffi::CStr; use std::str::FromStr; use syn::{Lit, LitFloat, LitInt, LitStr}; @@ -101,6 +102,45 @@ fn byte_strings() { test_byte_string("br##\"...\"##q", b"..."); } +#[test] +fn c_strings() { + #[track_caller] + fn test_c_string(s: &str, value: &CStr) { + let s = s.trim(); + match lit(s) { + Lit::CStr(lit) => { + assert_eq!(*lit.value(), *value); + let again = lit.into_token_stream().to_string(); + if again != s { + test_c_string(&again, value); + } + } + wrong => panic!("{:?}", wrong), + } + } + + test_c_string(r#" c"" "#, c""); + test_c_string(r#" c"a" "#, c"a"); + test_c_string(r#" c"\n" "#, c"\n"); + test_c_string(r#" c"\r" "#, c"\r"); + test_c_string(r#" c"\t" "#, c"\t"); + test_c_string(r#" c"\\" "#, c"\\"); + test_c_string(r#" c"\'" "#, c"'"); + test_c_string(r#" c"\"" "#, c"\""); + test_c_string( + "c\"contains\nnewlines\\\nescaped newlines\"", + c"contains\nnewlinesescaped newlines", + ); + test_c_string("cr\"raw\nstring\\\nhere\"", c"raw\nstring\\\nhere"); + test_c_string("c\"...\"q", c"..."); + test_c_string("cr\"...\"", c"..."); + test_c_string("cr##\"...\"##", c"..."); + test_c_string( + r#" c"hello\x80我叫\u{1F980}" "#, // from the RFC + c"hello\x80我叫\u{1F980}", + ); +} + #[test] fn bytes() { #[track_caller] @@ -242,6 +282,7 @@ fn suffix() { match lit { Lit::Str(lit) => lit.suffix().to_owned(), Lit::ByteStr(lit) => lit.suffix().to_owned(), + Lit::CStr(lit) => lit.suffix().to_owned(), Lit::Byte(lit) => lit.suffix().to_owned(), Lit::Char(lit) => lit.suffix().to_owned(), Lit::Int(lit) => lit.suffix().to_owned(), @@ -256,6 +297,9 @@ fn suffix() { assert_eq!(get_suffix("b\"\"b"), "b"); assert_eq!(get_suffix("br\"\"br"), "br"); assert_eq!(get_suffix("br#\"\"#br"), "br"); + assert_eq!(get_suffix("c\"\"c"), "c"); + assert_eq!(get_suffix("cr\"\"cr"), "cr"); + assert_eq!(get_suffix("cr#\"\"#cr"), "cr"); assert_eq!(get_suffix("'c'c"), "c"); assert_eq!(get_suffix("b'b'b"), "b"); assert_eq!(get_suffix("1i32"), "i32");
diff --git a/Cargo.toml b/Cargo.toml index def141422..e3b83601b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,7 +35,7 @@ proc-macro = ["proc-macro2/proc-macro", "quote?/proc-macro"] test = ["syn-test-suite/all-features"] [dependencies] -proc-macro2 = { version = "1.0.75", default-features = false } +proc-macro2 = { version = "1.0.80", default-features = false } quote = { version = "1.0.35", optional = true, default-features = false } unicode-ident = "1" diff --git a/src/gen/clone.rs b/src/gen/clone.rs index 3313d4db2..c4007a738 100644 --- a/src/gen/clone.rs +++ b/src/gen/clone.rs @@ -1338,6 +1338,7 @@ impl Clone for crate::Lit { match self { crate::Lit::Str(v0) => crate::Lit::Str(v0.clone()), crate::Lit::ByteStr(v0) => crate::Lit::ByteStr(v0.clone()), + crate::Lit::CStr(v0) => crate::Lit::CStr(v0.clone()), crate::Lit::Byte(v0) => crate::Lit::Byte(v0.clone()), crate::Lit::Char(v0) => crate::Lit::Char(v0.clone()), crate::Lit::Int(v0) => crate::Lit::Int(v0.clone()), diff --git a/src/gen/debug.rs b/src/gen/debug.rs index 2dc531ead..9db611484 100644 --- a/src/gen/debug.rs +++ b/src/gen/debug.rs @@ -1958,6 +1958,7 @@ impl Debug for crate::Lit { match self { crate::Lit::Str(v0) => v0.debug(formatter, "Str"), crate::Lit::ByteStr(v0) => v0.debug(formatter, "ByteStr"), + crate::Lit::CStr(v0) => v0.debug(formatter, "CStr"), crate::Lit::Byte(v0) => v0.debug(formatter, "Byte"), crate::Lit::Char(v0) => v0.debug(formatter, "Char"), crate::Lit::Int(v0) => v0.debug(formatter, "Int"), diff --git a/src/gen/eq.rs b/src/gen/eq.rs index 9bfce5f2a..555c48b95 100644 --- a/src/gen/eq.rs +++ b/src/gen/eq.rs @@ -1300,6 +1300,7 @@ impl PartialEq for crate::Lit { match (self, other) { (crate::Lit::Str(self0), crate::Lit::Str(other0)) => self0 == other0, (crate::Lit::ByteStr(self0), crate::Lit::ByteStr(other0)) => self0 == other0, + (crate::Lit::CStr(self0), crate::Lit::CStr(other0)) => self0 == other0, (crate::Lit::Byte(self0), crate::Lit::Byte(other0)) => self0 == other0, (crate::Lit::Char(self0), crate::Lit::Char(other0)) => self0 == other0, (crate::Lit::Int(self0), crate::Lit::Int(other0)) => self0 == other0, @@ -1325,6 +1326,8 @@ impl Eq for crate::LitByte {} #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Eq for crate::LitByteStr {} #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for crate::LitCStr {} +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Eq for crate::LitChar {} #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Eq for crate::LitFloat {} diff --git a/src/gen/fold.rs b/src/gen/fold.rs index 872ffe10e..ec2aed49d 100644 --- a/src/gen/fold.rs +++ b/src/gen/fold.rs @@ -581,6 +581,9 @@ pub trait Fold { fn fold_lit_byte_str(&mut self, i: crate::LitByteStr) -> crate::LitByteStr { fold_lit_byte_str(self, i) } + fn fold_lit_cstr(&mut self, i: crate::LitCStr) -> crate::LitCStr { + fold_lit_cstr(self, i) + } fn fold_lit_char(&mut self, i: crate::LitChar) -> crate::LitChar { fold_lit_char(self, i) } @@ -2628,6 +2631,7 @@ where crate::Lit::ByteStr(_binding_0) => { crate::Lit::ByteStr(f.fold_lit_byte_str(_binding_0)) } + crate::Lit::CStr(_binding_0) => crate::Lit::CStr(f.fold_lit_cstr(_binding_0)), crate::Lit::Byte(_binding_0) => crate::Lit::Byte(f.fold_lit_byte(_binding_0)), crate::Lit::Char(_binding_0) => crate::Lit::Char(f.fold_lit_char(_binding_0)), crate::Lit::Int(_binding_0) => crate::Lit::Int(f.fold_lit_int(_binding_0)), @@ -2663,6 +2667,15 @@ where node.set_span(span); node } +pub fn fold_lit_cstr<F>(f: &mut F, node: crate::LitCStr) -> crate::LitCStr +where + F: Fold + ?Sized, +{ + let span = f.fold_span(node.span()); + let mut node = node; + node.set_span(span); + node +} pub fn fold_lit_char<F>(f: &mut F, node: crate::LitChar) -> crate::LitChar where F: Fold + ?Sized, diff --git a/src/gen/hash.rs b/src/gen/hash.rs index 7ead139c3..54d8fe25d 100644 --- a/src/gen/hash.rs +++ b/src/gen/hash.rs @@ -1682,28 +1682,32 @@ impl Hash for crate::Lit { state.write_u8(1u8); v0.hash(state); } - crate::Lit::Byte(v0) => { + crate::Lit::CStr(v0) => { state.write_u8(2u8); v0.hash(state); } - crate::Lit::Char(v0) => { + crate::Lit::Byte(v0) => { state.write_u8(3u8); v0.hash(state); } - crate::Lit::Int(v0) => { + crate::Lit::Char(v0) => { state.write_u8(4u8); v0.hash(state); } - crate::Lit::Float(v0) => { + crate::Lit::Int(v0) => { state.write_u8(5u8); v0.hash(state); } - crate::Lit::Bool(v0) => { + crate::Lit::Float(v0) => { state.write_u8(6u8); v0.hash(state); } - crate::Lit::Verbatim(v0) => { + crate::Lit::Bool(v0) => { state.write_u8(7u8); + v0.hash(state); + } + crate::Lit::Verbatim(v0) => { + state.write_u8(8u8); v0.to_string().hash(state); } } diff --git a/src/gen/visit.rs b/src/gen/visit.rs index 5d87e63f7..8da25c87c 100644 --- a/src/gen/visit.rs +++ b/src/gen/visit.rs @@ -547,6 +547,9 @@ pub trait Visit<'ast> { fn visit_lit_byte_str(&mut self, i: &'ast crate::LitByteStr) { visit_lit_byte_str(self, i); } + fn visit_lit_cstr(&mut self, i: &'ast crate::LitCStr) { + visit_lit_cstr(self, i); + } fn visit_lit_char(&mut self, i: &'ast crate::LitChar) { visit_lit_char(self, i); } @@ -2694,6 +2697,9 @@ where crate::Lit::ByteStr(_binding_0) => { v.visit_lit_byte_str(_binding_0); } + crate::Lit::CStr(_binding_0) => { + v.visit_lit_cstr(_binding_0); + } crate::Lit::Byte(_binding_0) => { v.visit_lit_byte(_binding_0); } @@ -2729,6 +2735,10 @@ pub fn visit_lit_byte_str<'ast, V>(v: &mut V, node: &'ast crate::LitByteStr) where V: Visit<'ast> + ?Sized, {} +pub fn visit_lit_cstr<'ast, V>(v: &mut V, node: &'ast crate::LitCStr) +where + V: Visit<'ast> + ?Sized, +{} pub fn visit_lit_char<'ast, V>(v: &mut V, node: &'ast crate::LitChar) where V: Visit<'ast> + ?Sized, diff --git a/src/gen/visit_mut.rs b/src/gen/visit_mut.rs index f35fc099a..06345a53c 100644 --- a/src/gen/visit_mut.rs +++ b/src/gen/visit_mut.rs @@ -548,6 +548,9 @@ pub trait VisitMut { fn visit_lit_byte_str_mut(&mut self, i: &mut crate::LitByteStr) { visit_lit_byte_str_mut(self, i); } + fn visit_lit_cstr_mut(&mut self, i: &mut crate::LitCStr) { + visit_lit_cstr_mut(self, i); + } fn visit_lit_char_mut(&mut self, i: &mut crate::LitChar) { visit_lit_char_mut(self, i); } @@ -2694,6 +2697,9 @@ where crate::Lit::ByteStr(_binding_0) => { v.visit_lit_byte_str_mut(_binding_0); } + crate::Lit::CStr(_binding_0) => { + v.visit_lit_cstr_mut(_binding_0); + } crate::Lit::Byte(_binding_0) => { v.visit_lit_byte_mut(_binding_0); } @@ -2729,6 +2735,10 @@ pub fn visit_lit_byte_str_mut<V>(v: &mut V, node: &mut crate::LitByteStr) where V: VisitMut + ?Sized, {} +pub fn visit_lit_cstr_mut<V>(v: &mut V, node: &mut crate::LitCStr) +where + V: VisitMut + ?Sized, +{} pub fn visit_lit_char_mut<V>(v: &mut V, node: &mut crate::LitChar) where V: VisitMut + ?Sized, diff --git a/src/lib.rs b/src/lib.rs index af04ffc1c..5be5b0a9c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -418,7 +418,9 @@ mod lit; #[doc(hidden)] // https://github.com/dtolnay/syn/issues/1566 pub use crate::lit::StrStyle; #[doc(inline)] -pub use crate::lit::{Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr}; +pub use crate::lit::{ + Lit, LitBool, LitByte, LitByteStr, LitCStr, LitChar, LitFloat, LitInt, LitStr, +}; #[cfg(feature = "parsing")] mod lookahead; diff --git a/src/lit.rs b/src/lit.rs index bb88016ac..aa95020dc 100644 --- a/src/lit.rs +++ b/src/lit.rs @@ -6,6 +6,7 @@ use crate::{Error, Result}; use proc_macro2::{Ident, Literal, Span}; #[cfg(feature = "parsing")] use proc_macro2::{TokenStream, TokenTree}; +use std::ffi::{CStr, CString}; use std::fmt::{self, Display}; #[cfg(feature = "extra-traits")] use std::hash::{Hash, Hasher}; @@ -27,6 +28,9 @@ ast_enum_of_structs! { /// A byte string literal: `b"foo"`. ByteStr(LitByteStr), + /// A nul-terminated C-string literal: `c"foo"`. + CStr(LitCStr), + /// A byte literal: `b'f'`. Byte(LitByte), @@ -63,6 +67,13 @@ ast_struct! { } } +ast_struct! { + /// A nul-terminated C-string literal: `c"foo"`. + pub struct LitCStr { + repr: Box<LitRepr>, + } +} + ast_struct! { /// A byte literal: `b'f'`. pub struct LitByte { @@ -294,6 +305,41 @@ impl LitByteStr { } } +impl LitCStr { + pub fn new(value: &CStr, span: Span) -> Self { + let mut token = Literal::c_string(value); + token.set_span(span); + LitCStr { + repr: Box::new(LitRepr { + token, + suffix: Box::<str>::default(), + }), + } + } + + pub fn value(&self) -> CString { + let repr = self.repr.token.to_string(); + let (value, _suffix) = value::parse_lit_c_str(&repr); + value + } + + pub fn span(&self) -> Span { + self.repr.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.repr.token.set_span(span); + } + + pub fn suffix(&self) -> &str { + &self.repr.suffix + } + + pub fn token(&self) -> Literal { + self.repr.token.clone() + } +} + impl LitByte { pub fn new(value: u8, span: Span) -> Self { let mut token = Literal::u8_suffixed(value); @@ -555,7 +601,7 @@ impl LitBool { #[cfg(feature = "extra-traits")] mod debug_impls { - use crate::lit::{LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr}; + use crate::lit::{LitBool, LitByte, LitByteStr, LitCStr, LitChar, LitFloat, LitInt, LitStr}; use std::fmt::{self, Debug}; #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] @@ -590,6 +636,22 @@ mod debug_impls { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] + impl Debug for LitCStr { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.debug(formatter, "LitCStr") + } + } + + impl LitCStr { + pub(crate) fn debug(&self, formatter: &mut fmt::Formatter, name: &str) -> fmt::Result { + formatter + .debug_struct(name) + .field("token", &format_args!("{}", self.repr.token)) + .finish() + } + } + #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for LitByte { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { @@ -750,6 +812,7 @@ macro_rules! lit_extra_traits { lit_extra_traits!(LitStr); lit_extra_traits!(LitByteStr); +lit_extra_traits!(LitCStr); lit_extra_traits!(LitByte); lit_extra_traits!(LitChar); lit_extra_traits!(LitInt); @@ -790,7 +853,7 @@ pub(crate) mod parsing { use crate::buffer::Cursor; use crate::error::Result; use crate::lit::{ - value, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitFloatRepr, LitInt, + value, Lit, LitBool, LitByte, LitByteStr, LitCStr, LitChar, LitFloat, LitFloatRepr, LitInt, LitIntRepr, LitStr, }; use crate::parse::{Parse, ParseStream}; @@ -889,6 +952,17 @@ pub(crate) mod parsing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] + impl Parse for LitCStr { + fn parse(input: ParseStream) -> Result<Self> { + let head = input.fork(); + match input.parse() { + Ok(Lit::CStr(lit)) => Ok(lit), + _ => Err(head.error("expected C string literal")), + } + } + } + #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for LitByte { fn parse(input: ParseStream) -> Result<Self> { @@ -947,7 +1021,7 @@ pub(crate) mod parsing { #[cfg(feature = "printing")] mod printing { - use crate::lit::{LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitInt, LitStr}; + use crate::lit::{LitBool, LitByte, LitByteStr, LitCStr, LitChar, LitFloat, LitInt, LitStr}; use proc_macro2::TokenStream; use quote::{ToTokens, TokenStreamExt}; @@ -965,6 +1039,13 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for LitCStr { + fn to_tokens(&self, tokens: &mut TokenStream) { + self.repr.token.to_tokens(tokens); + } + } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for LitByte { fn to_tokens(&self, tokens: &mut TokenStream) { @@ -1004,12 +1085,13 @@ mod printing { mod value { use crate::bigint::BigInt; use crate::lit::{ - Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, LitFloatRepr, LitInt, LitIntRepr, - LitRepr, LitStr, + Lit, LitBool, LitByte, LitByteStr, LitCStr, LitChar, LitFloat, LitFloatRepr, LitInt, + LitIntRepr, LitRepr, LitStr, }; use proc_macro2::{Literal, Span}; use std::ascii; use std::char; + use std::ffi::CString; use std::ops::{Index, RangeFrom}; impl Lit { @@ -1042,6 +1124,13 @@ mod value { } _ => {} }, + // c"...", cr"...", cr#"..."# + b'c' => { + let (_, suffix) = parse_lit_c_str(&repr); + return Lit::CStr(LitCStr { + repr: Box::new(LitRepr { token, suffix }), + }); + } // '...' b'\'' => { let (_, suffix) = parse_lit_char(&repr); @@ -1080,9 +1169,6 @@ mod value { }); } } - // c"...", cr"...", cr#"..."# - // TODO: add a Lit::CStr variant? - b'c' => return Lit::Verbatim(token), b'(' if repr == "(/*ERROR*/)" => return Lit::Verbatim(token), _ => {} } @@ -1094,6 +1180,7 @@ mod value { match self { Lit::Str(lit) => lit.suffix(), Lit::ByteStr(lit) => lit.suffix(), + Lit::CStr(lit) => lit.suffix(), Lit::Byte(lit) => lit.suffix(), Lit::Char(lit) => lit.suffix(), Lit::Int(lit) => lit.suffix(), @@ -1106,6 +1193,7 @@ mod value { match self { Lit::Str(lit) => lit.span(), Lit::ByteStr(lit) => lit.span(), + Lit::CStr(lit) => lit.span(), Lit::Byte(lit) => lit.span(), Lit::Char(lit) => lit.span(), Lit::Int(lit) => lit.span(), @@ -1119,6 +1207,7 @@ mod value { match self { Lit::Str(lit) => lit.set_span(span), Lit::ByteStr(lit) => lit.set_span(span), + Lit::CStr(lit) => lit.set_span(span), Lit::Byte(lit) => lit.set_span(span), Lit::Char(lit) => lit.set_span(span), Lit::Int(lit) => lit.set_span(span), @@ -1317,6 +1406,92 @@ mod value { (String::from(value).into_bytes(), suffix) } + // Returns (content, suffix). + pub(crate) fn parse_lit_c_str(s: &str) -> (CString, Box<str>) { + assert_eq!(byte(s, 0), b'c'); + match byte(s, 1) { + b'"' => parse_lit_c_str_cooked(s), + b'r' => parse_lit_c_str_raw(s), + _ => unreachable!(), + } + } + + // Clippy false positive + // https://github.com/rust-lang-nursery/rust-clippy/issues/2329 + #[allow(clippy::needless_continue)] + fn parse_lit_c_str_cooked(mut s: &str) -> (CString, Box<str>) { + assert_eq!(byte(s, 0), b'c'); + assert_eq!(byte(s, 1), b'"'); + s = &s[2..]; + + // We're going to want to have slices which don't respect codepoint boundaries. + let mut v = s.as_bytes(); + + let mut out = Vec::new(); + 'outer: loop { + let byte = match byte(v, 0) { + b'"' => break, + b'\\' => { + let b = byte(v, 1); + v = &v[2..]; + match b { + b'x' => { + let (b, rest) = backslash_x(v); + assert!(b != 0, "\\x00 is not allowed in C-string literal"); + v = rest; + b + } + b'u' => { + let (ch, rest) = backslash_u(v); + assert!(ch != '\0', "\\u{{0}} is not allowed in C-string literal"); + v = rest; + out.extend_from_slice(ch.encode_utf8(&mut [0u8; 4]).as_bytes()); + continue 'outer; + } + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'\\' => b'\\', + b'\'' => b'\'', + b'"' => b'"', + b'\r' | b'\n' => loop { + let byte = byte(v, 0); + if matches!(byte, b' ' | b'\t' | b'\n' | b'\r') { + v = &v[1..]; + } else { + continue 'outer; + } + }, + b => panic!( + "unexpected byte '{}' after \\ character in byte literal", + ascii::escape_default(b), + ), + } + } + b'\r' => { + assert_eq!(byte(v, 1), b'\n', "bare CR not allowed in string"); + v = &v[2..]; + b'\n' + } + b => { + v = &v[1..]; + b + } + }; + out.push(byte); + } + + assert_eq!(byte(v, 0), b'"'); + let suffix = s[s.len() - v.len() + 1..].to_owned().into_boxed_str(); + (CString::new(out).unwrap(), suffix) + } + + fn parse_lit_c_str_raw(s: &str) -> (CString, Box<str>) { + assert_eq!(byte(s, 0), b'c'); + let (value, suffix) = parse_lit_str_raw(&s[1..]); + (CString::new(String::from(value)).unwrap(), suffix) + } + // Returns (value, suffix). pub(crate) fn parse_lit_byte(s: &str) -> (u8, Box<str>) { assert_eq!(byte(s, 0), b'b'); @@ -1427,7 +1602,10 @@ mod value { (ch, &s[2..]) } - fn backslash_u(mut s: &str) -> (char, &str) { + fn backslash_u<S>(mut s: &S) -> (char, &S) + where + S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized, + { if byte(s, 0) != b'{' { panic!("{}", "expected { after \\u"); } diff --git a/syn.json b/syn.json index c8918179c..db31b0292 100644 --- a/syn.json +++ b/syn.json @@ -3366,6 +3366,11 @@ "syn": "LitByteStr" } ], + "CStr": [ + { + "syn": "LitCStr" + } + ], "Byte": [ { "syn": "LitByte" @@ -3425,6 +3430,12 @@ "any": [] } }, + { + "ident": "LitCStr", + "features": { + "any": [] + } + }, { "ident": "LitChar", "features": {
Parse `c"…"` and `cr"…"` string literals RFC: https://github.com/rust-lang/rfcs/pull/3348 Tracking issue: https://github.com/rust-lang/rust/issues/105723
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2023-11-06T00:51:53Z
2.0
1,530
[ "1528" ]
c6a651aa12447d50c22db3189ef38cff90fc267b
dtolnay__syn-1530
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index aa385a1d4..9d5dfa2f7 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -56,10 +56,6 @@ static EXCLUDE_FILES: &[&str] = &[ // https://github.com/dtolnay/syn/issues/1527 "tests/ui/parser/struct-literal-in-match-guard.rs", - // TODO: precedence of return in match guard - // https://github.com/dtolnay/syn/issues/1528 - "tests/ui/unreachable-code.rs", - // Compile-fail expr parameter in const generic position: f::<1 + 2>() "tests/ui/const-generics/early/closing-args-token.rs", "tests/ui/const-generics/early/const-expression-parameter.rs",
diff --git a/src/expr.rs b/src/expr.rs index 1988b544f..2c0b346f2 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -957,6 +957,8 @@ pub(crate) fn requires_terminator(expr: &Expr) -> bool { #[cfg(feature = "parsing")] pub(crate) mod parsing { use super::*; + #[cfg(feature = "full")] + use crate::ext::IdentExt; use crate::parse::discouraged::Speculative; #[cfg(feature = "full")] use crate::parse::ParseBuffer; @@ -1155,6 +1157,25 @@ pub(crate) mod parsing { } } + #[cfg(feature = "full")] + fn can_begin_expr(input: ParseStream) -> bool { + input.peek(Ident::peek_any) // value name or keyword + || input.peek(token::Paren) // tuple + || input.peek(token::Bracket) // array + || input.peek(token::Brace) // block + || input.peek(Lit) // literal + || input.peek(Token![!]) && !input.peek(Token![!=]) // operator not + || input.peek(Token![-]) && !input.peek(Token![-=]) && !input.peek(Token![->]) // unary minus + || input.peek(Token![*]) && !input.peek(Token![*=]) // dereference + || input.peek(Token![|]) && !input.peek(Token![|=]) // closure + || input.peek(Token![&]) && !input.peek(Token![&=]) // reference + || input.peek(Token![..]) // range notation + || input.peek(Token![<]) && !input.peek(Token![<=]) && !input.peek(Token![<<=]) // associated path + || input.peek(Token![::]) // global path + || input.peek(Lifetime) // labeled loop + || input.peek(Token![#]) // expression attributes + } + #[cfg(feature = "full")] fn parse_expr( input: ParseStream, @@ -2247,7 +2268,7 @@ pub(crate) mod parsing { attrs: Vec::new(), yield_token: input.parse()?, expr: { - if !input.is_empty() && !input.peek(Token![,]) && !input.peek(Token![;]) { + if can_begin_expr(input) { Some(input.parse()?) } else { None @@ -2447,15 +2468,11 @@ pub(crate) mod parsing { break_token: input.parse()?, label: input.parse()?, expr: { - if input.is_empty() - || input.peek(Token![,]) - || input.peek(Token![;]) - || !allow_struct.0 && input.peek(token::Brace) - { - None - } else { + if can_begin_expr(input) && (allow_struct.0 || !input.peek(token::Brace)) { let expr = ambiguous_expr(input, allow_struct)?; Some(Box::new(expr)) + } else { + None } }, }) @@ -2467,9 +2484,7 @@ pub(crate) mod parsing { attrs: Vec::new(), return_token: input.parse()?, expr: { - if input.is_empty() || input.peek(Token![,]) || input.peek(Token![;]) { - None - } else { + if can_begin_expr(input) { // NOTE: return is greedy and eats blocks after it even when in a // position where structs are not allowed, such as in if statement // conditions. For example: @@ -2477,6 +2492,8 @@ pub(crate) mod parsing { // if return { println!("A") } {} // Prints "A" let expr = ambiguous_expr(input, allow_struct)?; Some(Box::new(expr)) + } else { + None } }, })
Fix `return` precedence in match guard With `feature(if_let_guard)`, the following is valid Rust syntax. ```rust fn ret_guard() { match 2 { x if let true = return => { x; } _ => {} } } ``` Syn currently fails to parse it: ```console error: expected an expression --> dev/main.rs:3:30 | 3 | x if let true = return => { x; } | ^ ``` Tracking issue: https://github.com/rust-lang/rust/issues/51114
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2023-09-03T05:45:53Z
2.0
1,499
[ "1497" ]
78f94eac59ceb2d37fa3bbb86fc8769c9833f0c5
dtolnay__syn-1499
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index 8ae1ae2d4..980a85470 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -17,16 +17,6 @@ const REVISION: &str = "9f5fc1bd443f59583e7af0d94d289f95fe1e20c4"; #[rustfmt::skip] static EXCLUDE_FILES: &[&str] = &[ - // TODO: generic const items - // https://github.com/dtolnay/syn/issues/1497 - "tests/rustdoc/generic-const-items.rs", - "tests/rustdoc/inline_cross/auxiliary/generic-const-items.rs", - "tests/ui/generic-const-items/associated-const-equality.rs", - "tests/ui/generic-const-items/basic.rs", - "tests/ui/generic-const-items/recursive.rs", - "tests/ui/object-safety/assoc_const_bounds.rs", - "tests/ui/object-safety/assoc_const_bounds_sized.rs", - // CStr literals (c"…") are not yet supported by rustc's lexer // https://github.com/rust-lang/rust/issues/113333 "src/tools/clippy/tests/ui/needless_raw_string_hashes.rs",
diff --git a/src/item.rs b/src/item.rs index 50d7e6ef6..39a5f4cd1 100644 --- a/src/item.rs +++ b/src/item.rs @@ -985,23 +985,28 @@ pub(crate) mod parsing { } else { return Err(lookahead.error()); }; + let mut generics: Generics = input.parse()?; let colon_token = input.parse()?; let ty = input.parse()?; if input.peek(Token![;]) { input.parse::<Token![;]>()?; Ok(Item::Verbatim(verbatim::between(&begin, input))) } else { + let eq_token: Token![=] = input.parse()?; + let expr: Expr = input.parse()?; + generics.where_clause = input.parse()?; + let semi_token: Token![;] = input.parse()?; Ok(Item::Const(ItemConst { attrs: Vec::new(), vis, const_token, ident, - generics: Generics::default(), + generics, colon_token, ty, - eq_token: input.parse()?, - expr: input.parse()?, - semi_token: input.parse()?, + eq_token, + expr: Box::new(expr), + semi_token, })) } } else if lookahead.peek(Token![unsafe]) { @@ -1400,24 +1405,36 @@ pub(crate) mod parsing { #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ItemConst { fn parse(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + let const_token: Token![const] = input.parse()?; + + let lookahead = input.lookahead1(); + let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.call(Ident::parse_any)? + } else { + return Err(lookahead.error()); + }; + + let mut generics: Generics = input.parse()?; + let colon_token: Token![:] = input.parse()?; + let ty: Type = input.parse()?; + let eq_token: Token![=] = input.parse()?; + let expr: Expr = input.parse()?; + generics.where_clause = input.parse()?; + let semi_token: Token![;] = input.parse()?; + Ok(ItemConst { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - const_token: input.parse()?, - ident: { - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) || lookahead.peek(Token![_]) { - input.call(Ident::parse_any)? - } else { - return Err(lookahead.error()); - } - }, - generics: Generics::default(), - colon_token: input.parse()?, - ty: input.parse()?, - eq_token: input.parse()?, - expr: input.parse()?, - semi_token: input.parse()?, + attrs, + vis, + const_token, + ident, + generics, + colon_token, + ty: Box::new(ty), + eq_token, + expr: Box::new(expr), + semi_token, }) } } @@ -2273,30 +2290,38 @@ pub(crate) mod parsing { #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for TraitItemConst { fn parse(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; + let const_token: Token![const] = input.parse()?; + + let lookahead = input.lookahead1(); + let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.call(Ident::parse_any)? + } else { + return Err(lookahead.error()); + }; + + let mut generics: Generics = input.parse()?; + let colon_token: Token![:] = input.parse()?; + let ty: Type = input.parse()?; + let default = if input.peek(Token![=]) { + let eq_token: Token![=] = input.parse()?; + let default: Expr = input.parse()?; + Some((eq_token, default)) + } else { + None + }; + generics.where_clause = input.parse()?; + let semi_token: Token![;] = input.parse()?; + Ok(TraitItemConst { - attrs: input.call(Attribute::parse_outer)?, - const_token: input.parse()?, - ident: { - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) || lookahead.peek(Token![_]) { - input.call(Ident::parse_any)? - } else { - return Err(lookahead.error()); - } - }, - generics: Generics::default(), - colon_token: input.parse()?, - ty: input.parse()?, - default: { - if input.peek(Token![=]) { - let eq_token: Token![=] = input.parse()?; - let default: Expr = input.parse()?; - Some((eq_token, default)) - } else { - None - } - }, - semi_token: input.parse()?, + attrs, + const_token, + ident, + generics, + colon_token, + ty, + default, + semi_token, }) } } @@ -2550,23 +2575,28 @@ pub(crate) mod parsing { } else { return Err(lookahead.error()); }; + let mut generics: Generics = input.parse()?; let colon_token: Token![:] = input.parse()?; let ty: Type = input.parse()?; if let Some(eq_token) = input.parse()? { + let expr: Expr = input.parse()?; + generics.where_clause = input.parse()?; + let semi_token: Token![;] = input.parse()?; return Ok(ImplItem::Const(ImplItemConst { attrs, vis, defaultness, const_token, ident, - generics: Generics::default(), + generics, colon_token, ty, eq_token, - expr: input.parse()?, - semi_token: input.parse()?, + expr, + semi_token, })); } else { + input.parse::<Option<WhereClause>>()?; input.parse::<Token![;]>()?; return Ok(ImplItem::Verbatim(verbatim::between(&begin, input))); } @@ -2604,25 +2634,38 @@ pub(crate) mod parsing { #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for ImplItemConst { fn parse(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + let defaultness: Option<Token![default]> = input.parse()?; + let const_token: Token![const] = input.parse()?; + + let lookahead = input.lookahead1(); + let ident = if lookahead.peek(Ident) || lookahead.peek(Token![_]) { + input.call(Ident::parse_any)? + } else { + return Err(lookahead.error()); + }; + + let mut generics: Generics = input.parse()?; + let colon_token: Token![:] = input.parse()?; + let ty: Type = input.parse()?; + let eq_token: Token![=] = input.parse()?; + let expr: Expr = input.parse()?; + generics.where_clause = input.parse()?; + let semi_token: Token![;] = input.parse()?; + Ok(ImplItemConst { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, - defaultness: input.parse()?, - const_token: input.parse()?, - ident: { - let lookahead = input.lookahead1(); - if lookahead.peek(Ident) || lookahead.peek(Token![_]) { - input.call(Ident::parse_any)? - } else { - return Err(lookahead.error()); - } - }, - generics: Generics::default(), - colon_token: input.parse()?, - ty: input.parse()?, - eq_token: input.parse()?, - expr: input.parse()?, - semi_token: input.parse()?, + attrs, + vis, + defaultness, + const_token, + ident, + generics, + colon_token, + ty, + eq_token, + expr, + semi_token, }) } } @@ -2834,10 +2877,12 @@ mod printing { self.vis.to_tokens(tokens); self.const_token.to_tokens(tokens); self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); self.colon_token.to_tokens(tokens); self.ty.to_tokens(tokens); self.eq_token.to_tokens(tokens); self.expr.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); self.semi_token.to_tokens(tokens); } } @@ -3084,12 +3129,14 @@ mod printing { tokens.append_all(self.attrs.outer()); self.const_token.to_tokens(tokens); self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); self.colon_token.to_tokens(tokens); self.ty.to_tokens(tokens); if let Some((eq_token, default)) = &self.default { eq_token.to_tokens(tokens); default.to_tokens(tokens); } + self.generics.where_clause.to_tokens(tokens); self.semi_token.to_tokens(tokens); } } @@ -3150,10 +3197,12 @@ mod printing { self.defaultness.to_tokens(tokens); self.const_token.to_tokens(tokens); self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); self.colon_token.to_tokens(tokens); self.ty.to_tokens(tokens); self.eq_token.to_tokens(tokens); self.expr.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); self.semi_token.to_tokens(tokens); } }
Parse generic const items Tracking issue for experimental feature (no RFC): https://github.com/rust-lang/rust/issues/113521 ```rust pub const K<'a, T: 'a + Copy, const N: usize>: Option<[T; N]> = None where String: From<T>; ```
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2023-09-03T04:52:02Z
2.0
1,498
Gonna block this on https://github.com/rust-lang/rust/issues/88583.
[ "1049" ]
face31f20f166d19d61c702d237d51f755f89ad8
dtolnay__syn-1498
diff --git a/tests/repo/mod.rs b/tests/repo/mod.rs index 0c61f4abe..8ae1ae2d4 100644 --- a/tests/repo/mod.rs +++ b/tests/repo/mod.rs @@ -17,10 +17,6 @@ const REVISION: &str = "9f5fc1bd443f59583e7af0d94d289f95fe1e20c4"; #[rustfmt::skip] static EXCLUDE_FILES: &[&str] = &[ - // TODO: anonymous union and struct - // https://github.com/dtolnay/syn/issues/1049 - "src/tools/rustfmt/tests/target/anonymous-types.rs", - // TODO: generic const items // https://github.com/dtolnay/syn/issues/1497 "tests/rustdoc/generic-const-items.rs",
diff --git a/src/data.rs b/src/data.rs index 185f88ba0..431c0857d 100644 --- a/src/data.rs +++ b/src/data.rs @@ -214,17 +214,37 @@ pub(crate) mod parsing { /// Parses a named (braced struct) field. #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] pub fn parse_named(input: ParseStream) -> Result<Self> { + let attrs = input.call(Attribute::parse_outer)?; + let vis: Visibility = input.parse()?; + + let unnamed_field = cfg!(feature = "full") && input.peek(Token![_]); + let ident = if unnamed_field { + input.call(Ident::parse_any) + } else { + input.parse() + }?; + + let colon_token: Token![:] = input.parse()?; + + let ty: Type = if unnamed_field + && (input.peek(Token![struct]) + || input.peek(Token![union]) && input.peek2(token::Brace)) + { + let begin = input.fork(); + input.call(Ident::parse_any)?; + input.parse::<FieldsNamed>()?; + Type::Verbatim(verbatim::between(&begin, input)) + } else { + input.parse()? + }; + Ok(Field { - attrs: input.call(Attribute::parse_outer)?, - vis: input.parse()?, + attrs, + vis, mutability: FieldMutability::None, - ident: Some(if input.peek(Token![_]) { - input.call(Ident::parse_any) - } else { - input.parse() - }?), - colon_token: Some(input.parse()?), - ty: input.parse()?, + ident: Some(ident), + colon_token: Some(colon_token), + ty, }) }
Parse unnamed struct/union type Part of RFC 2102. - RFC: https://github.com/rust-lang/rfcs/pull/2102 - Tracking issue: https://github.com/rust-lang/rust/issues/49804 - Example usage: https://github.com/rust-lang/rust/blob/e3c71f1e33b026dea7c9ca7c1c4554e63f56a0da/src/test/pretty/anonymous-types.rs ```rust type A = struct { field: u8 }; ```
dtolnay/syn
e011ba794aba6aaa0d5c96368bf6cf686581ee96
2023-02-06T05:29:00Z
1.0
1,372
[ "1352" ]
b7b288a0cb569a8e0c175ee675939929c5f3f202
dtolnay__syn-1372
diff --git a/tests/debug/gen.rs b/tests/debug/gen.rs index fb58c4bf9..eee1e6009 100644 --- a/tests/debug/gen.rs +++ b/tests/debug/gen.rs @@ -3134,6 +3134,14 @@ impl Debug for Lite<syn::Pat> { } formatter.finish() } + syn::Pat::Paren(_val) => { + let mut formatter = formatter.debug_struct("Pat::Paren"); + if !_val.attrs.is_empty() { + formatter.field("attrs", Lite(&_val.attrs)); + } + formatter.field("pat", Lite(&_val.pat)); + formatter.finish() + } syn::Pat::Path(_val) => { formatter.write_str("Pat::Path")?; formatter.write_str("(")?; @@ -3322,6 +3330,16 @@ impl Debug for Lite<syn::PatOr> { formatter.finish() } } +impl Debug for Lite<syn::PatParen> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("PatParen"); + if !self.value.attrs.is_empty() { + formatter.field("attrs", Lite(&self.value.attrs)); + } + formatter.field("pat", Lite(&self.value.pat)); + formatter.finish() + } +} impl Debug for Lite<syn::PatReference> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let mut formatter = formatter.debug_struct("PatReference");
diff --git a/src/expr.rs b/src/expr.rs index b240f47b7..67ddb90c5 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -2308,6 +2308,7 @@ pub(crate) mod parsing { Pat::Lit(pat) => pat.attrs = attrs, Pat::Macro(pat) => pat.attrs = attrs, Pat::Or(pat) => pat.attrs = attrs, + Pat::Paren(pat) => pat.attrs = attrs, Pat::Path(pat) => pat.attrs = attrs, Pat::Range(pat) => pat.attrs = attrs, Pat::Reference(pat) => pat.attrs = attrs, diff --git a/src/gen/clone.rs b/src/gen/clone.rs index d373e5af9..4f0c8418f 100644 --- a/src/gen/clone.rs +++ b/src/gen/clone.rs @@ -1461,6 +1461,7 @@ impl Clone for Pat { Pat::Lit(v0) => Pat::Lit(v0.clone()), Pat::Macro(v0) => Pat::Macro(v0.clone()), Pat::Or(v0) => Pat::Or(v0.clone()), + Pat::Paren(v0) => Pat::Paren(v0.clone()), Pat::Path(v0) => Pat::Path(v0.clone()), Pat::Range(v0) => Pat::Range(v0.clone()), Pat::Reference(v0) => Pat::Reference(v0.clone()), @@ -1501,6 +1502,17 @@ impl Clone for PatOr { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for PatParen { + fn clone(&self) -> Self { + PatParen { + attrs: self.attrs.clone(), + paren_token: self.paren_token.clone(), + pat: self.pat.clone(), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] impl Clone for PatReference { fn clone(&self) -> Self { PatReference { diff --git a/src/gen/debug.rs b/src/gen/debug.rs index b0932da2f..408a1168d 100644 --- a/src/gen/debug.rs +++ b/src/gen/debug.rs @@ -2076,6 +2076,7 @@ impl Debug for Pat { formatter.finish() } Pat::Or(v0) => v0.debug(formatter, "Or"), + Pat::Paren(v0) => v0.debug(formatter, "Paren"), Pat::Path(v0) => { let mut formatter = formatter.debug_tuple("Path"); formatter.field(v0); @@ -2138,6 +2139,22 @@ impl Debug for PatOr { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for PatParen { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + impl PatParen { + fn debug(&self, formatter: &mut fmt::Formatter, name: &str) -> fmt::Result { + let mut formatter = formatter.debug_struct(name); + formatter.field("attrs", &self.attrs); + formatter.field("paren_token", &self.paren_token); + formatter.field("pat", &self.pat); + formatter.finish() + } + } + self.debug(formatter, "PatParen") + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for PatReference { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { impl PatReference { diff --git a/src/gen/eq.rs b/src/gen/eq.rs index ccfdbdb89..9149747d2 100644 --- a/src/gen/eq.rs +++ b/src/gen/eq.rs @@ -1393,6 +1393,7 @@ impl PartialEq for Pat { (Pat::Lit(self0), Pat::Lit(other0)) => self0 == other0, (Pat::Macro(self0), Pat::Macro(other0)) => self0 == other0, (Pat::Or(self0), Pat::Or(other0)) => self0 == other0, + (Pat::Paren(self0), Pat::Paren(other0)) => self0 == other0, (Pat::Path(self0), Pat::Path(other0)) => self0 == other0, (Pat::Range(self0), Pat::Range(other0)) => self0 == other0, (Pat::Reference(self0), Pat::Reference(other0)) => self0 == other0, @@ -1435,6 +1436,16 @@ impl PartialEq for PatOr { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for PatParen {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for PatParen { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.pat == other.pat + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Eq for PatReference {} #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] diff --git a/src/gen/fold.rs b/src/gen/fold.rs index c3806185c..0b9958d80 100644 --- a/src/gen/fold.rs +++ b/src/gen/fold.rs @@ -512,6 +512,10 @@ pub trait Fold { fold_pat_or(self, i) } #[cfg(feature = "full")] + fn fold_pat_paren(&mut self, i: PatParen) -> PatParen { + fold_pat_paren(self, i) + } + #[cfg(feature = "full")] fn fold_pat_reference(&mut self, i: PatReference) -> PatReference { fold_pat_reference(self, i) } @@ -2443,6 +2447,7 @@ where Pat::Lit(_binding_0) => Pat::Lit(f.fold_expr_lit(_binding_0)), Pat::Macro(_binding_0) => Pat::Macro(f.fold_expr_macro(_binding_0)), Pat::Or(_binding_0) => Pat::Or(f.fold_pat_or(_binding_0)), + Pat::Paren(_binding_0) => Pat::Paren(f.fold_pat_paren(_binding_0)), Pat::Path(_binding_0) => Pat::Path(f.fold_expr_path(_binding_0)), Pat::Range(_binding_0) => Pat::Range(f.fold_expr_range(_binding_0)), Pat::Reference(_binding_0) => Pat::Reference(f.fold_pat_reference(_binding_0)), @@ -2488,6 +2493,17 @@ where } } #[cfg(feature = "full")] +pub fn fold_pat_paren<F>(f: &mut F, node: PatParen) -> PatParen +where + F: Fold + ?Sized, +{ + PatParen { + attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), + paren_token: Paren(tokens_helper(f, &node.paren_token.span)), + pat: Box::new(f.fold_pat(*node.pat)), + } +} +#[cfg(feature = "full")] pub fn fold_pat_reference<F>(f: &mut F, node: PatReference) -> PatReference where F: Fold + ?Sized, diff --git a/src/gen/hash.rs b/src/gen/hash.rs index 780308418..1f545615b 100644 --- a/src/gen/hash.rs +++ b/src/gen/hash.rs @@ -1864,48 +1864,52 @@ impl Hash for Pat { state.write_u8(4u8); v0.hash(state); } - Pat::Path(v0) => { + Pat::Paren(v0) => { state.write_u8(5u8); v0.hash(state); } - Pat::Range(v0) => { + Pat::Path(v0) => { state.write_u8(6u8); v0.hash(state); } - Pat::Reference(v0) => { + Pat::Range(v0) => { state.write_u8(7u8); v0.hash(state); } - Pat::Rest(v0) => { + Pat::Reference(v0) => { state.write_u8(8u8); v0.hash(state); } - Pat::Slice(v0) => { + Pat::Rest(v0) => { state.write_u8(9u8); v0.hash(state); } - Pat::Struct(v0) => { + Pat::Slice(v0) => { state.write_u8(10u8); v0.hash(state); } - Pat::Tuple(v0) => { + Pat::Struct(v0) => { state.write_u8(11u8); v0.hash(state); } - Pat::TupleStruct(v0) => { + Pat::Tuple(v0) => { state.write_u8(12u8); v0.hash(state); } - Pat::Type(v0) => { + Pat::TupleStruct(v0) => { state.write_u8(13u8); v0.hash(state); } - Pat::Verbatim(v0) => { + Pat::Type(v0) => { state.write_u8(14u8); + v0.hash(state); + } + Pat::Verbatim(v0) => { + state.write_u8(15u8); TokenStreamHelper(v0).hash(state); } Pat::Wild(v0) => { - state.write_u8(15u8); + state.write_u8(16u8); v0.hash(state); } } @@ -1939,6 +1943,17 @@ impl Hash for PatOr { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for PatParen { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.pat.hash(state); + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for PatReference { fn hash<H>(&self, state: &mut H) where diff --git a/src/gen/visit.rs b/src/gen/visit.rs index 26a65b56d..5a0d02906 100644 --- a/src/gen/visit.rs +++ b/src/gen/visit.rs @@ -514,6 +514,10 @@ pub trait Visit<'ast> { visit_pat_or(self, i); } #[cfg(feature = "full")] + fn visit_pat_paren(&mut self, i: &'ast PatParen) { + visit_pat_paren(self, i); + } + #[cfg(feature = "full")] fn visit_pat_reference(&mut self, i: &'ast PatReference) { visit_pat_reference(self, i); } @@ -2733,6 +2737,9 @@ where Pat::Or(_binding_0) => { v.visit_pat_or(_binding_0); } + Pat::Paren(_binding_0) => { + v.visit_pat_paren(_binding_0); + } Pat::Path(_binding_0) => { v.visit_expr_path(_binding_0); } @@ -2808,6 +2815,17 @@ where } } #[cfg(feature = "full")] +pub fn visit_pat_paren<'ast, V>(v: &mut V, node: &'ast PatParen) +where + V: Visit<'ast> + ?Sized, +{ + for it in &node.attrs { + v.visit_attribute(it); + } + tokens_helper(v, &node.paren_token.span); + v.visit_pat(&*node.pat); +} +#[cfg(feature = "full")] pub fn visit_pat_reference<'ast, V>(v: &mut V, node: &'ast PatReference) where V: Visit<'ast> + ?Sized, diff --git a/src/gen/visit_mut.rs b/src/gen/visit_mut.rs index 976f2bcc1..e5cb61591 100644 --- a/src/gen/visit_mut.rs +++ b/src/gen/visit_mut.rs @@ -515,6 +515,10 @@ pub trait VisitMut { visit_pat_or_mut(self, i); } #[cfg(feature = "full")] + fn visit_pat_paren_mut(&mut self, i: &mut PatParen) { + visit_pat_paren_mut(self, i); + } + #[cfg(feature = "full")] fn visit_pat_reference_mut(&mut self, i: &mut PatReference) { visit_pat_reference_mut(self, i); } @@ -2736,6 +2740,9 @@ where Pat::Or(_binding_0) => { v.visit_pat_or_mut(_binding_0); } + Pat::Paren(_binding_0) => { + v.visit_pat_paren_mut(_binding_0); + } Pat::Path(_binding_0) => { v.visit_expr_path_mut(_binding_0); } @@ -2811,6 +2818,17 @@ where } } #[cfg(feature = "full")] +pub fn visit_pat_paren_mut<V>(v: &mut V, node: &mut PatParen) +where + V: VisitMut + ?Sized, +{ + for it in &mut node.attrs { + v.visit_attribute_mut(it); + } + tokens_helper(v, &mut node.paren_token.span); + v.visit_pat_mut(&mut *node.pat); +} +#[cfg(feature = "full")] pub fn visit_pat_reference_mut<V>(v: &mut V, node: &mut PatReference) where V: VisitMut + ?Sized, diff --git a/src/lib.rs b/src/lib.rs index 5fbc1695f..9afeca7bd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -442,7 +442,7 @@ pub use crate::expr::{ }; #[cfg(feature = "full")] pub use crate::pat::{ - FieldPat, Pat, PatIdent, PatOr, PatReference, PatRest, PatSlice, PatStruct, PatTuple, + FieldPat, Pat, PatIdent, PatOr, PatParen, PatReference, PatRest, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatType, PatWild, }; diff --git a/src/pat.rs b/src/pat.rs index 3bce02681..56336f82c 100644 --- a/src/pat.rs +++ b/src/pat.rs @@ -29,6 +29,9 @@ ast_enum_of_structs! { /// A pattern that matches any one of a set of cases. Or(PatOr), + /// A parenthesized pattern: `(A | B)`. + Paren(PatParen), + /// A path pattern like `Color::Red`, optionally qualified with a /// self-type. /// @@ -112,6 +115,15 @@ ast_struct! { } } +ast_struct! { + /// A parenthesized pattern: `(A | B)`. + pub struct PatParen { + pub attrs: Vec<Attribute>, + pub paren_token: token::Paren, + pub pat: Box<Pat>, + } +} + ast_struct! { /// A reference pattern: `&mut var`. #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] @@ -283,7 +295,7 @@ pub(crate) mod parsing { } else if lookahead.peek(Token![&]) { input.call(pat_reference).map(Pat::Reference) } else if lookahead.peek(token::Paren) { - input.call(pat_tuple).map(Pat::Tuple) + input.call(pat_paren_or_tuple) } else if lookahead.peek(token::Bracket) { input.call(pat_slice).map(Pat::Slice) } else if lookahead.peek(Token![..]) && !input.peek(Token![...]) { @@ -450,7 +462,20 @@ pub(crate) mod parsing { qself: Option<QSelf>, path: Path, ) -> Result<PatTupleStruct> { - let (paren_token, elems) = pat_tuple_elements(input)?; + let content; + let paren_token = parenthesized!(content in input); + + let mut elems = Punctuated::new(); + while !content.is_empty() { + let value = Pat::parse_multi_with_leading_vert(&content)?; + elems.push_value(value); + if content.is_empty() { + break; + } + let punct = content.parse()?; + elems.push_punct(punct); + } + Ok(PatTupleStruct { attrs: Vec::new(), qself, @@ -588,33 +613,34 @@ pub(crate) mod parsing { } } - fn pat_tuple(input: ParseStream) -> Result<PatTuple> { - let (paren_token, elems) = pat_tuple_elements(input)?; - Ok(PatTuple { - attrs: Vec::new(), - paren_token, - elems, - }) - } - - fn pat_tuple_elements( - input: ParseStream, - ) -> Result<(token::Paren, Punctuated<Pat, Token![,]>)> { + fn pat_paren_or_tuple(input: ParseStream) -> Result<Pat> { let content; let paren_token = parenthesized!(content in input); let mut elems = Punctuated::new(); while !content.is_empty() { let value = Pat::parse_multi_with_leading_vert(&content)?; - elems.push_value(value); if content.is_empty() { + if elems.is_empty() && !matches!(value, Pat::Rest(_)) { + return Ok(Pat::Paren(PatParen { + attrs: Vec::new(), + paren_token, + pat: Box::new(value), + })); + } + elems.push_value(value); break; } + elems.push_value(value); let punct = content.parse()?; elems.push_punct(punct); } - Ok((paren_token, elems)) + Ok(Pat::Tuple(PatTuple { + attrs: Vec::new(), + paren_token, + elems, + })) } fn pat_reference(input: ParseStream) -> Result<PatReference> { @@ -765,6 +791,16 @@ mod printing { } } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for PatParen { + fn to_tokens(&self, tokens: &mut TokenStream) { + tokens.append_all(self.attrs.outer()); + self.paren_token.surround(tokens, |tokens| { + self.pat.to_tokens(tokens); + }); + } + } + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for PatReference { fn to_tokens(&self, tokens: &mut TokenStream) { diff --git a/syn.json b/syn.json index 6babac558..ef37ba655 100644 --- a/syn.json +++ b/syn.json @@ -3697,6 +3697,11 @@ "syn": "PatOr" } ], + "Paren": [ + { + "syn": "PatParen" + } + ], "Path": [ { "syn": "ExprPath" @@ -3825,6 +3830,29 @@ } } }, + { + "ident": "PatParen", + "features": { + "any": [ + "full" + ] + }, + "fields": { + "attrs": { + "vec": { + "syn": "Attribute" + } + }, + "paren_token": { + "group": "Paren" + }, + "pat": { + "box": { + "syn": "Pat" + } + } + } + }, { "ident": "PatReference", "features": {
Arm group in @ binding mis-parsed as tuple In this example ``` fn main() { match x { v @ (A::B | A::A) => (), } } ``` `(A :: B | A :: A)` gets parsed as a `Pat::Tuple` but this is a distinct element that I _think_ only can appear in match statements with at bindings and may not contain commas.
dtolnay/syn
b7b288a0cb569a8e0c175ee675939929c5f3f202
2023-01-23T21:37:05Z
1.0
1,324
[ "1193" ]
1ec86a22a0ffd7526fee811d56faa231f22b81dd
dtolnay__syn-1324
diff --git a/tests/debug/gen.rs b/tests/debug/gen.rs index 92a163340..46c971e5c 100644 --- a/tests/debug/gen.rs +++ b/tests/debug/gen.rs @@ -4522,9 +4522,52 @@ impl Debug for Lite<syn::Stmt> { }); formatter.finish() } + syn::Stmt::Macro(_val) => { + let mut formatter = formatter.debug_struct("Stmt::Macro"); + if !_val.attrs.is_empty() { + formatter.field("attrs", Lite(&_val.attrs)); + } + formatter.field("mac", Lite(&_val.mac)); + if let Some(val) = &_val.semi_token { + #[derive(RefCast)] + #[repr(transparent)] + struct Print(syn::token::Semi); + impl Debug for Print { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Some")?; + Ok(()) + } + } + formatter.field("semi_token", Print::ref_cast(val)); + } + formatter.finish() + } } } } +impl Debug for Lite<syn::StmtMacro> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let _val = &self.value; + let mut formatter = formatter.debug_struct("StmtMacro"); + if !_val.attrs.is_empty() { + formatter.field("attrs", Lite(&_val.attrs)); + } + formatter.field("mac", Lite(&_val.mac)); + if let Some(val) = &_val.semi_token { + #[derive(RefCast)] + #[repr(transparent)] + struct Print(syn::token::Semi); + impl Debug for Print { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Some")?; + Ok(()) + } + } + formatter.field("semi_token", Print::ref_cast(val)); + } + formatter.finish() + } +} impl Debug for Lite<syn::TraitBound> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; diff --git a/tests/test_stmt.rs b/tests/test_stmt.rs index 88a1f450f..04de300e4 100644 --- a/tests/test_stmt.rs +++ b/tests/test_stmt.rs @@ -155,3 +155,88 @@ fn test_let_else() { }) "###); } + +#[test] +fn test_macros() { + let tokens = quote! { + fn main() { + macro_rules! mac {} + thread_local! { static FOO } + println!(""); + vec![] + } + }; + + snapshot!(tokens as Stmt, @r###" + Item(Item::Fn { + vis: Inherited, + sig: Signature { + ident: "main", + generics: Generics, + output: Default, + }, + block: Block { + stmts: [ + Item(Item::Macro { + ident: Some("mac"), + mac: Macro { + path: Path { + segments: [ + PathSegment { + ident: "macro_rules", + arguments: None, + }, + ], + }, + delimiter: Brace, + tokens: TokenStream(``), + }, + }), + Stmt::Macro { + mac: Macro { + path: Path { + segments: [ + PathSegment { + ident: "thread_local", + arguments: None, + }, + ], + }, + delimiter: Brace, + tokens: TokenStream(`static FOO`), + }, + }, + Stmt::Macro { + mac: Macro { + path: Path { + segments: [ + PathSegment { + ident: "println", + arguments: None, + }, + ], + }, + delimiter: Paren, + tokens: TokenStream(`""`), + }, + semi_token: Some, + }, + Stmt::Macro { + mac: Macro { + path: Path { + segments: [ + PathSegment { + ident: "vec", + arguments: None, + }, + ], + }, + delimiter: Bracket, + tokens: TokenStream(``), + }, + }, + ], + }, + }) + "###); +}
diff --git a/src/gen/clone.rs b/src/gen/clone.rs index 81675f49a..627abf7c7 100644 --- a/src/gen/clone.rs +++ b/src/gen/clone.rs @@ -1694,6 +1694,18 @@ impl Clone for Stmt { Stmt::Local(v0) => Stmt::Local(v0.clone()), Stmt::Item(v0) => Stmt::Item(v0.clone()), Stmt::Expr(v0, v1) => Stmt::Expr(v0.clone(), v1.clone()), + Stmt::Macro(v0) => Stmt::Macro(v0.clone()), + } + } +} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] +impl Clone for StmtMacro { + fn clone(&self) -> Self { + StmtMacro { + attrs: self.attrs.clone(), + mac: self.mac.clone(), + semi_token: self.semi_token.clone(), } } } diff --git a/src/gen/debug.rs b/src/gen/debug.rs index 7d51e07b7..6701f5515 100644 --- a/src/gen/debug.rs +++ b/src/gen/debug.rs @@ -2320,9 +2320,25 @@ impl Debug for Stmt { formatter.field(v1); formatter.finish() } + Stmt::Macro(v0) => { + let mut formatter = formatter.debug_tuple("Macro"); + formatter.field(v0); + formatter.finish() + } } } } +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Debug for StmtMacro { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut formatter = formatter.debug_struct("StmtMacro"); + formatter.field("attrs", &self.attrs); + formatter.field("mac", &self.mac); + formatter.field("semi_token", &self.semi_token); + formatter.finish() + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for TraitBound { diff --git a/src/gen/eq.rs b/src/gen/eq.rs index 73d88bda3..8d33c6ce0 100644 --- a/src/gen/eq.rs +++ b/src/gen/eq.rs @@ -1624,10 +1624,22 @@ impl PartialEq for Stmt { (Stmt::Expr(self0, self1), Stmt::Expr(other0, other1)) => { self0 == other0 && self1 == other1 } + (Stmt::Macro(self0), Stmt::Macro(other0)) => self0 == other0, _ => false, } } } +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Eq for StmtMacro {} +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl PartialEq for StmtMacro { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.mac == other.mac + && self.semi_token == other.semi_token + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Eq for TraitBound {} diff --git a/src/gen/fold.rs b/src/gen/fold.rs index 2865a8d42..dd53bb458 100644 --- a/src/gen/fold.rs +++ b/src/gen/fold.rs @@ -582,6 +582,10 @@ pub trait Fold { fn fold_stmt(&mut self, i: Stmt) -> Stmt { fold_stmt(self, i) } + #[cfg(feature = "full")] + fn fold_stmt_macro(&mut self, i: StmtMacro) -> StmtMacro { + fold_stmt_macro(self, i) + } #[cfg(any(feature = "derive", feature = "full"))] fn fold_trait_bound(&mut self, i: TraitBound) -> TraitBound { fold_trait_bound(self, i) @@ -2704,6 +2708,18 @@ where (_binding_1).map(|it| Token![;](tokens_helper(f, &it.spans))), ) } + Stmt::Macro(_binding_0) => Stmt::Macro(f.fold_stmt_macro(_binding_0)), + } +} +#[cfg(feature = "full")] +pub fn fold_stmt_macro<F>(f: &mut F, node: StmtMacro) -> StmtMacro +where + F: Fold + ?Sized, +{ + StmtMacro { + attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), + mac: f.fold_macro(node.mac), + semi_token: (node.semi_token).map(|it| Token![;](tokens_helper(f, &it.spans))), } } #[cfg(any(feature = "derive", feature = "full"))] diff --git a/src/gen/hash.rs b/src/gen/hash.rs index bb1ab6de7..d70d5c45d 100644 --- a/src/gen/hash.rs +++ b/src/gen/hash.rs @@ -2163,9 +2163,25 @@ impl Hash for Stmt { v0.hash(state); v1.hash(state); } + Stmt::Macro(v0) => { + state.write_u8(3u8); + v0.hash(state); + } } } } +#[cfg(feature = "full")] +#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] +impl Hash for StmtMacro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.mac.hash(state); + self.semi_token.hash(state); + } +} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for TraitBound { diff --git a/src/gen/visit.rs b/src/gen/visit.rs index 32633762e..1b3df4ea9 100644 --- a/src/gen/visit.rs +++ b/src/gen/visit.rs @@ -584,6 +584,10 @@ pub trait Visit<'ast> { fn visit_stmt(&mut self, i: &'ast Stmt) { visit_stmt(self, i); } + #[cfg(feature = "full")] + fn visit_stmt_macro(&mut self, i: &'ast StmtMacro) { + visit_stmt_macro(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] fn visit_trait_bound(&mut self, i: &'ast TraitBound) { visit_trait_bound(self, i); @@ -3064,6 +3068,22 @@ where tokens_helper(v, &it.spans); } } + Stmt::Macro(_binding_0) => { + v.visit_stmt_macro(_binding_0); + } + } +} +#[cfg(feature = "full")] +pub fn visit_stmt_macro<'ast, V>(v: &mut V, node: &'ast StmtMacro) +where + V: Visit<'ast> + ?Sized, +{ + for it in &node.attrs { + v.visit_attribute(it); + } + v.visit_macro(&node.mac); + if let Some(it) = &node.semi_token { + tokens_helper(v, &it.spans); } } #[cfg(any(feature = "derive", feature = "full"))] diff --git a/src/gen/visit_mut.rs b/src/gen/visit_mut.rs index 889456c0c..aeb4d269f 100644 --- a/src/gen/visit_mut.rs +++ b/src/gen/visit_mut.rs @@ -585,6 +585,10 @@ pub trait VisitMut { fn visit_stmt_mut(&mut self, i: &mut Stmt) { visit_stmt_mut(self, i); } + #[cfg(feature = "full")] + fn visit_stmt_macro_mut(&mut self, i: &mut StmtMacro) { + visit_stmt_macro_mut(self, i); + } #[cfg(any(feature = "derive", feature = "full"))] fn visit_trait_bound_mut(&mut self, i: &mut TraitBound) { visit_trait_bound_mut(self, i); @@ -3067,6 +3071,22 @@ where tokens_helper(v, &mut it.spans); } } + Stmt::Macro(_binding_0) => { + v.visit_stmt_macro_mut(_binding_0); + } + } +} +#[cfg(feature = "full")] +pub fn visit_stmt_macro_mut<V>(v: &mut V, node: &mut StmtMacro) +where + V: VisitMut + ?Sized, +{ + for it in &mut node.attrs { + v.visit_attribute_mut(it); + } + v.visit_macro_mut(&mut node.mac); + if let Some(it) = &mut node.semi_token { + tokens_helper(v, &mut it.spans); } } #[cfg(any(feature = "derive", feature = "full"))] diff --git a/src/item.rs b/src/item.rs index 7893e1f98..6ca27fc5e 100644 --- a/src/item.rs +++ b/src/item.rs @@ -2653,7 +2653,7 @@ pub mod parsing { } impl MacroDelimiter { - fn is_brace(&self) -> bool { + pub(crate) fn is_brace(&self) -> bool { match self { MacroDelimiter::Brace(_) => true, MacroDelimiter::Paren(_) | MacroDelimiter::Bracket(_) => false, diff --git a/src/lib.rs b/src/lib.rs index 27ea3cfcf..563325920 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -477,7 +477,7 @@ pub mod spanned; #[cfg(feature = "full")] mod stmt; #[cfg(feature = "full")] -pub use crate::stmt::{Block, Local, LocalInit, Stmt}; +pub use crate::stmt::{Block, Local, LocalInit, Stmt, StmtMacro}; mod thread; diff --git a/src/stmt.rs b/src/stmt.rs index c27f2678f..6235a201e 100644 --- a/src/stmt.rs +++ b/src/stmt.rs @@ -22,6 +22,13 @@ ast_enum! { /// Expression, with or without trailing semicolon. Expr(Expr, Option<Token![;]>), + + /// A macro invocation in statement position. + /// + /// Syntactically it's ambiguous which other kind of statement this + /// macro would expand to. It can be an of local variable (`let`), item, + /// or expression. + Macro(StmtMacro), } } @@ -51,6 +58,20 @@ ast_struct! { } } +ast_struct! { + /// A macro invocation in statement position. + /// + /// Syntactically it's ambiguous which other kind of statement this macro + /// would expand to. It can be an of local variable (`let`), item, or + /// expression. + #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] + pub struct StmtMacro { + pub attrs: Vec<Attribute>, + pub mac: Macro, + pub semi_token: Option<Token![;]>, + } +} + #[cfg(feature = "parsing")] pub mod parsing { use super::*; @@ -120,13 +141,15 @@ pub mod parsing { if input.is_empty() { break; } - let s = parse_stmt(input, AllowNoSemi(true))?; - let requires_semicolon = if let Stmt::Expr(s, None) = &s { - expr::requires_terminator(s) - } else { - false + let stmt = parse_stmt(input, AllowNoSemi(true))?; + let requires_semicolon = match &stmt { + Stmt::Expr(stmt, None) => expr::requires_terminator(stmt), + Stmt::Macro(stmt) => { + stmt.semi_token.is_none() && !stmt.mac.delimiter.is_brace() + } + Stmt::Local(_) | Stmt::Item(_) | Stmt::Expr(_, Some(_)) => false, }; - stmts.push(s); + stmts.push(stmt); if input.is_empty() { break; } else if requires_semicolon { @@ -162,14 +185,17 @@ pub mod parsing { // brace-style macros; paren and bracket macros get parsed as // expression statements. let ahead = input.fork(); + let mut is_item_macro = false; if let Ok(path) = ahead.call(Path::parse_mod_style) { - if ahead.peek(Token![!]) - && (ahead.peek2(token::Brace) + if ahead.peek(Token![!]) { + if ahead.peek2(Ident) { + is_item_macro = true; + } else if ahead.peek2(token::Brace) && !(ahead.peek3(Token![.]) || ahead.peek3(Token![?])) - || ahead.peek2(Ident)) - { - input.advance_to(&ahead); - return stmt_mac(input, attrs, path); + { + input.advance_to(&ahead); + return stmt_mac(input, attrs, path).map(Stmt::Macro); + } } } @@ -202,6 +228,7 @@ pub mod parsing { && (input.peek2(Token![unsafe]) || input.peek2(Token![impl])) || input.peek(Token![impl]) || input.peek(Token![macro]) + || is_item_macro { let mut item: Item = input.parse()?; attrs.extend(item.replace_attrs(Vec::new())); @@ -212,15 +239,13 @@ pub mod parsing { } } - fn stmt_mac(input: ParseStream, attrs: Vec<Attribute>, path: Path) -> Result<Stmt> { + fn stmt_mac(input: ParseStream, attrs: Vec<Attribute>, path: Path) -> Result<StmtMacro> { let bang_token: Token![!] = input.parse()?; - let ident: Option<Ident> = input.parse()?; let (delimiter, tokens) = mac::parse_delimiter(input)?; let semi_token: Option<Token![;]> = input.parse()?; - Ok(Stmt::Item(Item::Macro(ItemMacro { + Ok(StmtMacro { attrs, - ident, mac: Macro { path, bang_token, @@ -228,7 +253,7 @@ pub mod parsing { tokens, }, semi_token, - }))) + }) } fn stmt_local(input: ParseStream, attrs: Vec<Attribute>) -> Result<Local> { @@ -337,11 +362,21 @@ pub mod parsing { attrs.extend(attr_target.replace_attrs(Vec::new())); attr_target.replace_attrs(attrs); - if let semi @ Some(_) = input.parse()? { - return Ok(Stmt::Expr(e, semi)); + let semi_token: Option<Token![;]> = input.parse()?; + + if allow_nosemi.0 || semi_token.is_some() { + if let Expr::Macro(ExprMacro { attrs, mac }) = e { + return Ok(Stmt::Macro(StmtMacro { + attrs, + mac, + semi_token, + })); + } } - if allow_nosemi.0 || !expr::requires_terminator(&e) { + if semi_token.is_some() { + Ok(Stmt::Expr(e, semi_token)) + } else if allow_nosemi.0 || !expr::requires_terminator(&e) { Ok(Stmt::Expr(e, None)) } else { Err(input.error("expected semicolon")) @@ -374,6 +409,7 @@ mod printing { expr.to_tokens(tokens); semi.to_tokens(tokens); } + Stmt::Macro(mac) => mac.to_tokens(tokens), } } } @@ -395,4 +431,13 @@ mod printing { self.semi_token.to_tokens(tokens); } } + + #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] + impl ToTokens for StmtMacro { + fn to_tokens(&self, tokens: &mut TokenStream) { + expr::printing::outer_attrs_to_tokens(&self.attrs, tokens); + self.mac.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } } diff --git a/syn.json b/syn.json index ff86558fa..0d462ee15 100644 --- a/syn.json +++ b/syn.json @@ -4275,9 +4275,37 @@ "token": "Semi" } } + ], + "Macro": [ + { + "syn": "StmtMacro" + } ] } }, + { + "ident": "StmtMacro", + "features": { + "any": [ + "full" + ] + }, + "fields": { + "attrs": { + "vec": { + "syn": "Attribute" + } + }, + "mac": { + "syn": "Macro" + }, + "semi_token": { + "option": { + "token": "Semi" + } + } + } + }, { "ident": "TraitBound", "features": {
Consider adding a Stmt::Macro variant In something like: ```rust fn main() { thread_local! { static FOO: i32 = 1; } println! { "{}", FOO.with(i32::clone) } } ``` it's syntactically ambiguous whether the macros represent an expression or an item. Currently this syntax is arbitrarily disambiguated to Stmt::Item by syn (as opposed to Stmt::Expr) but perhaps it would be clearer not to do that so arbitrarily.
dtolnay/syn
b7b288a0cb569a8e0c175ee675939929c5f3f202
2023-01-23T07:44:43Z
1.0
1,323
[ "1090" ]
7ab0dea6d8ca74b4167c7dda48b4397ee83d6a0e
dtolnay__syn-1323
diff --git a/tests/debug/gen.rs b/tests/debug/gen.rs index ddcdc439a..92a163340 100644 --- a/tests/debug/gen.rs +++ b/tests/debug/gen.rs @@ -2427,8 +2427,8 @@ impl Debug for Lite<syn::ImplItem> { formatter.field("expr", Lite(&_val.expr)); formatter.finish() } - syn::ImplItem::Method(_val) => { - let mut formatter = formatter.debug_struct("ImplItem::Method"); + syn::ImplItem::Fn(_val) => { + let mut formatter = formatter.debug_struct("ImplItem::Fn"); if !_val.attrs.is_empty() { formatter.field("attrs", Lite(&_val.attrs)); } @@ -2529,51 +2529,51 @@ impl Debug for Lite<syn::ImplItemConst> { formatter.finish() } } -impl Debug for Lite<syn::ImplItemMacro> { +impl Debug for Lite<syn::ImplItemFn> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemMacro"); + let mut formatter = formatter.debug_struct("ImplItemFn"); if !_val.attrs.is_empty() { formatter.field("attrs", Lite(&_val.attrs)); } - formatter.field("mac", Lite(&_val.mac)); - if let Some(val) = &_val.semi_token { + formatter.field("vis", Lite(&_val.vis)); + if let Some(val) = &_val.defaultness { #[derive(RefCast)] #[repr(transparent)] - struct Print(syn::token::Semi); + struct Print(syn::token::Default); impl Debug for Print { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("Some")?; Ok(()) } } - formatter.field("semi_token", Print::ref_cast(val)); + formatter.field("defaultness", Print::ref_cast(val)); } + formatter.field("sig", Lite(&_val.sig)); + formatter.field("block", Lite(&_val.block)); formatter.finish() } } -impl Debug for Lite<syn::ImplItemMethod> { +impl Debug for Lite<syn::ImplItemMacro> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; - let mut formatter = formatter.debug_struct("ImplItemMethod"); + let mut formatter = formatter.debug_struct("ImplItemMacro"); if !_val.attrs.is_empty() { formatter.field("attrs", Lite(&_val.attrs)); } - formatter.field("vis", Lite(&_val.vis)); - if let Some(val) = &_val.defaultness { + formatter.field("mac", Lite(&_val.mac)); + if let Some(val) = &_val.semi_token { #[derive(RefCast)] #[repr(transparent)] - struct Print(syn::token::Default); + struct Print(syn::token::Semi); impl Debug for Print { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("Some")?; Ok(()) } } - formatter.field("defaultness", Print::ref_cast(val)); + formatter.field("semi_token", Print::ref_cast(val)); } - formatter.field("sig", Lite(&_val.sig)); - formatter.field("block", Lite(&_val.block)); formatter.finish() } } @@ -4603,8 +4603,8 @@ impl Debug for Lite<syn::TraitItem> { } formatter.finish() } - syn::TraitItem::Method(_val) => { - let mut formatter = formatter.debug_struct("TraitItem::Method"); + syn::TraitItem::Fn(_val) => { + let mut formatter = formatter.debug_struct("TraitItem::Fn"); if !_val.attrs.is_empty() { formatter.field("attrs", Lite(&_val.attrs)); } @@ -4738,14 +4738,30 @@ impl Debug for Lite<syn::TraitItemConst> { formatter.finish() } } -impl Debug for Lite<syn::TraitItemMacro> { +impl Debug for Lite<syn::TraitItemFn> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemMacro"); + let mut formatter = formatter.debug_struct("TraitItemFn"); if !_val.attrs.is_empty() { formatter.field("attrs", Lite(&_val.attrs)); } - formatter.field("mac", Lite(&_val.mac)); + formatter.field("sig", Lite(&_val.sig)); + if let Some(val) = &_val.default { + #[derive(RefCast)] + #[repr(transparent)] + struct Print(syn::Block); + impl Debug for Print { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("Some")?; + let _val = &self.0; + formatter.write_str("(")?; + Debug::fmt(Lite(_val), formatter)?; + formatter.write_str(")")?; + Ok(()) + } + } + formatter.field("default", Print::ref_cast(val)); + } if let Some(val) = &_val.semi_token { #[derive(RefCast)] #[repr(transparent)] @@ -4761,30 +4777,14 @@ impl Debug for Lite<syn::TraitItemMacro> { formatter.finish() } } -impl Debug for Lite<syn::TraitItemMethod> { +impl Debug for Lite<syn::TraitItemMacro> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; - let mut formatter = formatter.debug_struct("TraitItemMethod"); + let mut formatter = formatter.debug_struct("TraitItemMacro"); if !_val.attrs.is_empty() { formatter.field("attrs", Lite(&_val.attrs)); } - formatter.field("sig", Lite(&_val.sig)); - if let Some(val) = &_val.default { - #[derive(RefCast)] - #[repr(transparent)] - struct Print(syn::Block); - impl Debug for Print { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("Some")?; - let _val = &self.0; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - formatter.field("default", Print::ref_cast(val)); - } + formatter.field("mac", Lite(&_val.mac)); if let Some(val) = &_val.semi_token { #[derive(RefCast)] #[repr(transparent)] diff --git a/tests/test_receiver.rs b/tests/test_receiver.rs index c772992c1..fc2d5403a 100644 --- a/tests/test_receiver.rs +++ b/tests/test_receiver.rs @@ -1,10 +1,10 @@ #![allow(clippy::uninlined_format_args)] -use syn::{parse_quote, FnArg, Receiver, TraitItemMethod}; +use syn::{parse_quote, FnArg, Receiver, TraitItemFn}; #[test] fn test_by_value() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn by_value(self: Self); }; match sig.receiver() { @@ -15,7 +15,7 @@ fn test_by_value() { #[test] fn test_by_mut_value() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn by_mut(mut self: Self); }; match sig.receiver() { @@ -26,7 +26,7 @@ fn test_by_mut_value() { #[test] fn test_by_ref() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn by_ref(self: &Self); }; match sig.receiver() { @@ -37,7 +37,7 @@ fn test_by_ref() { #[test] fn test_by_box() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn by_box(self: Box<Self>); }; match sig.receiver() { @@ -48,7 +48,7 @@ fn test_by_box() { #[test] fn test_by_pin() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn by_pin(self: Pin<Self>); }; match sig.receiver() { @@ -59,7 +59,7 @@ fn test_by_pin() { #[test] fn test_explicit_type() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn explicit_type(self: Pin<MyType>); }; match sig.receiver() { @@ -70,7 +70,7 @@ fn test_explicit_type() { #[test] fn test_value_shorthand() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn value_shorthand(self); }; match sig.receiver() { @@ -85,7 +85,7 @@ fn test_value_shorthand() { #[test] fn test_mut_value_shorthand() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn mut_value_shorthand(mut self); }; match sig.receiver() { @@ -100,7 +100,7 @@ fn test_mut_value_shorthand() { #[test] fn test_ref_shorthand() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn ref_shorthand(&self); }; match sig.receiver() { @@ -115,7 +115,7 @@ fn test_ref_shorthand() { #[test] fn test_ref_mut_shorthand() { - let TraitItemMethod { sig, .. } = parse_quote! { + let TraitItemFn { sig, .. } = parse_quote! { fn ref_mut_shorthand(&mut self); }; match sig.receiver() {
diff --git a/src/gen/clone.rs b/src/gen/clone.rs index 0b3b1e8b9..81675f49a 100644 --- a/src/gen/clone.rs +++ b/src/gen/clone.rs @@ -942,7 +942,7 @@ impl Clone for ImplItem { fn clone(&self) -> Self { match self { ImplItem::Const(v0) => ImplItem::Const(v0.clone()), - ImplItem::Method(v0) => ImplItem::Method(v0.clone()), + ImplItem::Fn(v0) => ImplItem::Fn(v0.clone()), ImplItem::Type(v0) => ImplItem::Type(v0.clone()), ImplItem::Macro(v0) => ImplItem::Macro(v0.clone()), ImplItem::Verbatim(v0) => ImplItem::Verbatim(v0.clone()), @@ -969,25 +969,25 @@ impl Clone for ImplItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] -impl Clone for ImplItemMacro { +impl Clone for ImplItemFn { fn clone(&self) -> Self { - ImplItemMacro { + ImplItemFn { attrs: self.attrs.clone(), - mac: self.mac.clone(), - semi_token: self.semi_token.clone(), + vis: self.vis.clone(), + defaultness: self.defaultness.clone(), + sig: self.sig.clone(), + block: self.block.clone(), } } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] -impl Clone for ImplItemMethod { +impl Clone for ImplItemMacro { fn clone(&self) -> Self { - ImplItemMethod { + ImplItemMacro { attrs: self.attrs.clone(), - vis: self.vis.clone(), - defaultness: self.defaultness.clone(), - sig: self.sig.clone(), - block: self.block.clone(), + mac: self.mac.clone(), + semi_token: self.semi_token.clone(), } } } @@ -1725,7 +1725,7 @@ impl Clone for TraitItem { fn clone(&self) -> Self { match self { TraitItem::Const(v0) => TraitItem::Const(v0.clone()), - TraitItem::Method(v0) => TraitItem::Method(v0.clone()), + TraitItem::Fn(v0) => TraitItem::Fn(v0.clone()), TraitItem::Type(v0) => TraitItem::Type(v0.clone()), TraitItem::Macro(v0) => TraitItem::Macro(v0.clone()), TraitItem::Verbatim(v0) => TraitItem::Verbatim(v0.clone()), @@ -1749,23 +1749,23 @@ impl Clone for TraitItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] -impl Clone for TraitItemMacro { +impl Clone for TraitItemFn { fn clone(&self) -> Self { - TraitItemMacro { + TraitItemFn { attrs: self.attrs.clone(), - mac: self.mac.clone(), + sig: self.sig.clone(), + default: self.default.clone(), semi_token: self.semi_token.clone(), } } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] -impl Clone for TraitItemMethod { +impl Clone for TraitItemMacro { fn clone(&self) -> Self { - TraitItemMethod { + TraitItemMacro { attrs: self.attrs.clone(), - sig: self.sig.clone(), - default: self.default.clone(), + mac: self.mac.clone(), semi_token: self.semi_token.clone(), } } diff --git a/src/gen/debug.rs b/src/gen/debug.rs index bc0a1f915..7d51e07b7 100644 --- a/src/gen/debug.rs +++ b/src/gen/debug.rs @@ -1328,8 +1328,8 @@ impl Debug for ImplItem { formatter.field(v0); formatter.finish() } - ImplItem::Method(v0) => { - let mut formatter = formatter.debug_tuple("Method"); + ImplItem::Fn(v0) => { + let mut formatter = formatter.debug_tuple("Fn"); formatter.field(v0); formatter.finish() } @@ -1371,25 +1371,25 @@ impl Debug for ImplItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Debug for ImplItemMacro { +impl Debug for ImplItemFn { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let mut formatter = formatter.debug_struct("ImplItemMacro"); + let mut formatter = formatter.debug_struct("ImplItemFn"); formatter.field("attrs", &self.attrs); - formatter.field("mac", &self.mac); - formatter.field("semi_token", &self.semi_token); + formatter.field("vis", &self.vis); + formatter.field("defaultness", &self.defaultness); + formatter.field("sig", &self.sig); + formatter.field("block", &self.block); formatter.finish() } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Debug for ImplItemMethod { +impl Debug for ImplItemMacro { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let mut formatter = formatter.debug_struct("ImplItemMethod"); + let mut formatter = formatter.debug_struct("ImplItemMacro"); formatter.field("attrs", &self.attrs); - formatter.field("vis", &self.vis); - formatter.field("defaultness", &self.defaultness); - formatter.field("sig", &self.sig); - formatter.field("block", &self.block); + formatter.field("mac", &self.mac); + formatter.field("semi_token", &self.semi_token); formatter.finish() } } @@ -2359,8 +2359,8 @@ impl Debug for TraitItem { formatter.field(v0); formatter.finish() } - TraitItem::Method(v0) => { - let mut formatter = formatter.debug_tuple("Method"); + TraitItem::Fn(v0) => { + let mut formatter = formatter.debug_tuple("Fn"); formatter.field(v0); formatter.finish() } @@ -2399,23 +2399,23 @@ impl Debug for TraitItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Debug for TraitItemMacro { +impl Debug for TraitItemFn { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let mut formatter = formatter.debug_struct("TraitItemMacro"); + let mut formatter = formatter.debug_struct("TraitItemFn"); formatter.field("attrs", &self.attrs); - formatter.field("mac", &self.mac); + formatter.field("sig", &self.sig); + formatter.field("default", &self.default); formatter.field("semi_token", &self.semi_token); formatter.finish() } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Debug for TraitItemMethod { +impl Debug for TraitItemMacro { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let mut formatter = formatter.debug_struct("TraitItemMethod"); + let mut formatter = formatter.debug_struct("TraitItemMacro"); formatter.field("attrs", &self.attrs); - formatter.field("sig", &self.sig); - formatter.field("default", &self.default); + formatter.field("mac", &self.mac); formatter.field("semi_token", &self.semi_token); formatter.finish() } diff --git a/src/gen/eq.rs b/src/gen/eq.rs index 5251693ca..73d88bda3 100644 --- a/src/gen/eq.rs +++ b/src/gen/eq.rs @@ -928,7 +928,7 @@ impl PartialEq for ImplItem { fn eq(&self, other: &Self) -> bool { match (self, other) { (ImplItem::Const(self0), ImplItem::Const(other0)) => self0 == other0, - (ImplItem::Method(self0), ImplItem::Method(other0)) => self0 == other0, + (ImplItem::Fn(self0), ImplItem::Fn(other0)) => self0 == other0, (ImplItem::Type(self0), ImplItem::Type(other0)) => self0 == other0, (ImplItem::Macro(self0), ImplItem::Macro(other0)) => self0 == other0, (ImplItem::Verbatim(self0), ImplItem::Verbatim(other0)) => { @@ -952,25 +952,25 @@ impl PartialEq for ImplItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Eq for ImplItemMacro {} +impl Eq for ImplItemFn {} #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl PartialEq for ImplItemMacro { +impl PartialEq for ImplItemFn { fn eq(&self, other: &Self) -> bool { - self.attrs == other.attrs && self.mac == other.mac - && self.semi_token == other.semi_token + self.attrs == other.attrs && self.vis == other.vis + && self.defaultness == other.defaultness && self.sig == other.sig + && self.block == other.block } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Eq for ImplItemMethod {} +impl Eq for ImplItemMacro {} #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl PartialEq for ImplItemMethod { +impl PartialEq for ImplItemMacro { fn eq(&self, other: &Self) -> bool { - self.attrs == other.attrs && self.vis == other.vis - && self.defaultness == other.defaultness && self.sig == other.sig - && self.block == other.block + self.attrs == other.attrs && self.mac == other.mac + && self.semi_token == other.semi_token } } #[cfg(feature = "full")] @@ -1662,7 +1662,7 @@ impl PartialEq for TraitItem { fn eq(&self, other: &Self) -> bool { match (self, other) { (TraitItem::Const(self0), TraitItem::Const(other0)) => self0 == other0, - (TraitItem::Method(self0), TraitItem::Method(other0)) => self0 == other0, + (TraitItem::Fn(self0), TraitItem::Fn(other0)) => self0 == other0, (TraitItem::Type(self0), TraitItem::Type(other0)) => self0 == other0, (TraitItem::Macro(self0), TraitItem::Macro(other0)) => self0 == other0, (TraitItem::Verbatim(self0), TraitItem::Verbatim(other0)) => { @@ -1685,24 +1685,24 @@ impl PartialEq for TraitItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Eq for TraitItemMacro {} +impl Eq for TraitItemFn {} #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl PartialEq for TraitItemMacro { +impl PartialEq for TraitItemFn { fn eq(&self, other: &Self) -> bool { - self.attrs == other.attrs && self.mac == other.mac - && self.semi_token == other.semi_token + self.attrs == other.attrs && self.sig == other.sig + && self.default == other.default && self.semi_token == other.semi_token } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Eq for TraitItemMethod {} +impl Eq for TraitItemMacro {} #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl PartialEq for TraitItemMethod { +impl PartialEq for TraitItemMacro { fn eq(&self, other: &Self) -> bool { - self.attrs == other.attrs && self.sig == other.sig - && self.default == other.default && self.semi_token == other.semi_token + self.attrs == other.attrs && self.mac == other.mac + && self.semi_token == other.semi_token } } #[cfg(feature = "full")] diff --git a/src/gen/fold.rs b/src/gen/fold.rs index c689a7dbf..2865a8d42 100644 --- a/src/gen/fold.rs +++ b/src/gen/fold.rs @@ -334,12 +334,12 @@ pub trait Fold { fold_impl_item_const(self, i) } #[cfg(feature = "full")] - fn fold_impl_item_macro(&mut self, i: ImplItemMacro) -> ImplItemMacro { - fold_impl_item_macro(self, i) + fn fold_impl_item_fn(&mut self, i: ImplItemFn) -> ImplItemFn { + fold_impl_item_fn(self, i) } #[cfg(feature = "full")] - fn fold_impl_item_method(&mut self, i: ImplItemMethod) -> ImplItemMethod { - fold_impl_item_method(self, i) + fn fold_impl_item_macro(&mut self, i: ImplItemMacro) -> ImplItemMacro { + fold_impl_item_macro(self, i) } #[cfg(feature = "full")] fn fold_impl_item_type(&mut self, i: ImplItemType) -> ImplItemType { @@ -602,12 +602,12 @@ pub trait Fold { fold_trait_item_const(self, i) } #[cfg(feature = "full")] - fn fold_trait_item_macro(&mut self, i: TraitItemMacro) -> TraitItemMacro { - fold_trait_item_macro(self, i) + fn fold_trait_item_fn(&mut self, i: TraitItemFn) -> TraitItemFn { + fold_trait_item_fn(self, i) } #[cfg(feature = "full")] - fn fold_trait_item_method(&mut self, i: TraitItemMethod) -> TraitItemMethod { - fold_trait_item_method(self, i) + fn fold_trait_item_macro(&mut self, i: TraitItemMacro) -> TraitItemMacro { + fold_trait_item_macro(self, i) } #[cfg(feature = "full")] fn fold_trait_item_type(&mut self, i: TraitItemType) -> TraitItemType { @@ -1804,9 +1804,7 @@ where ImplItem::Const(_binding_0) => { ImplItem::Const(f.fold_impl_item_const(_binding_0)) } - ImplItem::Method(_binding_0) => { - ImplItem::Method(f.fold_impl_item_method(_binding_0)) - } + ImplItem::Fn(_binding_0) => ImplItem::Fn(f.fold_impl_item_fn(_binding_0)), ImplItem::Type(_binding_0) => ImplItem::Type(f.fold_impl_item_type(_binding_0)), ImplItem::Macro(_binding_0) => { ImplItem::Macro(f.fold_impl_item_macro(_binding_0)) @@ -1834,28 +1832,28 @@ where } } #[cfg(feature = "full")] -pub fn fold_impl_item_macro<F>(f: &mut F, node: ImplItemMacro) -> ImplItemMacro +pub fn fold_impl_item_fn<F>(f: &mut F, node: ImplItemFn) -> ImplItemFn where F: Fold + ?Sized, { - ImplItemMacro { + ImplItemFn { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - mac: f.fold_macro(node.mac), - semi_token: (node.semi_token).map(|it| Token![;](tokens_helper(f, &it.spans))), + vis: f.fold_visibility(node.vis), + defaultness: (node.defaultness) + .map(|it| Token![default](tokens_helper(f, &it.span))), + sig: f.fold_signature(node.sig), + block: f.fold_block(node.block), } } #[cfg(feature = "full")] -pub fn fold_impl_item_method<F>(f: &mut F, node: ImplItemMethod) -> ImplItemMethod +pub fn fold_impl_item_macro<F>(f: &mut F, node: ImplItemMacro) -> ImplItemMacro where F: Fold + ?Sized, { - ImplItemMethod { + ImplItemMacro { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - vis: f.fold_visibility(node.vis), - defaultness: (node.defaultness) - .map(|it| Token![default](tokens_helper(f, &it.span))), - sig: f.fold_signature(node.sig), - block: f.fold_block(node.block), + mac: f.fold_macro(node.mac), + semi_token: (node.semi_token).map(|it| Token![;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] @@ -2744,9 +2742,7 @@ where TraitItem::Const(_binding_0) => { TraitItem::Const(f.fold_trait_item_const(_binding_0)) } - TraitItem::Method(_binding_0) => { - TraitItem::Method(f.fold_trait_item_method(_binding_0)) - } + TraitItem::Fn(_binding_0) => TraitItem::Fn(f.fold_trait_item_fn(_binding_0)), TraitItem::Type(_binding_0) => { TraitItem::Type(f.fold_trait_item_type(_binding_0)) } @@ -2773,25 +2769,25 @@ where } } #[cfg(feature = "full")] -pub fn fold_trait_item_macro<F>(f: &mut F, node: TraitItemMacro) -> TraitItemMacro +pub fn fold_trait_item_fn<F>(f: &mut F, node: TraitItemFn) -> TraitItemFn where F: Fold + ?Sized, { - TraitItemMacro { + TraitItemFn { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - mac: f.fold_macro(node.mac), + sig: f.fold_signature(node.sig), + default: (node.default).map(|it| f.fold_block(it)), semi_token: (node.semi_token).map(|it| Token![;](tokens_helper(f, &it.spans))), } } #[cfg(feature = "full")] -pub fn fold_trait_item_method<F>(f: &mut F, node: TraitItemMethod) -> TraitItemMethod +pub fn fold_trait_item_macro<F>(f: &mut F, node: TraitItemMacro) -> TraitItemMacro where F: Fold + ?Sized, { - TraitItemMethod { + TraitItemMacro { attrs: FoldHelper::lift(node.attrs, |it| f.fold_attribute(it)), - sig: f.fold_signature(node.sig), - default: (node.default).map(|it| f.fold_block(it)), + mac: f.fold_macro(node.mac), semi_token: (node.semi_token).map(|it| Token![;](tokens_helper(f, &it.spans))), } } diff --git a/src/gen/hash.rs b/src/gen/hash.rs index 7a1cae095..bb1ab6de7 100644 --- a/src/gen/hash.rs +++ b/src/gen/hash.rs @@ -1245,7 +1245,7 @@ impl Hash for ImplItem { state.write_u8(0u8); v0.hash(state); } - ImplItem::Method(v0) => { + ImplItem::Fn(v0) => { state.write_u8(1u8); v0.hash(state); } @@ -1281,28 +1281,28 @@ impl Hash for ImplItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Hash for ImplItemMacro { +impl Hash for ImplItemFn { fn hash<H>(&self, state: &mut H) where H: Hasher, { self.attrs.hash(state); - self.mac.hash(state); - self.semi_token.hash(state); + self.vis.hash(state); + self.defaultness.hash(state); + self.sig.hash(state); + self.block.hash(state); } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Hash for ImplItemMethod { +impl Hash for ImplItemMacro { fn hash<H>(&self, state: &mut H) where H: Hasher, { self.attrs.hash(state); - self.vis.hash(state); - self.defaultness.hash(state); - self.sig.hash(state); - self.block.hash(state); + self.mac.hash(state); + self.semi_token.hash(state); } } #[cfg(feature = "full")] @@ -2208,7 +2208,7 @@ impl Hash for TraitItem { state.write_u8(0u8); v0.hash(state); } - TraitItem::Method(v0) => { + TraitItem::Fn(v0) => { state.write_u8(1u8); v0.hash(state); } @@ -2242,26 +2242,26 @@ impl Hash for TraitItemConst { } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Hash for TraitItemMacro { +impl Hash for TraitItemFn { fn hash<H>(&self, state: &mut H) where H: Hasher, { self.attrs.hash(state); - self.mac.hash(state); + self.sig.hash(state); + self.default.hash(state); self.semi_token.hash(state); } } #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Hash for TraitItemMethod { +impl Hash for TraitItemMacro { fn hash<H>(&self, state: &mut H) where H: Hasher, { self.attrs.hash(state); - self.sig.hash(state); - self.default.hash(state); + self.mac.hash(state); self.semi_token.hash(state); } } diff --git a/src/gen/visit.rs b/src/gen/visit.rs index 4390396ec..32633762e 100644 --- a/src/gen/visit.rs +++ b/src/gen/visit.rs @@ -336,12 +336,12 @@ pub trait Visit<'ast> { visit_impl_item_const(self, i); } #[cfg(feature = "full")] - fn visit_impl_item_macro(&mut self, i: &'ast ImplItemMacro) { - visit_impl_item_macro(self, i); + fn visit_impl_item_fn(&mut self, i: &'ast ImplItemFn) { + visit_impl_item_fn(self, i); } #[cfg(feature = "full")] - fn visit_impl_item_method(&mut self, i: &'ast ImplItemMethod) { - visit_impl_item_method(self, i); + fn visit_impl_item_macro(&mut self, i: &'ast ImplItemMacro) { + visit_impl_item_macro(self, i); } #[cfg(feature = "full")] fn visit_impl_item_type(&mut self, i: &'ast ImplItemType) { @@ -601,12 +601,12 @@ pub trait Visit<'ast> { visit_trait_item_const(self, i); } #[cfg(feature = "full")] - fn visit_trait_item_macro(&mut self, i: &'ast TraitItemMacro) { - visit_trait_item_macro(self, i); + fn visit_trait_item_fn(&mut self, i: &'ast TraitItemFn) { + visit_trait_item_fn(self, i); } #[cfg(feature = "full")] - fn visit_trait_item_method(&mut self, i: &'ast TraitItemMethod) { - visit_trait_item_method(self, i); + fn visit_trait_item_macro(&mut self, i: &'ast TraitItemMacro) { + visit_trait_item_macro(self, i); } #[cfg(feature = "full")] fn visit_trait_item_type(&mut self, i: &'ast TraitItemType) { @@ -2007,8 +2007,8 @@ where ImplItem::Const(_binding_0) => { v.visit_impl_item_const(_binding_0); } - ImplItem::Method(_binding_0) => { - v.visit_impl_item_method(_binding_0); + ImplItem::Fn(_binding_0) => { + v.visit_impl_item_fn(_binding_0); } ImplItem::Type(_binding_0) => { v.visit_impl_item_type(_binding_0); @@ -2042,32 +2042,32 @@ where tokens_helper(v, &node.semi_token.spans); } #[cfg(feature = "full")] -pub fn visit_impl_item_macro<'ast, V>(v: &mut V, node: &'ast ImplItemMacro) +pub fn visit_impl_item_fn<'ast, V>(v: &mut V, node: &'ast ImplItemFn) where V: Visit<'ast> + ?Sized, { for it in &node.attrs { v.visit_attribute(it); } - v.visit_macro(&node.mac); - if let Some(it) = &node.semi_token { - tokens_helper(v, &it.spans); + v.visit_visibility(&node.vis); + if let Some(it) = &node.defaultness { + tokens_helper(v, &it.span); } + v.visit_signature(&node.sig); + v.visit_block(&node.block); } #[cfg(feature = "full")] -pub fn visit_impl_item_method<'ast, V>(v: &mut V, node: &'ast ImplItemMethod) +pub fn visit_impl_item_macro<'ast, V>(v: &mut V, node: &'ast ImplItemMacro) where V: Visit<'ast> + ?Sized, { for it in &node.attrs { v.visit_attribute(it); } - v.visit_visibility(&node.vis); - if let Some(it) = &node.defaultness { - tokens_helper(v, &it.span); + v.visit_macro(&node.mac); + if let Some(it) = &node.semi_token { + tokens_helper(v, &it.spans); } - v.visit_signature(&node.sig); - v.visit_block(&node.block); } #[cfg(feature = "full")] pub fn visit_impl_item_type<'ast, V>(v: &mut V, node: &'ast ImplItemType) @@ -3101,8 +3101,8 @@ where TraitItem::Const(_binding_0) => { v.visit_trait_item_const(_binding_0); } - TraitItem::Method(_binding_0) => { - v.visit_trait_item_method(_binding_0); + TraitItem::Fn(_binding_0) => { + v.visit_trait_item_fn(_binding_0); } TraitItem::Type(_binding_0) => { v.visit_trait_item_type(_binding_0); @@ -3134,30 +3134,30 @@ where tokens_helper(v, &node.semi_token.spans); } #[cfg(feature = "full")] -pub fn visit_trait_item_macro<'ast, V>(v: &mut V, node: &'ast TraitItemMacro) +pub fn visit_trait_item_fn<'ast, V>(v: &mut V, node: &'ast TraitItemFn) where V: Visit<'ast> + ?Sized, { for it in &node.attrs { v.visit_attribute(it); } - v.visit_macro(&node.mac); + v.visit_signature(&node.sig); + if let Some(it) = &node.default { + v.visit_block(it); + } if let Some(it) = &node.semi_token { tokens_helper(v, &it.spans); } } #[cfg(feature = "full")] -pub fn visit_trait_item_method<'ast, V>(v: &mut V, node: &'ast TraitItemMethod) +pub fn visit_trait_item_macro<'ast, V>(v: &mut V, node: &'ast TraitItemMacro) where V: Visit<'ast> + ?Sized, { for it in &node.attrs { v.visit_attribute(it); } - v.visit_signature(&node.sig); - if let Some(it) = &node.default { - v.visit_block(it); - } + v.visit_macro(&node.mac); if let Some(it) = &node.semi_token { tokens_helper(v, &it.spans); } diff --git a/src/gen/visit_mut.rs b/src/gen/visit_mut.rs index 1704d05df..889456c0c 100644 --- a/src/gen/visit_mut.rs +++ b/src/gen/visit_mut.rs @@ -337,12 +337,12 @@ pub trait VisitMut { visit_impl_item_const_mut(self, i); } #[cfg(feature = "full")] - fn visit_impl_item_macro_mut(&mut self, i: &mut ImplItemMacro) { - visit_impl_item_macro_mut(self, i); + fn visit_impl_item_fn_mut(&mut self, i: &mut ImplItemFn) { + visit_impl_item_fn_mut(self, i); } #[cfg(feature = "full")] - fn visit_impl_item_method_mut(&mut self, i: &mut ImplItemMethod) { - visit_impl_item_method_mut(self, i); + fn visit_impl_item_macro_mut(&mut self, i: &mut ImplItemMacro) { + visit_impl_item_macro_mut(self, i); } #[cfg(feature = "full")] fn visit_impl_item_type_mut(&mut self, i: &mut ImplItemType) { @@ -602,12 +602,12 @@ pub trait VisitMut { visit_trait_item_const_mut(self, i); } #[cfg(feature = "full")] - fn visit_trait_item_macro_mut(&mut self, i: &mut TraitItemMacro) { - visit_trait_item_macro_mut(self, i); + fn visit_trait_item_fn_mut(&mut self, i: &mut TraitItemFn) { + visit_trait_item_fn_mut(self, i); } #[cfg(feature = "full")] - fn visit_trait_item_method_mut(&mut self, i: &mut TraitItemMethod) { - visit_trait_item_method_mut(self, i); + fn visit_trait_item_macro_mut(&mut self, i: &mut TraitItemMacro) { + visit_trait_item_macro_mut(self, i); } #[cfg(feature = "full")] fn visit_trait_item_type_mut(&mut self, i: &mut TraitItemType) { @@ -2010,8 +2010,8 @@ where ImplItem::Const(_binding_0) => { v.visit_impl_item_const_mut(_binding_0); } - ImplItem::Method(_binding_0) => { - v.visit_impl_item_method_mut(_binding_0); + ImplItem::Fn(_binding_0) => { + v.visit_impl_item_fn_mut(_binding_0); } ImplItem::Type(_binding_0) => { v.visit_impl_item_type_mut(_binding_0); @@ -2045,32 +2045,32 @@ where tokens_helper(v, &mut node.semi_token.spans); } #[cfg(feature = "full")] -pub fn visit_impl_item_macro_mut<V>(v: &mut V, node: &mut ImplItemMacro) +pub fn visit_impl_item_fn_mut<V>(v: &mut V, node: &mut ImplItemFn) where V: VisitMut + ?Sized, { for it in &mut node.attrs { v.visit_attribute_mut(it); } - v.visit_macro_mut(&mut node.mac); - if let Some(it) = &mut node.semi_token { - tokens_helper(v, &mut it.spans); + v.visit_visibility_mut(&mut node.vis); + if let Some(it) = &mut node.defaultness { + tokens_helper(v, &mut it.span); } + v.visit_signature_mut(&mut node.sig); + v.visit_block_mut(&mut node.block); } #[cfg(feature = "full")] -pub fn visit_impl_item_method_mut<V>(v: &mut V, node: &mut ImplItemMethod) +pub fn visit_impl_item_macro_mut<V>(v: &mut V, node: &mut ImplItemMacro) where V: VisitMut + ?Sized, { for it in &mut node.attrs { v.visit_attribute_mut(it); } - v.visit_visibility_mut(&mut node.vis); - if let Some(it) = &mut node.defaultness { - tokens_helper(v, &mut it.span); + v.visit_macro_mut(&mut node.mac); + if let Some(it) = &mut node.semi_token { + tokens_helper(v, &mut it.spans); } - v.visit_signature_mut(&mut node.sig); - v.visit_block_mut(&mut node.block); } #[cfg(feature = "full")] pub fn visit_impl_item_type_mut<V>(v: &mut V, node: &mut ImplItemType) @@ -3104,8 +3104,8 @@ where TraitItem::Const(_binding_0) => { v.visit_trait_item_const_mut(_binding_0); } - TraitItem::Method(_binding_0) => { - v.visit_trait_item_method_mut(_binding_0); + TraitItem::Fn(_binding_0) => { + v.visit_trait_item_fn_mut(_binding_0); } TraitItem::Type(_binding_0) => { v.visit_trait_item_type_mut(_binding_0); @@ -3137,30 +3137,30 @@ where tokens_helper(v, &mut node.semi_token.spans); } #[cfg(feature = "full")] -pub fn visit_trait_item_macro_mut<V>(v: &mut V, node: &mut TraitItemMacro) +pub fn visit_trait_item_fn_mut<V>(v: &mut V, node: &mut TraitItemFn) where V: VisitMut + ?Sized, { for it in &mut node.attrs { v.visit_attribute_mut(it); } - v.visit_macro_mut(&mut node.mac); + v.visit_signature_mut(&mut node.sig); + if let Some(it) = &mut node.default { + v.visit_block_mut(it); + } if let Some(it) = &mut node.semi_token { tokens_helper(v, &mut it.spans); } } #[cfg(feature = "full")] -pub fn visit_trait_item_method_mut<V>(v: &mut V, node: &mut TraitItemMethod) +pub fn visit_trait_item_macro_mut<V>(v: &mut V, node: &mut TraitItemMacro) where V: VisitMut + ?Sized, { for it in &mut node.attrs { v.visit_attribute_mut(it); } - v.visit_signature_mut(&mut node.sig); - if let Some(it) = &mut node.default { - v.visit_block_mut(it); - } + v.visit_macro_mut(&mut node.mac); if let Some(it) = &mut node.semi_token { tokens_helper(v, &mut it.spans); } diff --git a/src/item.rs b/src/item.rs index 9fbe41af3..7893e1f98 100644 --- a/src/item.rs +++ b/src/item.rs @@ -584,8 +584,8 @@ ast_enum_of_structs! { /// An associated constant within the definition of a trait. Const(TraitItemConst), - /// A trait method within the definition of a trait. - Method(TraitItemMethod), + /// An associated function within the definition of a trait. + Fn(TraitItemFn), /// An associated type within the definition of a trait. Type(TraitItemType), @@ -600,7 +600,7 @@ ast_enum_of_structs! { // // match item { // TraitItem::Const(item) => {...} - // TraitItem::Method(item) => {...} + // TraitItem::Fn(item) => {...} // ... // TraitItem::Verbatim(item) => {...} // @@ -630,9 +630,9 @@ ast_struct! { } ast_struct! { - /// A trait method within the definition of a trait. + /// An associated function within the definition of a trait. #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] - pub struct TraitItemMethod { + pub struct TraitItemFn { pub attrs: Vec<Attribute>, pub sig: Signature, pub default: Option<Block>, @@ -679,8 +679,8 @@ ast_enum_of_structs! { /// An associated constant within an impl block. Const(ImplItemConst), - /// A method within an impl block. - Method(ImplItemMethod), + /// An associated function within an impl block. + Fn(ImplItemFn), /// An associated type within an impl block. Type(ImplItemType), @@ -695,7 +695,7 @@ ast_enum_of_structs! { // // match item { // ImplItem::Const(item) => {...} - // ImplItem::Method(item) => {...} + // ImplItem::Fn(item) => {...} // ... // ImplItem::Verbatim(item) => {...} // @@ -728,9 +728,9 @@ ast_struct! { } ast_struct! { - /// A method within an impl block. + /// An associated function within an impl block. #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] - pub struct ImplItemMethod { + pub struct ImplItemFn { pub attrs: Vec<Attribute>, pub vis: Visibility, pub defaultness: Option<Token![default]>, @@ -2116,7 +2116,7 @@ pub mod parsing { let lookahead = ahead.lookahead1(); let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { - input.parse().map(TraitItem::Method) + input.parse().map(TraitItem::Fn) } else if lookahead.peek(Token![const]) { ahead.parse::<Token![const]>()?; let lookahead = ahead.lookahead1(); @@ -2127,7 +2127,7 @@ pub mod parsing { || lookahead.peek(Token![extern]) || lookahead.peek(Token![fn]) { - input.parse().map(TraitItem::Method) + input.parse().map(TraitItem::Fn) } else { Err(lookahead.error()) } @@ -2151,7 +2151,7 @@ pub mod parsing { let item_attrs = match &mut item { TraitItem::Const(item) => &mut item.attrs, - TraitItem::Method(item) => &mut item.attrs, + TraitItem::Fn(item) => &mut item.attrs, TraitItem::Type(item) => &mut item.attrs, TraitItem::Macro(item) => &mut item.attrs, TraitItem::Verbatim(_) => unreachable!(), @@ -2193,7 +2193,7 @@ pub mod parsing { } #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] - impl Parse for TraitItemMethod { + impl Parse for TraitItemFn { fn parse(input: ParseStream) -> Result<Self> { let mut attrs = input.call(Attribute::parse_outer)?; let sig: Signature = input.parse()?; @@ -2212,7 +2212,7 @@ pub mod parsing { return Err(lookahead.error()); }; - Ok(TraitItemMethod { + Ok(TraitItemFn { attrs, sig, default: brace_token.map(|brace_token| Block { brace_token, stmts }), @@ -2442,7 +2442,7 @@ pub mod parsing { }; let mut item = if lookahead.peek(Token![fn]) || peek_signature(&ahead) { - input.parse().map(ImplItem::Method) + input.parse().map(ImplItem::Fn) } else if lookahead.peek(Token![const]) { let const_token: Token![const] = ahead.parse()?; let lookahead = ahead.lookahead1(); @@ -2489,7 +2489,7 @@ pub mod parsing { { let item_attrs = match &mut item { ImplItem::Const(item) => &mut item.attrs, - ImplItem::Method(item) => &mut item.attrs, + ImplItem::Fn(item) => &mut item.attrs, ImplItem::Type(item) => &mut item.attrs, ImplItem::Macro(item) => &mut item.attrs, ImplItem::Verbatim(_) => return Ok(item), @@ -2528,7 +2528,7 @@ pub mod parsing { } #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] - impl Parse for ImplItemMethod { + impl Parse for ImplItemFn { fn parse(input: ParseStream) -> Result<Self> { let mut attrs = input.call(Attribute::parse_outer)?; let vis: Visibility = input.parse()?; @@ -2536,7 +2536,7 @@ pub mod parsing { let sig: Signature = input.parse()?; let block = if let Some(semi) = input.parse::<Option<Token![;]>>()? { - // Accept methods without a body in an impl block because + // Accept functions without a body in an impl block because // rustc's *parser* does not reject them (the compilation error // is emitted later than parsing) and it can be useful for macro // DSLs. @@ -2557,7 +2557,7 @@ pub mod parsing { } }; - Ok(ImplItemMethod { + Ok(ImplItemFn { attrs, vis, defaultness, @@ -2980,7 +2980,7 @@ mod printing { } #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] - impl ToTokens for TraitItemMethod { + impl ToTokens for TraitItemFn { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); self.sig.to_tokens(tokens); @@ -3044,7 +3044,7 @@ mod printing { } #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] - impl ToTokens for ImplItemMethod { + impl ToTokens for ImplItemFn { fn to_tokens(&self, tokens: &mut TokenStream) { tokens.append_all(self.attrs.outer()); self.vis.to_tokens(tokens); diff --git a/src/lib.rs b/src/lib.rs index 596e21054..27ea3cfcf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -384,11 +384,11 @@ mod item; #[cfg(feature = "full")] pub use crate::item::{ FnArg, ForeignItem, ForeignItemFn, ForeignItemMacro, ForeignItemStatic, ForeignItemType, - ImplItem, ImplItemConst, ImplItemMacro, ImplItemMethod, ImplItemType, Item, ItemConst, - ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, - ItemStruct, ItemTrait, ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, Signature, - TraitItem, TraitItemConst, TraitItemMacro, TraitItemMethod, TraitItemType, UseGlob, UseGroup, - UseName, UsePath, UseRename, UseTree, + ImplItem, ImplItemConst, ImplItemFn, ImplItemMacro, ImplItemType, Item, ItemConst, ItemEnum, + ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMod, ItemStatic, ItemStruct, + ItemTrait, ItemTraitAlias, ItemType, ItemUnion, ItemUse, Receiver, Signature, TraitItem, + TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, UseGlob, UseGroup, UseName, + UsePath, UseRename, UseTree, }; mod lifetime; diff --git a/syn.json b/syn.json index 71c8ef345..ff86558fa 100644 --- a/syn.json +++ b/syn.json @@ -2334,9 +2334,9 @@ "syn": "ImplItemConst" } ], - "Method": [ + "Fn": [ { - "syn": "ImplItemMethod" + "syn": "ImplItemFn" } ], "Type": [ @@ -2402,7 +2402,7 @@ } }, { - "ident": "ImplItemMacro", + "ident": "ImplItemFn", "features": { "any": [ "full" @@ -2414,18 +2414,24 @@ "syn": "Attribute" } }, - "mac": { - "syn": "Macro" + "vis": { + "syn": "Visibility" }, - "semi_token": { + "defaultness": { "option": { - "token": "Semi" + "token": "Default" } + }, + "sig": { + "syn": "Signature" + }, + "block": { + "syn": "Block" } } }, { - "ident": "ImplItemMethod", + "ident": "ImplItemMacro", "features": { "any": [ "full" @@ -2437,19 +2443,13 @@ "syn": "Attribute" } }, - "vis": { - "syn": "Visibility" + "mac": { + "syn": "Macro" }, - "defaultness": { + "semi_token": { "option": { - "token": "Default" + "token": "Semi" } - }, - "sig": { - "syn": "Signature" - }, - "block": { - "syn": "Block" } } }, @@ -4335,9 +4335,9 @@ "syn": "TraitItemConst" } ], - "Method": [ + "Fn": [ { - "syn": "TraitItemMethod" + "syn": "TraitItemFn" } ], "Type": [ @@ -4401,7 +4401,7 @@ } }, { - "ident": "TraitItemMacro", + "ident": "TraitItemFn", "features": { "any": [ "full" @@ -4413,8 +4413,13 @@ "syn": "Attribute" } }, - "mac": { - "syn": "Macro" + "sig": { + "syn": "Signature" + }, + "default": { + "option": { + "syn": "Block" + } }, "semi_token": { "option": { @@ -4424,7 +4429,7 @@ } }, { - "ident": "TraitItemMethod", + "ident": "TraitItemMacro", "features": { "any": [ "full" @@ -4436,13 +4441,8 @@ "syn": "Attribute" } }, - "sig": { - "syn": "Signature" - }, - "default": { - "option": { - "syn": "Block" - } + "mac": { + "syn": "Macro" }, "semi_token": { "option": {
Consider renaming Method to associated function <!-- ❤️ --> This is a small issue, but I think method is not the same as associated fn. `ImplItem::Method` and `TraitItem::Method` actually should be named something else... Please take this into consideration if a breaking change is made sometime in the future.
dtolnay/syn
b7b288a0cb569a8e0c175ee675939929c5f3f202
2023-01-23T06:48:14Z
1.0
1,320
[ "1319" ]
a3198b7f75db5f3e99d90dd1a6d007153b9f6727
dtolnay__syn-1320
diff --git a/tests/debug/gen.rs b/tests/debug/gen.rs index c03c1660e..ecaaf01d4 100644 --- a/tests/debug/gen.rs +++ b/tests/debug/gen.rs @@ -2322,27 +2322,6 @@ impl Debug for Lite<syn::GenericArgument> { } } } -impl Debug for Lite<syn::GenericMethodArgument> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let _val = &self.value; - match _val { - syn::GenericMethodArgument::Type(_val) => { - formatter.write_str("Type")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - syn::GenericMethodArgument::Const(_val) => { - formatter.write_str("Const")?; - formatter.write_str("(")?; - Debug::fmt(Lite(_val), formatter)?; - formatter.write_str(")")?; - Ok(()) - } - } - } -} impl Debug for Lite<syn::GenericParam> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { let _val = &self.value; diff --git a/tests/test_precedence.rs b/tests/test_precedence.rs index fd5b82a1f..24d2b240c 100644 --- a/tests/test_precedence.rs +++ b/tests/test_precedence.rs @@ -355,11 +355,8 @@ fn librustc_brackets(mut librustc_expr: P<ast::Expr>) -> Option<P<ast::Expr>> { /// reveal the precedence of the parsed expressions, and produce a stringified /// form of the resulting expression. fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr { - use syn::fold::{fold_expr, fold_generic_argument, fold_generic_method_argument, Fold}; - use syn::{ - token, BinOp, Expr, ExprParen, GenericArgument, GenericMethodArgument, MetaNameValue, Pat, - Stmt, Type, - }; + use syn::fold::{fold_expr, fold_generic_argument, Fold}; + use syn::{token, BinOp, Expr, ExprParen, GenericArgument, MetaNameValue, Pat, Stmt, Type}; struct ParenthesizeEveryExpr; impl Fold for ParenthesizeEveryExpr { @@ -396,20 +393,6 @@ fn syn_brackets(syn_expr: syn::Expr) -> syn::Expr { } } - fn fold_generic_method_argument( - &mut self, - arg: GenericMethodArgument, - ) -> GenericMethodArgument { - match arg { - GenericMethodArgument::Const(arg) => GenericMethodArgument::Const(match arg { - Expr::Block(_) => fold_expr(self, arg), - // Don't wrap unbraced const generic arg as that's invalid syntax. - _ => arg, - }), - _ => fold_generic_method_argument(self, arg), - } - } - fn fold_stmt(&mut self, stmt: Stmt) -> Stmt { match stmt { // Don't wrap toplevel expressions in statements.
diff --git a/src/expr.rs b/src/expr.rs index e142149ce..ad8909f7a 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -866,26 +866,11 @@ ast_struct! { pub struct MethodTurbofish { pub colon2_token: Token![::], pub lt_token: Token![<], - pub args: Punctuated<GenericMethodArgument, Token![,]>, + pub args: Punctuated<GenericArgument, Token![,]>, pub gt_token: Token![>], } } -#[cfg(feature = "full")] -ast_enum! { - /// An individual generic argument to a method, like `T`. - #[cfg_attr(doc_cfg, doc(cfg(feature = "full")))] - pub enum GenericMethodArgument { - /// A type argument. - Type(Type), - /// A const expression. Must be inside of a block. - /// - /// NOTE: Identity expressions are represented as Type arguments, as - /// they are indistinguishable syntactically. - Const(Expr), - } -} - #[cfg(feature = "full")] ast_struct! { /// A field-value pair in a struct literal. @@ -1961,24 +1946,6 @@ pub(crate) mod parsing { }) } - #[cfg(feature = "full")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] - impl Parse for GenericMethodArgument { - fn parse(input: ParseStream) -> Result<Self> { - if input.peek(Lit) { - let lit = input.parse()?; - return Ok(GenericMethodArgument::Const(Expr::Lit(lit))); - } - - if input.peek(token::Brace) { - let block: ExprBlock = input.parse()?; - return Ok(GenericMethodArgument::Const(Expr::Block(block))); - } - - input.parse().map(GenericMethodArgument::Type) - } - } - #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))] impl Parse for MethodTurbofish { @@ -1992,7 +1959,7 @@ pub(crate) mod parsing { if input.peek(Token![>]) { break; } - let value: GenericMethodArgument = input.parse()?; + let value: GenericArgument = input.parse()?; args.push_value(value); if input.peek(Token![>]) { break; @@ -2899,17 +2866,6 @@ pub(crate) mod printing { } } - #[cfg(feature = "full")] - #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] - impl ToTokens for GenericMethodArgument { - fn to_tokens(&self, tokens: &mut TokenStream) { - match self { - GenericMethodArgument::Type(t) => t.to_tokens(tokens), - GenericMethodArgument::Const(c) => c.to_tokens(tokens), - } - } - } - #[cfg(feature = "full")] #[cfg_attr(doc_cfg, doc(cfg(feature = "printing")))] impl ToTokens for ExprTuple { diff --git a/src/gen/clone.rs b/src/gen/clone.rs index 52b43a82e..cf7f3a419 100644 --- a/src/gen/clone.rs +++ b/src/gen/clone.rs @@ -913,16 +913,6 @@ impl Clone for GenericArgument { } } } -#[cfg(feature = "full")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] -impl Clone for GenericMethodArgument { - fn clone(&self) -> Self { - match self { - GenericMethodArgument::Type(v0) => GenericMethodArgument::Type(v0.clone()), - GenericMethodArgument::Const(v0) => GenericMethodArgument::Const(v0.clone()), - } - } -} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))] impl Clone for GenericParam { diff --git a/src/gen/debug.rs b/src/gen/debug.rs index 52e51d56a..da7b45e15 100644 --- a/src/gen/debug.rs +++ b/src/gen/debug.rs @@ -1283,24 +1283,6 @@ impl Debug for GenericArgument { } } } -#[cfg(feature = "full")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Debug for GenericMethodArgument { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self { - GenericMethodArgument::Type(v0) => { - let mut formatter = formatter.debug_tuple("Type"); - formatter.field(v0); - formatter.finish() - } - GenericMethodArgument::Const(v0) => { - let mut formatter = formatter.debug_tuple("Const"); - formatter.field(v0); - formatter.finish() - } - } - } -} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Debug for GenericParam { diff --git a/src/gen/eq.rs b/src/gen/eq.rs index 55990ad92..384988c26 100644 --- a/src/gen/eq.rs +++ b/src/gen/eq.rs @@ -891,25 +891,6 @@ impl PartialEq for GenericArgument { } } } -#[cfg(feature = "full")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Eq for GenericMethodArgument {} -#[cfg(feature = "full")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl PartialEq for GenericMethodArgument { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (GenericMethodArgument::Type(self0), GenericMethodArgument::Type(other0)) => { - self0 == other0 - } - ( - GenericMethodArgument::Const(self0), - GenericMethodArgument::Const(other0), - ) => self0 == other0, - _ => false, - } - } -} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Eq for GenericParam {} diff --git a/src/gen/fold.rs b/src/gen/fold.rs index 4d04f2e65..953d5461e 100644 --- a/src/gen/fold.rs +++ b/src/gen/fold.rs @@ -314,13 +314,6 @@ pub trait Fold { fn fold_generic_argument(&mut self, i: GenericArgument) -> GenericArgument { fold_generic_argument(self, i) } - #[cfg(feature = "full")] - fn fold_generic_method_argument( - &mut self, - i: GenericMethodArgument, - ) -> GenericMethodArgument { - fold_generic_method_argument(self, i) - } #[cfg(any(feature = "derive", feature = "full"))] fn fold_generic_param(&mut self, i: GenericParam) -> GenericParam { fold_generic_param(self, i) @@ -1771,23 +1764,6 @@ where } } } -#[cfg(feature = "full")] -pub fn fold_generic_method_argument<F>( - f: &mut F, - node: GenericMethodArgument, -) -> GenericMethodArgument -where - F: Fold + ?Sized, -{ - match node { - GenericMethodArgument::Type(_binding_0) => { - GenericMethodArgument::Type(f.fold_type(_binding_0)) - } - GenericMethodArgument::Const(_binding_0) => { - GenericMethodArgument::Const(f.fold_expr(_binding_0)) - } - } -} #[cfg(any(feature = "derive", feature = "full"))] pub fn fold_generic_param<F>(f: &mut F, node: GenericParam) -> GenericParam where @@ -2424,7 +2400,7 @@ where MethodTurbofish { colon2_token: Token![::](tokens_helper(f, &node.colon2_token.spans)), lt_token: Token![<](tokens_helper(f, &node.lt_token.spans)), - args: FoldHelper::lift(node.args, |it| f.fold_generic_method_argument(it)), + args: FoldHelper::lift(node.args, |it| f.fold_generic_argument(it)), gt_token: Token![>](tokens_helper(f, &node.gt_token.spans)), } } diff --git a/src/gen/hash.rs b/src/gen/hash.rs index 0c077b3dd..2a4cc3b1c 100644 --- a/src/gen/hash.rs +++ b/src/gen/hash.rs @@ -1197,25 +1197,6 @@ impl Hash for GenericArgument { } } } -#[cfg(feature = "full")] -#[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] -impl Hash for GenericMethodArgument { - fn hash<H>(&self, state: &mut H) - where - H: Hasher, - { - match self { - GenericMethodArgument::Type(v0) => { - state.write_u8(0u8); - v0.hash(state); - } - GenericMethodArgument::Const(v0) => { - state.write_u8(1u8); - v0.hash(state); - } - } - } -} #[cfg(any(feature = "derive", feature = "full"))] #[cfg_attr(doc_cfg, doc(cfg(feature = "extra-traits")))] impl Hash for GenericParam { diff --git a/src/gen/visit.rs b/src/gen/visit.rs index 8bd9ae6ad..5d6fa2962 100644 --- a/src/gen/visit.rs +++ b/src/gen/visit.rs @@ -316,10 +316,6 @@ pub trait Visit<'ast> { fn visit_generic_argument(&mut self, i: &'ast GenericArgument) { visit_generic_argument(self, i); } - #[cfg(feature = "full")] - fn visit_generic_method_argument(&mut self, i: &'ast GenericMethodArgument) { - visit_generic_method_argument(self, i); - } #[cfg(any(feature = "derive", feature = "full"))] fn visit_generic_param(&mut self, i: &'ast GenericParam) { visit_generic_param(self, i); @@ -1965,23 +1961,6 @@ where } } } -#[cfg(feature = "full")] -pub fn visit_generic_method_argument<'ast, V>( - v: &mut V, - node: &'ast GenericMethodArgument, -) -where - V: Visit<'ast> + ?Sized, -{ - match node { - GenericMethodArgument::Type(_binding_0) => { - v.visit_type(_binding_0); - } - GenericMethodArgument::Const(_binding_0) => { - v.visit_expr(_binding_0); - } - } -} #[cfg(any(feature = "derive", feature = "full"))] pub fn visit_generic_param<'ast, V>(v: &mut V, node: &'ast GenericParam) where @@ -2692,7 +2671,7 @@ where tokens_helper(v, &node.lt_token.spans); for el in Punctuated::pairs(&node.args) { let (it, p) = el.into_tuple(); - v.visit_generic_method_argument(it); + v.visit_generic_argument(it); if let Some(p) = p { tokens_helper(v, &p.spans); } diff --git a/src/gen/visit_mut.rs b/src/gen/visit_mut.rs index abf3b5b90..e9453b992 100644 --- a/src/gen/visit_mut.rs +++ b/src/gen/visit_mut.rs @@ -317,10 +317,6 @@ pub trait VisitMut { fn visit_generic_argument_mut(&mut self, i: &mut GenericArgument) { visit_generic_argument_mut(self, i); } - #[cfg(feature = "full")] - fn visit_generic_method_argument_mut(&mut self, i: &mut GenericMethodArgument) { - visit_generic_method_argument_mut(self, i); - } #[cfg(any(feature = "derive", feature = "full"))] fn visit_generic_param_mut(&mut self, i: &mut GenericParam) { visit_generic_param_mut(self, i); @@ -1966,20 +1962,6 @@ where } } } -#[cfg(feature = "full")] -pub fn visit_generic_method_argument_mut<V>(v: &mut V, node: &mut GenericMethodArgument) -where - V: VisitMut + ?Sized, -{ - match node { - GenericMethodArgument::Type(_binding_0) => { - v.visit_type_mut(_binding_0); - } - GenericMethodArgument::Const(_binding_0) => { - v.visit_expr_mut(_binding_0); - } - } -} #[cfg(any(feature = "derive", feature = "full"))] pub fn visit_generic_param_mut<V>(v: &mut V, node: &mut GenericParam) where @@ -2692,7 +2674,7 @@ where tokens_helper(v, &mut node.lt_token.spans); for el in Punctuated::pairs_mut(&mut node.args) { let (it, p) = el.into_tuple(); - v.visit_generic_method_argument_mut(it); + v.visit_generic_argument_mut(it); if let Some(p) = p { tokens_helper(v, &mut p.spans); } diff --git a/src/lib.rs b/src/lib.rs index 2f5c4d34b..617500ac2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -345,9 +345,7 @@ pub use crate::error::{Error, Result}; #[cfg(any(feature = "full", feature = "derive"))] mod expr; #[cfg(feature = "full")] -pub use crate::expr::{ - Arm, FieldValue, GenericMethodArgument, Label, MethodTurbofish, RangeLimits, -}; +pub use crate::expr::{Arm, FieldValue, Label, MethodTurbofish, RangeLimits}; #[cfg(any(feature = "full", feature = "derive"))] pub use crate::expr::{ Expr, ExprArray, ExprAssign, ExprAssignOp, ExprAsync, ExprAwait, ExprBinary, ExprBlock, diff --git a/syn.json b/syn.json index c749cfa56..d8b59577f 100644 --- a/syn.json +++ b/syn.json @@ -2261,26 +2261,6 @@ ] } }, - { - "ident": "GenericMethodArgument", - "features": { - "any": [ - "full" - ] - }, - "variants": { - "Type": [ - { - "syn": "Type" - } - ], - "Const": [ - { - "syn": "Expr" - } - ] - } - }, { "ident": "GenericParam", "features": { @@ -3617,7 +3597,7 @@ "args": { "punctuated": { "element": { - "syn": "GenericMethodArgument" + "syn": "GenericArgument" }, "punct": "Comma" }
Parse lifetime args inside of turbofish This is apparently legal Rust syntax. It takes some effort to come up with code with lifetimes inside turbofish which rustc will accept without hitting https://github.com/rust-lang/rust/issues/42868, but here is one such example: ```rust struct Struct; impl Struct { fn f<'a: 'a>(&'a self) {} } fn main() { Struct.f::<'static>(); } ``` Syn currently doesn't parse this syntax, it assumes the turbofish contains only types and constant expressions, and treats the lifetime as if it were a bound of a 2015-edition syntax trait object type. ```console error: at least one trait is required for an object type --> dev/main.rs:8:16 | 8 | Struct.f::<'static>(); | ^^^^^^^ ```
dtolnay/syn
b7b288a0cb569a8e0c175ee675939929c5f3f202
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1