From f18ab272575f99f7b7b0a5d461a7612b476aa5fa Mon Sep 17 00:00:00 2001 From: Daniel Thaler Date: Mon, 2 Sep 2024 17:48:07 +0200 Subject: [PATCH] generate enums with values for A2ML if possible If each item in the A2ML enum has a value (e.g. OPTIONAL_CMD), then the generated Rust enum also uses these values. --- a2lmacros/src/codegenerator/data_structure.rs | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/a2lmacros/src/codegenerator/data_structure.rs b/a2lmacros/src/codegenerator/data_structure.rs index a142469..9cfe30c 100644 --- a/a2lmacros/src/codegenerator/data_structure.rs +++ b/a2lmacros/src/codegenerator/data_structure.rs @@ -47,15 +47,33 @@ pub(crate) fn generate(typename: &str, dataitem: &DataItem) -> TokenStream { fn generate_enum_data_structure(typename: &str, enumitems: &[EnumItem]) -> TokenStream { let typeident = format_ident!("{}", typename); - let enumidents: Vec = enumitems - .iter() - .map(|enumitem| format_ident!("{}", ucname_to_typename(&enumitem.name))) - .collect(); + // check if all enum items have a value assigned + let use_values = enumitems.iter().all(|item| item.value.is_some()); + let enum_defs: Vec = if !use_values { + // if no values are assigned, the enum items are just listed without values + enumitems + .iter() + .map(|enumitem| { + let ident = format_ident!("{}", ucname_to_typename(&enumitem.name)); + quote! {#ident} + }) + .collect() + } else { + // if values are assigned, the enum items are listed with values + enumitems + .iter() + .map(|enumitem| { + let ident = format_ident!("{}", ucname_to_typename(&enumitem.name)); + let value = *enumitem.value.as_ref().unwrap() as isize; + quote! {#ident = #value} + }) + .collect() + }; quote! { #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum #typeident { - #(#enumidents),* + #(#enum_defs),* } } }