Slightly simplify attribute parsing code

This commit is contained in:
Jonas Platte 2019-11-11 22:28:43 +01:00
parent e8858f119d
commit 47267cc2ba
No known key found for this signature in database
GPG Key ID: 7D261D771D915378
3 changed files with 22 additions and 18 deletions

View File

@ -14,23 +14,27 @@ pub enum Meta {
}
impl Meta {
/// Check if the given attribute is a ruma_api attribute. If it is, parse it, if not, return
/// it unchanged. Panics if the argument is an invalid ruma_api attribute.
pub fn from_attribute(attr: syn::Attribute) -> Result<Self, syn::Attribute> {
/// Check if the given attribute is a ruma_api attribute. If it is, parse it.
///
/// # Panics
///
/// Panics if the given attribute is a ruma_api attribute, but fails to parse.
pub fn from_attribute(attr: &syn::Attribute) -> Option<Self> {
match &attr.path {
syn::Path {
leading_colon: None,
segments,
} => {
if segments.len() == 1 && segments[0].ident == "ruma_api" {
Ok(attr
.parse_args()
.expect("ruma_api! could not parse request field attributes"))
Some(
attr.parse_args()
.expect("ruma_api! could not parse request field attributes"),
)
} else {
Err(attr)
None
}
}
_ => Err(attr),
_ => None,
}
}
}

View File

@ -134,10 +134,10 @@ impl From<Vec<Field>> for Request {
let mut field_kind = RequestFieldKind::Body;
let mut header = None;
field.attrs = field.attrs.into_iter().filter_map(|attr| {
field.attrs.retain(|attr| {
let meta = match Meta::from_attribute(attr) {
Ok(meta) => meta,
Err(attr) => return Some(attr),
Some(meta) => meta,
None => return true,
};
match meta {
@ -163,8 +163,8 @@ impl From<Vec<Field>> for Request {
}
}
None
}).collect();
false
});
if field_kind == RequestFieldKind::Body {
assert!(

View File

@ -104,10 +104,10 @@ impl From<Vec<Field>> for Response {
let mut field_kind = ResponseFieldKind::Body;
let mut header = None;
field.attrs = field.attrs.into_iter().filter_map(|attr| {
field.attrs.retain(|attr| {
let meta = match Meta::from_attribute(attr) {
Ok(meta) => meta,
Err(attr) => return Some(attr),
Some(meta) => meta,
None => return true,
};
match meta {
@ -131,8 +131,8 @@ impl From<Vec<Field>> for Response {
}
}
None
}).collect();
false
});
match field_kind {
ResponseFieldKind::Body => {