Skip to content

Commit

Permalink
simplify id column parse
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonThormeyer committed Jan 30, 2025
1 parent 8a01ccc commit 165fdea
Showing 1 changed file with 33 additions and 46 deletions.
79 changes: 33 additions & 46 deletions crypto-macros/src/entity_derive/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,45 +75,48 @@ impl IdColumn {
fn parse(named_fields: &FieldsNamed) -> syn::Result<Self> {
let mut id = None;
let mut implicit_id = None;
let mut column_name = None;
let mut transformation = None;
for field in named_fields.named.iter() {

for field in &named_fields.named {
let name = field
.ident
.as_ref()
.expect("named fields always have identifiers")
.clone();

if let Some(attr) = field.attrs.iter().find(|attr| attr.path().is_ident("id")) {
let meta = &attr.meta;
if let Ok(list) = meta.require_list() {
if let Some(attr) = field.attrs.iter().find(|a| a.path().is_ident("id")) {
let mut column_name = None;
let mut transformation = None;
let column_type = IdColumnType::parse(&field.ty)?;

if let Ok(list) = attr.meta.require_list() {
list.parse_nested_meta(|meta| {
let ident = meta.path.require_ident()?;
match ident.to_string().as_str() {
match meta.path.require_ident()?.to_string().as_str() {
"column" => {
meta.input.parse::<Token![=]>()?;
column_name = Some(meta.input.parse::<syn::LitStr>()?.value());
Ok(())
}
"hex" => {
transformation = Some(IdTransformation::Hex);
Ok(())
}
_ => Err(syn::Error::new_spanned(ident, format!("unknown argument: {ident}"))),
"hex" => transformation = Some(IdTransformation::Hex),
_ => return Err(syn::Error::new_spanned(meta.path, "unknown argument")),
}
Ok(())
})?;
}

let column_type = IdColumnType::parse(&field.ty)?;

id = Some(IdColumn {
name,
column_type,
column_name,
transformation,
});
break;
} else if name.to_string() == "id" {
if id
.replace(IdColumn {
name,
column_type,
column_name,
transformation,
})
.is_some()
{
return Err(syn::Error::new_spanned(
named_fields,
"Ambiguous `#[id]` attributes. Provide exactly one.",
));
}
} else if name == "id" {
let column_type = IdColumnType::parse(&field.ty)?;
implicit_id = Some(IdColumn {
name,
Expand All @@ -124,28 +127,12 @@ impl IdColumn {
}
}

// Ensure at max one field has the #[id] attribute
if id.is_some() {
if named_fields
.named
.iter()
.flat_map(|field| field.attrs.iter())
.filter(|attr| attr.path().is_ident("id"))
.count()
> 1
{
return Err(syn::Error::new_spanned(
named_fields,
"Ambiguous `#[id]` attributes. Provide exactly one.",
));
}
}

id = id.or(implicit_id);
id.ok_or(syn::Error::new_spanned(
named_fields,
"No field named `id` or annotated `#[id]` attribute provided.",
))
id.or(implicit_id).ok_or_else(|| {
syn::Error::new_spanned(
named_fields,
"No field named `id` or annotated `#[id]` attribute provided.",
)
})
}
}

Expand Down

0 comments on commit 165fdea

Please sign in to comment.