Skip to content

Commit

Permalink
Merge pull request #1548 from dtolnay/parsequotefield
Browse files Browse the repository at this point in the history
Support parsing Field in parse_quote
  • Loading branch information
dtolnay authored Dec 12, 2023
2 parents 2ab0f6a + 5e15924 commit 920ab7d
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
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

0 comments on commit 920ab7d

Please sign in to comment.