Detect duplicate source attributes

This commit is contained in:
David Tolnay 2019-10-12 13:01:13 -07:00
parent ae085b0863
commit d42a95076c
No known key found for this signature in database
GPG key ID: F9BA143B95FF6D82
6 changed files with 83 additions and 24 deletions

View file

@ -1,4 +1,4 @@
use crate::ast::{Enum, Input, Struct};
use crate::ast::{Enum, Field, Input, Struct, Variant};
use syn::{Error, Result};
pub(crate) const CHECKED: &str = "checked in validation";
@ -14,23 +14,46 @@ impl Input<'_> {
impl Struct<'_> {
fn validate(&self) -> Result<()> {
// nothing for now
find_duplicate_source(&self.fields)?;
Ok(())
}
}
impl Enum<'_> {
fn validate(&self) -> Result<()> {
if self.has_display() {
for variant in &self.variants {
if variant.attrs.display.is_none() {
return Err(Error::new_spanned(
variant.original,
"missing #[error(\"...\")] display attribute",
));
}
let has_display = self.has_display();
for variant in &self.variants {
variant.validate()?;
if has_display && variant.attrs.display.is_none() {
return Err(Error::new_spanned(
variant.original,
"missing #[error(\"...\")] display attribute",
));
}
}
Ok(())
}
}
impl Variant<'_> {
fn validate(&self) -> Result<()> {
find_duplicate_source(&self.fields)?;
Ok(())
}
}
fn find_duplicate_source(fields: &[Field]) -> Result<()> {
let mut has_source = false;
for field in fields {
if let Some(source) = &field.attrs.source {
if has_source {
return Err(Error::new_spanned(
source.original,
"duplicate #[source] attribute",
));
}
has_source = true;
}
}
Ok(())
}