Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support parsing Field in parse_quote #1548

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/parse_quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ impl<T: Parse> ParseQuote for T {

use crate::punctuated::Punctuated;
#[cfg(any(feature = "full", feature = "derive"))]
use crate::{attr, Attribute};
use crate::{attr, Attribute, Field, FieldMutability, Ident, Type, Visibility};
#[cfg(feature = "full")]
use crate::{Block, Pat, Stmt};

Expand All @@ -151,6 +151,36 @@ impl ParseQuote for Attribute {
}
}

#[cfg(any(feature = "full", feature = "derive"))]
impl ParseQuote for Field {
fn parse(input: ParseStream) -> Result<Self> {
let attrs = input.call(Attribute::parse_outer)?;
let vis: Visibility = input.parse()?;

let ident: Option<Ident>;
let colon_token: Option<Token![:]>;
let is_named = input.peek(Ident) && input.peek2(Token![:]) && !input.peek2(Token![::]);
if is_named {
ident = Some(input.parse()?);
colon_token = Some(input.parse()?);
} else {
ident = None;
colon_token = None;
}

let ty: Type = input.parse()?;

Ok(Field {
attrs,
vis,
mutability: FieldMutability::None,
ident,
colon_token,
ty,
})
}
}

#[cfg(feature = "full")]
impl ParseQuote for Pat {
fn parse(input: ParseStream) -> Result<Self> {
Expand Down
42 changes: 41 additions & 1 deletion tests/test_parse_quote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
mod macros;

use syn::punctuated::Punctuated;
use syn::{parse_quote, Attribute, Lit, Pat, Stmt, Token};
use syn::{parse_quote, Attribute, Field, Lit, Pat, Stmt, Token};

#[test]
fn test_attribute() {
Expand Down Expand Up @@ -35,6 +35,46 @@ fn test_attribute() {
"###);
}

#[test]
fn test_field() {
let field: Field = parse_quote!(pub enabled: bool);
snapshot!(field, @r###"
Field {
vis: Visibility::Public,
ident: Some("enabled"),
colon_token: Some,
ty: Type::Path {
path: Path {
segments: [
PathSegment {
ident: "bool",
},
],
},
},
}
"###);

let field: Field = parse_quote!(primitive::bool);
snapshot!(field, @r###"
Field {
vis: Visibility::Inherited,
ty: Type::Path {
path: Path {
segments: [
PathSegment {
ident: "primitive",
},
PathSegment {
ident: "bool",
},
],
},
},
}
"###);
}

#[test]
fn test_pat() {
let pat: Pat = parse_quote!(Some(false) | None);
Expand Down