rust-mavlink icon indicating copy to clipboard operation
rust-mavlink copied to clipboard

Enum entries without value are generated wrong.

Open pv42 opened this issue 6 months ago • 0 comments

On the latest 0.13.1 version a dialect containing an enum definition without explicit entry value assignments such as

<enum name="TEST_ENUM">
  <description>This is just for testing the bindgen</description>
  <entry name="TEST_ENTRY"></entry>
  <entry name="TEST_ENTRY2"></entry>
</enum>

will generate the following code (here with the format-generated-code feature):

#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
#[repr(u32)]
pub enum TestEnum {
    TEST_ENTRY = 1isize,
    TEST_ENTRY2 = 2isize,
}

This causes an error since the enum is tagged repr(u32) while the entries are isize. This was previously not the case in 0.11.2, but I am unsure when and why it broke.

The wrong type assignment of the enum entries can be fixed by changing parser.rs in mavlink-bindgen:

@@ -308,7 +308,7 @@ impl MavEnum {
     }
 
     fn emit_defs(&self) -> Vec<TokenStream> {
-        let mut cnt = 0isize;
+        let mut cnt = 0u32;
         self.entries
             .iter()
             .map(|enum_entry| {
@@ -330,7 +330,7 @@ impl MavEnum {
                     value = quote!(#cnt);
                 } else {
                     let tmp_value = enum_entry.value.unwrap();
-                    cnt = cnt.max(tmp_value as isize);
+                    cnt = cnt.max(tmp_value as u32);
                     let tmp = TokenStream::from_str(&tmp_value.to_string()).unwrap();
                     value = quote!(#tmp);
                 };

The generated code then look like this:

#[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
#[repr(u32)]
pub enum TestEnum {
    TEST_ENTRY = 1u32,
    TEST_ENTRY2 = 2u32,
}

Alternatively the enums could be tagged repr(isize) instead. When generating with explicit value the type annotations of the enum value are omitted in the generated code (e.g. TEST_ENTRY = 1, ...).

pv42 avatar Jul 30 '24 10:07 pv42