Skip to content

Commit

Permalink
Organize how the caller determines which attrs to parse
Browse files Browse the repository at this point in the history
In preparation for parsing even more attributes, such as `repr`.
  • Loading branch information
dtolnay committed May 10, 2020
1 parent e86b9cf commit b129ea7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
33 changes: 21 additions & 12 deletions syntax/attrs.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
use crate::syntax::{Derive, Doc};
use proc_macro2::Ident;
use syn::parse::{ParseStream, Parser};
use syn::parse::{ParseStream, Parser as _};
use syn::{Attribute, Error, LitStr, Path, Result, Token};

#[derive(Default)]
pub struct Parser<'a> {
pub doc: Option<&'a mut Doc>,
pub derives: Option<&'a mut Vec<Derive>>,
}

pub(super) fn parse_doc(attrs: &[Attribute]) -> Result<Doc> {
let mut doc = Doc::new();
let derives = None;
parse(attrs, &mut doc, derives)?;
parse(
attrs,
Parser {
doc: Some(&mut doc),
..Parser::default()
},
)?;
Ok(doc)
}

pub(super) fn parse(
attrs: &[Attribute],
doc: &mut Doc,
mut derives: Option<&mut Vec<Derive>>,
) -> Result<()> {
pub(super) fn parse(attrs: &[Attribute], mut parser: Parser) -> Result<()> {
for attr in attrs {
if attr.path.is_ident("doc") {
let lit = parse_doc_attribute.parse2(attr.tokens.clone())?;
doc.push(lit);
continue;
if let Some(doc) = &mut parser.doc {
let lit = parse_doc_attribute.parse2(attr.tokens.clone())?;
doc.push(lit);
continue;
}
} else if attr.path.is_ident("derive") {
if let Some(derives) = &mut derives {
if let Some(derives) = &mut parser.derives {
derives.extend(attr.parse_args_with(parse_derive_attribute)?);
continue;
}
Expand Down
8 changes: 7 additions & 1 deletion syntax/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,13 @@ fn parse_struct(item: ItemStruct) -> Result<Api> {

let mut doc = Doc::new();
let mut derives = Vec::new();
attrs::parse(&item.attrs, &mut doc, Some(&mut derives))?;
attrs::parse(
&item.attrs,
attrs::Parser {
doc: Some(&mut doc),
derives: Some(&mut derives),
},
)?;

let fields = match item.fields {
Fields::Named(fields) => fields,
Expand Down

0 comments on commit b129ea7

Please sign in to comment.