Skip to main content

mavlink_bindgen/
parser.rs

1use crc_any::CRCu16;
2use std::cmp::Ordering;
3use std::collections::btree_map::Entry;
4use std::collections::{BTreeMap, HashSet};
5use std::default::Default;
6use std::fmt::Display;
7use std::io::Write;
8use std::path::{Path, PathBuf};
9use std::str::FromStr;
10use std::sync::LazyLock;
11
12use regex::Regex;
13
14use quick_xml::{Reader, escape::resolve_xml_entity, events::Event};
15
16use proc_macro2::{Ident, Literal, TokenStream};
17use quote::{format_ident, quote};
18
19#[cfg(feature = "serde")]
20use serde::{Deserialize, Serialize};
21
22use crate::error::BindGenError;
23use crate::util;
24
25static URL_REGEX: LazyLock<Regex> = LazyLock::new(|| {
26    Regex::new(concat!(
27        r"(https?://",                                               // url scheme
28        r"([-a-zA-Z0-9@:%._\+~#=]{2,256}\.)+",                       // one or more subdomains
29        r"[a-zA-Z]{2,63}",                                           // root domain
30        r"\b([-a-zA-Z0-9@:%_\+.~#?&/=]*[-a-zA-Z0-9@:%_\+~#?&/=])?)", // optional query or url fragments
31    ))
32    .expect("failed to build regex")
33});
34
35#[derive(Debug, PartialEq, Clone, Default)]
36#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
37pub struct MavProfile {
38    pub messages: BTreeMap<String, MavMessage>,
39    pub enums: BTreeMap<String, MavEnum>,
40    pub version: Option<u8>,
41    pub dialect: Option<u8>,
42}
43
44impl MavProfile {
45    fn add_message(&mut self, message: &MavMessage) {
46        match self.messages.entry(message.name.clone()) {
47            Entry::Occupied(entry) => {
48                assert!(
49                    entry.get() == message,
50                    "Message '{}' defined twice but definitions are different",
51                    message.name
52                );
53            }
54            Entry::Vacant(entry) => {
55                entry.insert(message.clone());
56            }
57        }
58    }
59
60    fn add_enum(&mut self, enm: &MavEnum) {
61        match self.enums.entry(enm.name.clone()) {
62            Entry::Occupied(entry) => {
63                entry.into_mut().try_combine(enm);
64            }
65            Entry::Vacant(entry) => {
66                entry.insert(enm.clone());
67            }
68        }
69    }
70
71    /// Go over all fields in the messages, and if you encounter an enum,
72    /// which is a bitmask, set the bitmask size based on field size
73    fn update_enums(mut self) -> Self {
74        for msg in self.messages.values_mut() {
75            for field in &mut msg.fields {
76                if let Some(enum_name) = &field.enumtype {
77                    // find the corresponding enum
78                    if let Some(enm) = self.enums.get_mut(enum_name) {
79                        // Handle legacy definition where bitmask is defined as display="bitmask"
80                        if field.display == Some("bitmask".to_string()) {
81                            enm.bitmask = true;
82                        }
83
84                        // it is a bitmask
85                        if enm.bitmask {
86                            // check if any enum values can be stored in the fields
87                            let mut any_fit = false;
88                            let mut all_fit = true;
89                            for entry in &enm.entries {
90                                if field.mavtype.max_int_value() < entry.value.unwrap_or_default() {
91                                    field.is_undersized = true;
92                                    enm.additional_primitives.insert(field.mavtype.clone());
93                                    all_fit = false;
94                                } else {
95                                    any_fit = true;
96                                }
97                            }
98                            assert!(
99                                any_fit,
100                                "bitflag enum field {} of {} must be able to fit at least one possible value {}",
101                                field.name, msg.name, enum_name,
102                            );
103
104                            if all_fit {
105                                enm.primitive = Some(field.mavtype.clone());
106                            }
107
108                            // Fix fields in backwards manner
109                            if field.display.is_none() {
110                                field.display = Some("bitmask".to_string());
111                            }
112                        }
113                    }
114                }
115            }
116        }
117        for enm in self.enums.values_mut() {
118            if enm.bitmask && enm.primitive.is_none() {
119                let max = enm
120                    .entries
121                    .iter()
122                    .filter_map(|e| e.value)
123                    .max()
124                    .unwrap_or_default();
125                let primitive = match max {
126                    max if max <= u16::MAX as u64 => MavType::UInt16,
127                    max if max <= u32::MAX as u64 => MavType::UInt32,
128                    _ => MavType::UInt64,
129                };
130                enm.primitive = Some(primitive);
131            }
132        }
133        self
134    }
135
136    /// Simple header comment
137    #[inline(always)]
138    fn emit_comments(&self, dialect_name: &str) -> TokenStream {
139        let message = format!("MAVLink {dialect_name} dialect.");
140        quote!(
141            #![doc = #message]
142            #![doc = ""]
143            #![doc = "This file was automatically generated, do not edit."]
144        )
145    }
146
147    /// Emit rust messages
148    #[inline(always)]
149    fn emit_msgs(&self) -> Vec<TokenStream> {
150        self.messages
151            .values()
152            .map(|d| d.emit_rust(self.version.is_some()))
153            .collect()
154    }
155
156    /// Emit rust enums
157    #[inline(always)]
158    fn emit_enums(&self) -> Vec<TokenStream> {
159        self.enums.values().map(|d| d.emit_rust()).collect()
160    }
161
162    #[inline(always)]
163    fn emit_lifecycles(&self) -> Vec<TokenStream> {
164        self.messages
165            .values()
166            .map(|msg| {
167                msg.lifecycle
168                    .as_ref()
169                    .map(|d| d.emit_tokens())
170                    .unwrap_or_default()
171            })
172            .collect()
173    }
174
175    #[inline(always)]
176    fn emit_wips(&self) -> Vec<TokenStream> {
177        self.messages.values().map(|msg| msg.emit_wip()).collect()
178    }
179
180    /// Get list of original message names
181    #[inline(always)]
182    fn emit_enum_names(&self) -> Vec<TokenStream> {
183        self.messages
184            .values()
185            .map(|msg| {
186                let name = format_ident!("{}", msg.name);
187                quote!(#name)
188            })
189            .collect()
190    }
191
192    /// Emit message names with "_DATA" at the end
193    #[inline(always)]
194    fn emit_struct_names(&self) -> Vec<TokenStream> {
195        self.messages
196            .values()
197            .map(|msg| msg.emit_struct_name())
198            .collect()
199    }
200
201    fn emit_rust(&self, dialect_name: &str) -> TokenStream {
202        let id_width = format_ident!("u32");
203
204        let comment = self.emit_comments(dialect_name);
205        let mav_minor_version = self.emit_minor_version();
206        let mav_dialect_number = self.emit_dialect_number();
207        let msgs = self.emit_msgs();
208        let lifecycles = self.emit_lifecycles();
209        let enum_names = self.emit_enum_names();
210        let struct_names = self.emit_struct_names();
211        let wips = self.emit_wips();
212        let enums = self.emit_enums();
213
214        let variant_docs = self.emit_variant_description();
215
216        let mav_message =
217            self.emit_mav_message(&variant_docs, &lifecycles, &enum_names, &struct_names);
218        let mav_message_all_ids = self.emit_mav_message_all_ids();
219        let mav_message_all_messages = self.emit_mav_message_all_messages();
220        let mav_message_parse = self.emit_mav_message_parse(&enum_names, &struct_names, &wips);
221        let mav_message_crc = self.emit_mav_message_crc(&id_width, &struct_names, &wips);
222        let mav_message_name = self.emit_mav_message_name(&enum_names, &struct_names, &wips);
223        let mav_message_id = self.emit_mav_message_id(&enum_names, &struct_names, &wips);
224        let mav_message_id_from_name = self.emit_mav_message_id_from_name(&struct_names, &wips);
225        let mav_message_default_from_id =
226            self.emit_mav_message_default_from_id(&enum_names, &struct_names, &wips);
227        let mav_message_random_from_id =
228            self.emit_mav_message_random_from_id(&enum_names, &struct_names, &wips);
229        let mav_message_serialize = self.emit_mav_message_serialize(&enum_names, &wips);
230        let mav_message_target_system_and_component = self.emit_mav_message_target_accessors();
231
232        quote! {
233            #comment
234            #![allow(deprecated)]
235            #![allow(clippy::match_single_binding)]
236            #![allow(rustdoc::broken_intra_doc_links)]
237            #[allow(unused_imports)]
238            use num_derive::{FromPrimitive, ToPrimitive};
239            #[allow(unused_imports)]
240            use num_traits::{FromPrimitive, ToPrimitive};
241            #[allow(unused_imports)]
242            use bitflags::{bitflags, Flags};
243            #[allow(unused_imports)]
244            use mavlink_core::{MavlinkVersion, Message, MessageData, bytes::Bytes, bytes_mut::BytesMut, types::CharArray};
245
246            #[cfg(feature = "serde")]
247            use serde::{Serialize, Deserialize};
248
249            #[cfg(feature = "arbitrary")]
250            use arbitrary::Arbitrary;
251
252            #[cfg(feature = "ts-rs")]
253            use ts_rs::TS;
254
255            #mav_minor_version
256            #mav_dialect_number
257
258            #(#enums)*
259
260            #(#msgs)*
261
262            #[derive(Clone, PartialEq, Debug)]
263            #mav_message
264
265            impl MavMessage {
266                #mav_message_all_ids
267                #mav_message_all_messages
268            }
269
270            impl Message for MavMessage {
271                #mav_message_parse
272                #mav_message_name
273                #mav_message_id
274                #mav_message_id_from_name
275                #mav_message_default_from_id
276                #mav_message_random_from_id
277                #mav_message_serialize
278                #mav_message_crc
279                #mav_message_target_system_and_component
280            }
281        }
282    }
283
284    #[inline(always)]
285    fn emit_mav_message(
286        &self,
287        docs: &[TokenStream],
288        lifecycles: &[TokenStream],
289        enums: &[TokenStream],
290        structs: &[TokenStream],
291    ) -> TokenStream {
292        quote! {
293            #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
294            #[cfg_attr(feature = "serde", serde(tag = "type"))]
295            #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
296            #[cfg_attr(feature = "ts-rs", derive(TS))]
297            #[cfg_attr(feature = "ts-rs", ts(export))]
298            #[repr(u32)]
299            pub enum MavMessage {
300                #(#docs #lifecycles #enums(#structs),)*
301            }
302        }
303    }
304
305    fn emit_variant_description(&self) -> Vec<TokenStream> {
306        self.messages
307            .values()
308            .map(|msg| {
309                let mut ts = TokenStream::new();
310
311                if let Some(doc) = msg.description.as_ref() {
312                    let doc = format!("{doc}{}", if doc.ends_with('.') { "" } else { "." });
313                    let doc = URL_REGEX.replace_all(&doc, "<$1>");
314                    ts.extend(quote!(#[doc = #doc]));
315
316                    // Leave a blank line before the message ID for readability.
317                    ts.extend(quote!(#[doc = ""]));
318                }
319
320                let id = format!("ID: {}", msg.id);
321                ts.extend(quote!(#[doc = #id]));
322
323                ts
324            })
325            .collect()
326    }
327
328    #[inline(always)]
329    fn emit_mav_message_all_ids(&self) -> TokenStream {
330        let mut message_ids = self
331            .messages
332            .values()
333            .map(|m| (m.id, m.emit_wip()))
334            .collect::<Vec<_>>();
335        message_ids.sort_by_key(|(id, _)| *id);
336        let (ids, wips): (Vec<_>, Vec<_>) = message_ids.into_iter().unzip();
337
338        quote!(
339            pub const fn all_ids() -> &'static [u32] {
340                &[#(#wips #ids),*]
341            }
342        )
343    }
344
345    #[inline(always)]
346    fn emit_minor_version(&self) -> TokenStream {
347        if let Some(version) = self.version {
348            quote! (pub const MINOR_MAVLINK_VERSION: u8 = #version;)
349        } else {
350            TokenStream::default()
351        }
352    }
353
354    #[inline(always)]
355    fn emit_dialect_number(&self) -> TokenStream {
356        if let Some(dialect) = self.dialect {
357            quote! (pub const DIALECT_NUMBER: u8 = #dialect;)
358        } else {
359            TokenStream::default()
360        }
361    }
362
363    #[inline(always)]
364    fn emit_mav_message_parse(
365        &self,
366        enums: &[TokenStream],
367        structs: &[TokenStream],
368        wips: &[TokenStream],
369    ) -> TokenStream {
370        let id_width = format_ident!("u32");
371
372        quote! {
373            fn parse(version: MavlinkVersion, id: #id_width, payload: &[u8]) -> Result<Self, ::mavlink_core::error::ParserError> {
374                match id {
375                    #(
376                        #wips
377                        #structs::ID => #structs::deser(version, payload).map(Self::#enums),
378                    )*
379                    _ => {
380                        Err(::mavlink_core::error::ParserError::UnknownMessage { id })
381                    },
382                }
383            }
384        }
385    }
386
387    #[inline(always)]
388    fn emit_mav_message_crc(
389        &self,
390        id_width: &Ident,
391        structs: &[TokenStream],
392        wips: &[TokenStream],
393    ) -> TokenStream {
394        quote! {
395            fn extra_crc(id: #id_width) -> u8 {
396                match id {
397                    #(
398                        #wips
399                        #structs::ID => #structs::EXTRA_CRC,
400                    )*
401                    _ => {
402                        0
403                    },
404                }
405            }
406        }
407    }
408
409    #[inline(always)]
410    fn emit_mav_message_name(
411        &self,
412        enums: &[TokenStream],
413        structs: &[TokenStream],
414        wips: &[TokenStream],
415    ) -> TokenStream {
416        quote! {
417            fn message_name(&self) -> &'static str {
418                match self {
419                    #(
420                        #wips
421                        Self::#enums(..) => #structs::NAME,
422                    )*
423                }
424            }
425        }
426    }
427
428    #[inline(always)]
429    fn emit_mav_message_id(
430        &self,
431        enums: &[TokenStream],
432        structs: &[TokenStream],
433        wips: &[TokenStream],
434    ) -> TokenStream {
435        let id_width = format_ident!("u32");
436        quote! {
437            fn message_id(&self) -> #id_width {
438                match self {
439                    #(
440                        #wips
441                        Self::#enums(..) => #structs::ID,
442                    )*
443                }
444            }
445        }
446    }
447
448    #[inline(always)]
449    fn emit_mav_message_id_from_name(
450        &self,
451        structs: &[TokenStream],
452        wips: &[TokenStream],
453    ) -> TokenStream {
454        quote! {
455            fn message_id_from_name(name: &str) -> Option<u32> {
456                match name {
457                    #(
458                        #wips
459                        #structs::NAME => Some(#structs::ID),
460                    )*
461                    _ => {
462                        None
463                    }
464                }
465            }
466        }
467    }
468
469    #[inline(always)]
470    fn emit_mav_message_default_from_id(
471        &self,
472        enums: &[TokenStream],
473        structs: &[TokenStream],
474        wips: &[TokenStream],
475    ) -> TokenStream {
476        quote! {
477            fn default_message_from_id(id: u32) -> Option<Self> {
478                match id {
479                    #(
480                        #wips
481                        #structs::ID => Some(Self::#enums(#structs::default())),
482                    )*
483                    _ => {
484                        None
485                    }
486                }
487            }
488        }
489    }
490
491    #[inline(always)]
492    fn emit_mav_message_random_from_id(
493        &self,
494        enums: &[TokenStream],
495        structs: &[TokenStream],
496        wips: &[TokenStream],
497    ) -> TokenStream {
498        quote! {
499            #[cfg(feature = "arbitrary")]
500            fn random_message_from_id<R: rand::Rng>(id: u32, rng: &mut R) -> Option<Self> {
501                match id {
502                    #(
503                        #wips
504                        #structs::ID => Some(Self::#enums(#structs::random(rng))),
505                    )*
506                    _ => None,
507                }
508            }
509        }
510    }
511
512    #[inline(always)]
513    fn emit_mav_message_serialize(
514        &self,
515        enums: &Vec<TokenStream>,
516        wips: &[TokenStream],
517    ) -> TokenStream {
518        quote! {
519            fn ser(&self, version: MavlinkVersion, bytes: &mut [u8]) -> usize {
520                match self {
521                    #(
522                        #wips
523                        Self::#enums(body) => body.ser(version, bytes),
524                    )*
525                }
526            }
527        }
528    }
529
530    #[inline(always)]
531    fn emit_mav_message_target_accessors(&self) -> TokenStream {
532        const TARGET_SYSTEM: &str = "target_system";
533        const TARGET_COMPONENT: &str = "target_component";
534        const TARGET_FIELDS: [&str; 2] = [TARGET_SYSTEM, TARGET_COMPONENT];
535
536        fn is_target_system_field(message: &MavMessage, field: &MavField) -> bool {
537            matches!(
538                (message.name.as_str(), field.name.as_str()),
539                (_, TARGET_SYSTEM) | ("MANUAL_CONTROL", "target")
540            )
541        }
542
543        let accessors: Vec<TokenStream> = TARGET_FIELDS
544            .iter()
545            .map(|target_field| {
546                let getter = format_ident!("{}_id", target_field);
547                let getter_mut = format_ident!("{}_id_mut", target_field);
548                let fields: Vec<(Ident, Ident, TokenStream)> = self
549                    .messages
550                    .values()
551                    .filter_map(|msg| {
552                        msg.fields
553                            .iter()
554                            .find(|f| match *target_field {
555                                TARGET_SYSTEM => is_target_system_field(msg, f),
556                                TARGET_COMPONENT => f.name == TARGET_COMPONENT,
557                                _ => false,
558                            })
559                            .map(|f| (format_ident!("{}", msg.name), format_ident!("{}", f.name), msg.emit_wip()))
560                    })
561                    .collect();
562                let getter_arms: Vec<TokenStream> = fields
563                    .iter()
564                    .map(|(variant, field, wip)| quote!(#wip Self::#variant(inner) => Some(inner.#field),))
565                    .collect();
566                let getter_mut_arms: Vec<TokenStream> = fields
567                    .iter()
568                    .map(|(variant, field, wip)| {
569                        quote!(#wip Self::#variant(inner) => Some(&mut inner.#field),)
570                    })
571                    .collect();
572
573                quote! {
574                    fn #getter(&self) -> Option<u8> {
575                        match self {
576                            #(#getter_arms)*
577                            _ => None,
578                        }
579                    }
580
581                    fn #getter_mut(&mut self) -> Option<&mut u8> {
582                        match self {
583                            #(#getter_mut_arms)*
584                            _ => None,
585                        }
586                    }
587                }
588            })
589            .collect();
590
591        quote! { #(#accessors)* }
592    }
593
594    #[inline(always)]
595    fn emit_mav_message_all_messages(&self) -> TokenStream {
596        let mut entries = self
597            .messages
598            .values()
599            .map(|msg| (msg.id, msg.emit_struct_name(), msg.emit_wip()))
600            .collect::<Vec<_>>();
601
602        entries.sort_by_key(|(id, _, _)| *id);
603
604        let pairs = entries
605            .into_iter()
606            .map(|(_, struct_name, wip)| quote!(#wip (#struct_name::NAME, #struct_name::ID)))
607            .collect::<Vec<_>>();
608
609        quote! {
610            pub const fn all_messages() -> &'static [(&'static str, u32)] {
611                &[#(#pairs),*]
612            }
613        }
614    }
615}
616
617#[derive(Debug, PartialEq, Clone, Default)]
618#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
619pub struct MavEnum {
620    pub name: String,
621    pub description: Option<String>,
622    pub entries: Vec<MavEnumEntry>,
623    /// If contains Some, the string represents the primitive type (size) for bitflags.
624    /// If no fields use this enum, the bitmask is true, but primitive is None. In this case
625    /// regular enum is generated as primitive is unknown.
626    pub primitive: Option<MavType>,
627    pub bitmask: bool,
628    pub lifecycle: Option<MavLifecycle>,
629    pub additional_primitives: HashSet<MavType>,
630}
631
632impl MavEnum {
633    /// Returns true when this enum will be emitted as a `bitflags` struct.
634    fn is_generated_as_bitflags(&self) -> bool {
635        self.primitive.is_some()
636    }
637
638    fn try_combine(&mut self, enm: &Self) {
639        if self.name == enm.name {
640            for enum_entry in &enm.entries {
641                let found_entry = self.entries.iter().find(|elem| {
642                    elem.name == enum_entry.name && elem.value.unwrap() == enum_entry.value.unwrap()
643                });
644                match found_entry {
645                    Some(entry) => panic!("Enum entry {} already exists", entry.name),
646                    None => self.entries.push(enum_entry.clone()),
647                }
648            }
649            self.additional_primitives
650                .extend(enm.additional_primitives.clone());
651        }
652    }
653
654    /// Return resolved enum entries that fit the optional primitive type.
655    #[doc(hidden)]
656    pub fn entries_with_values(
657        &self,
658        restricted_primitive: Option<&MavType>,
659    ) -> impl Iterator<Item = (&MavEnumEntry, u64)> {
660        let max_value = restricted_primitive.map_or(u64::MAX, MavType::max_int_value);
661        let mut previous = 0;
662        self.entries
663            .iter()
664            .map(move |entry| {
665                let value = entry.value.unwrap_or_else(|| previous + 1);
666                previous = previous.max(value);
667                (entry, value)
668            })
669            .filter(move |(_, value)| *value <= max_value)
670    }
671
672    fn emit_defs(&self, restricted_primitive: Option<&MavType>) -> Vec<TokenStream> {
673        self.entries_with_values(restricted_primitive)
674            .map(|(enum_entry, value)| {
675                let name = format_ident!("{}", enum_entry.name);
676
677                let lifecycle = enum_entry.emit_lifecycle();
678
679                let description = if let Some(description) = enum_entry.description.as_ref() {
680                    let description = URL_REGEX.replace_all(description, "<$1>");
681                    quote!(#[doc = #description])
682                } else {
683                    quote!()
684                };
685
686                let params_doc = enum_entry.emit_params();
687
688                let value = Literal::u64_unsuffixed(value);
689                if self.is_generated_as_bitflags() {
690                    quote! {
691                        #description
692                        #lifecycle
693                        #params_doc
694                        const #name = #value;
695                    }
696                } else {
697                    quote! {
698                        #description
699                        #lifecycle
700                        #params_doc
701                        #name = #value,
702                    }
703                }
704            })
705            .collect()
706    }
707
708    #[inline(always)]
709    fn emit_name(&self, additional_primitive: Option<&MavType>) -> TokenStream {
710        let name = format_ident!(
711            "{}{}",
712            self.name,
713            &additional_primitive
714                .map(|s| s.rust_primitive_type().to_uppercase())
715                .unwrap_or_default()
716        );
717        quote!(#name)
718    }
719
720    #[inline(always)]
721    fn emit_const_default(&self) -> TokenStream {
722        let default = format_ident!("{}", self.entries[0].name);
723        quote!(pub const DEFAULT: Self = Self::#default;)
724    }
725
726    #[inline(always)]
727    fn emit_lifecycle(&self) -> TokenStream {
728        self.lifecycle
729            .as_ref()
730            .map(|d| d.emit_tokens())
731            .unwrap_or_default()
732    }
733
734    #[inline(always)]
735    fn emit_wip(&self) -> TokenStream {
736        self.lifecycle
737            .as_ref()
738            .map(|d| d.emit_wip_tokens())
739            .unwrap_or_default()
740    }
741
742    fn emit_rust(&self) -> TokenStream {
743        let base = self.emit_enum_def(None);
744        let adds = self.emit_additional_primitives();
745        quote! {
746            #base
747            #adds
748        }
749    }
750
751    fn emit_enum_def(&self, restricted_primitive: Option<MavType>) -> TokenStream {
752        let defs = self.emit_defs(restricted_primitive.as_ref());
753        let enum_name = self.emit_name(restricted_primitive.as_ref());
754        let const_default = self.emit_const_default();
755
756        let lifecycle = self.emit_lifecycle();
757        let wip = self.emit_wip();
758
759        let mut description = if let Some(description) = self.description.as_ref() {
760            let desc = URL_REGEX.replace_all(description, "<$1>");
761            quote!(#[doc = #desc])
762        } else {
763            quote!()
764        };
765
766        if let Some(restricted_primitive) = &restricted_primitive {
767            let doc = format!(
768                "This is the `{0}` version of `{1}`. It does not allow flags that exceed `{0}::MAX`",
769                restricted_primitive.rust_primitive_type(),
770                self.emit_name(None),
771            );
772            description.extend(quote! {#[doc = #doc]});
773        }
774
775        let mav_bool_impl = if self.name == "MavBool"
776            && self
777                .entries
778                .iter()
779                .any(|entry| entry.name == "MAV_BOOL_TRUE")
780        {
781            if self.is_generated_as_bitflags() {
782                quote!(
783                    pub fn as_bool(&self) -> bool {
784                        self.contains(Self::MAV_BOOL_TRUE)
785                    }
786                )
787            } else {
788                quote!(
789                    pub fn as_bool(&self) -> bool {
790                        *self == Self::MAV_BOOL_TRUE
791                    }
792                )
793            }
794        } else {
795            quote!()
796        };
797
798        let enum_def = if let Some(primitive) = self.primitive.clone() {
799            let primitive = format_ident!(
800                "{}",
801                &restricted_primitive
802                    .as_ref()
803                    .unwrap_or(&primitive)
804                    .rust_primitive_type()
805            );
806            quote! {
807                bitflags!{
808                    #[cfg_attr(feature = "ts-rs", derive(TS))]
809                    #[cfg_attr(feature = "ts-rs", ts(export, type = "number"))]
810                    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
811                    #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
812                    #[derive(Debug, Copy, Clone, PartialEq)]
813                    #description
814                    #lifecycle
815                    pub struct #enum_name: #primitive {
816                        #(#defs)*
817                    }
818                }
819            }
820        } else {
821            quote! {
822                #[cfg_attr(feature = "ts-rs", derive(TS))]
823                #[cfg_attr(feature = "ts-rs", ts(export))]
824                #[derive(Debug, Copy, Clone, PartialEq, FromPrimitive, ToPrimitive)]
825                #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
826                #[cfg_attr(feature = "serde", serde(tag = "type"))]
827                #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
828                #[repr(u32)]
829                #description
830                #lifecycle
831                pub enum #enum_name {
832                    #(#defs)*
833                }
834            }
835        };
836
837        quote! {
838            #enum_def
839
840            #wip
841            impl #enum_name {
842                #const_default
843                #mav_bool_impl
844            }
845
846            #wip
847            impl Default for #enum_name {
848                fn default() -> Self {
849                    Self::DEFAULT
850                }
851            }
852        }
853    }
854
855    fn emit_additional_primitives(&self) -> TokenStream {
856        let mut ts = TokenStream::new();
857        for primitive in &self.additional_primitives {
858            ts.extend(self.emit_enum_def(Some(primitive.clone())));
859        }
860        ts
861    }
862}
863
864#[derive(Debug, PartialEq, Clone, Default)]
865#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
866pub struct MavEnumEntry {
867    pub value: Option<u64>,
868    pub name: String,
869    pub description: Option<String>,
870    pub params: Option<Vec<MavParam>>,
871    pub lifecycle: Option<MavLifecycle>,
872}
873
874impl MavEnumEntry {
875    #[inline(always)]
876    fn emit_lifecycle(&self) -> TokenStream {
877        self.lifecycle
878            .as_ref()
879            .map(|d| d.emit_tokens())
880            .unwrap_or_default()
881    }
882
883    #[inline(always)]
884    fn emit_params(&self) -> TokenStream {
885        let Some(params) = &self.params else {
886            return quote!();
887        };
888        let any_value_range = params.iter().any(|p| {
889            p.min_value.is_some()
890                || p.max_value.is_some()
891                || p.increment.is_some()
892                || p.enum_used.is_some()
893                || (p.reserved && p.default.is_some())
894        });
895        let any_units = params.iter().any(|p| p.units.is_some());
896        let lines = params
897            .iter()
898            .map(|param| param.emit_doc_row(any_value_range, any_units));
899        let mut table_header = "| Parameter | Description |".to_string();
900        let mut table_hl = "| --------- | ----------- |".to_string();
901        if any_value_range {
902            table_header += " Values |";
903            table_hl += " ------ |";
904        }
905        if any_units {
906            table_header += " Units |";
907            table_hl += " ----- |";
908        }
909        quote! {
910            #[doc = ""]
911            #[doc = "# Parameters"]
912            #[doc = ""]
913            #[doc = #table_header]
914            #[doc = #table_hl]
915            #(#lines)*
916        }
917    }
918}
919
920#[derive(Debug, PartialEq, Clone, Default)]
921#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
922pub struct MavParam {
923    pub index: usize,
924    pub description: Option<String>,
925    pub label: Option<String>,
926    pub units: Option<String>,
927    pub enum_used: Option<String>,
928    pub increment: Option<f32>,
929    pub min_value: Option<f32>,
930    pub max_value: Option<f32>,
931    pub reserved: bool,
932    pub default: Option<f32>,
933}
934
935fn format_number_range(min: Option<f32>, max: Option<f32>, inc: Option<f32>) -> String {
936    match (min, max, inc) {
937        (Some(min), Some(max), Some(inc)) => {
938            if min + inc == max {
939                format!("{min}, {max}")
940            } else if min + 2. * inc == max {
941                format!("{}, {}, {}", min, min + inc, max)
942            } else {
943                format!("{}, {}, .. , {}", min, min + inc, max)
944            }
945        }
946        (Some(min), Some(max), None) => format!("{min} .. {max}"),
947        (Some(min), None, Some(inc)) => format!("{}, {}, ..", min, min + inc),
948        (None, Some(max), Some(inc)) => format!(".., {}, {}", max - inc, max),
949        (Some(min), None, None) => format!("&ge; {min}"),
950        (None, Some(max), None) => format!("&le; {max}"),
951        (None, None, Some(inc)) => format!("Multiples of {inc}"),
952        (None, None, None) => String::new(),
953    }
954}
955
956impl MavParam {
957    fn format_valid_values(&self) -> String {
958        if let (true, Some(default)) = (self.reserved, self.default) {
959            format!("Reserved (use {default})")
960        } else if let Some(enum_used) = &self.enum_used {
961            format!("[`{enum_used}`]")
962        } else {
963            format_number_range(self.min_value, self.max_value, self.increment)
964        }
965    }
966
967    fn emit_doc_row(&self, value_range_col: bool, units_col: bool) -> TokenStream {
968        let label = if let Some(label) = &self.label {
969            format!("{} ({})", self.index, label)
970        } else {
971            format!("{}", self.index)
972        };
973        let mut line = format!(
974            "| {label:10}| {:12}|",
975            self.description.as_deref().unwrap_or_default()
976        );
977        if value_range_col {
978            let range = self.format_valid_values();
979            line += &format!(" {range} |");
980        }
981        if units_col {
982            let units = self.units.clone().unwrap_or_default();
983            line += &format!(" {units} |");
984        }
985        quote! {#[doc = #line]}
986    }
987}
988
989#[derive(Debug, PartialEq, Clone, Default)]
990#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
991pub struct MavMessage {
992    pub id: u32,
993    pub name: String,
994    pub description: Option<String>,
995    pub fields: Vec<MavField>,
996    pub lifecycle: Option<MavLifecycle>,
997}
998
999impl MavMessage {
1000    /// Return Token of "MESSAGE_NAME_DATA
1001    /// for mavlink struct data
1002    fn emit_struct_name(&self) -> TokenStream {
1003        let name = format_ident!("{}", format!("{}_DATA", self.name));
1004        quote!(#name)
1005    }
1006
1007    #[inline(always)]
1008    fn emit_name_types(&self) -> (Vec<TokenStream>, usize) {
1009        let mut encoded_payload_size: usize = 0;
1010        let field_toks = self
1011            .fields
1012            .iter()
1013            .map(|field| {
1014                let nametype = field.emit_name_type();
1015                encoded_payload_size += field.mavtype.size();
1016
1017                let description = field.emit_description();
1018
1019                // From MAVLink specification:
1020                // If sent by an implementation that doesn't have the extensions fields
1021                // then the recipient will see zero values for the extensions fields.
1022                let serde_default = if field.is_extension {
1023                    if field.enumtype.is_some() {
1024                        quote!(#[cfg_attr(feature = "serde", serde(default))])
1025                    } else {
1026                        quote!(#[cfg_attr(feature = "serde", serde(default = "crate::utils::RustDefault::rust_default"))])
1027                    }
1028                } else {
1029                    quote!()
1030                };
1031
1032                let serde_with_attr = if matches!(field.mavtype, MavType::Array(_, _)) {
1033                    quote!(
1034                        #[cfg_attr(feature = "serde", serde(with = "serde_arrays"))]
1035                        #[cfg_attr(feature = "ts-rs", ts(type = "Array<number>"))]
1036                    )
1037                } else if matches!(field.mavtype, MavType::CharArray(_)) {
1038                    quote!(
1039                        #[cfg_attr(feature = "ts-rs", ts(type = "string"))]
1040                    )
1041                } else {
1042                    quote!()
1043                };
1044
1045                quote! {
1046                    #description
1047                    #serde_default
1048                    #serde_with_attr
1049                    #nametype
1050                }
1051            })
1052            .collect::<Vec<TokenStream>>();
1053        (field_toks, encoded_payload_size)
1054    }
1055
1056    /// Generate description for the given message
1057    #[inline(always)]
1058    fn emit_description(&self) -> TokenStream {
1059        let mut ts = TokenStream::new();
1060        if let Some(doc) = self.description.as_ref() {
1061            let doc = format!("{doc}{}", if doc.ends_with('.') { "" } else { "." });
1062            // create hyperlinks
1063            let doc = URL_REGEX.replace_all(&doc, "<$1>");
1064            ts.extend(quote!(#[doc = #doc]));
1065            // Leave a blank line before the message ID for readability.
1066            ts.extend(quote!(#[doc = ""]));
1067        }
1068        let id = format!("ID: {}", self.id);
1069        ts.extend(quote!(#[doc = #id]));
1070        ts
1071    }
1072
1073    #[inline(always)]
1074    fn emit_serialize_vars(&self) -> TokenStream {
1075        let (base_fields, ext_fields): (Vec<_>, Vec<_>) =
1076            self.fields.iter().partition(|f| !f.is_extension);
1077        let ser_vars = base_fields.iter().map(|f| f.rust_writer());
1078        let ser_ext_vars = ext_fields.iter().map(|f| f.rust_writer());
1079        quote! {
1080            let mut __tmp = BytesMut::new(bytes);
1081
1082            if __tmp.remaining() < Self::ENCODED_LEN {
1083                panic!(
1084                    "buffer is too small (need {} bytes, but got {})",
1085                    Self::ENCODED_LEN,
1086                    __tmp.remaining(),
1087                )
1088            }
1089
1090            #(#ser_vars)*
1091            if matches!(version, MavlinkVersion::V2) {
1092                #(#ser_ext_vars)*
1093                let len = __tmp.len();
1094                ::mavlink_core::utils::remove_trailing_zeroes(&bytes[..len])
1095            } else {
1096                __tmp.len()
1097            }
1098        }
1099    }
1100
1101    #[inline(always)]
1102    fn emit_deserialize_vars(&self) -> TokenStream {
1103        let deser_vars = self
1104            .fields
1105            .iter()
1106            .map(|f| f.rust_reader())
1107            .collect::<Vec<TokenStream>>();
1108
1109        if deser_vars.is_empty() {
1110            // struct has no fields
1111            quote! {
1112                Ok(Self::default())
1113            }
1114        } else {
1115            quote! {
1116                let avail_len = __input.len();
1117
1118                let mut payload_buf;
1119                let mut buf = if avail_len < Self::ENCODED_LEN {
1120                    //copy available bytes into an oversized buffer filled with zeros
1121                    payload_buf = [0; Self::ENCODED_LEN];
1122                    payload_buf[0..avail_len].copy_from_slice(__input);
1123                    Bytes::new(&payload_buf)
1124                } else {
1125                    // fast zero copy
1126                    Bytes::new(__input)
1127                };
1128
1129                let mut __struct = Self::default();
1130                #(#deser_vars)*
1131                Ok(__struct)
1132            }
1133        }
1134    }
1135
1136    #[inline(always)]
1137    fn emit_default_impl(&self) -> TokenStream {
1138        let msg_name = self.emit_struct_name();
1139        quote! {
1140            impl Default for #msg_name {
1141                fn default() -> Self {
1142                    Self::DEFAULT.clone()
1143                }
1144            }
1145        }
1146    }
1147
1148    #[inline(always)]
1149    fn emit_lifecycle(&self) -> TokenStream {
1150        self.lifecycle
1151            .as_ref()
1152            .map(|d| d.emit_tokens())
1153            .unwrap_or_default()
1154    }
1155
1156    #[inline(always)]
1157    fn emit_wip(&self) -> TokenStream {
1158        self.lifecycle
1159            .as_ref()
1160            .map(|d| d.emit_wip_tokens())
1161            .unwrap_or_default()
1162    }
1163
1164    #[inline(always)]
1165    fn emit_const_default(&self, dialect_has_version: bool) -> TokenStream {
1166        let initializers = self
1167            .fields
1168            .iter()
1169            .map(|field| field.emit_default_initializer(dialect_has_version));
1170        quote!(pub const DEFAULT: Self = Self { #(#initializers)* };)
1171    }
1172
1173    fn emit_rust(&self, dialect_has_version: bool) -> TokenStream {
1174        let msg_name = self.emit_struct_name();
1175        let id = self.id;
1176        let name = self.name.clone();
1177        let extra_crc = extra_crc(self);
1178        let (name_types, payload_encoded_size) = self.emit_name_types();
1179        assert!(
1180            (1..=255).contains(&payload_encoded_size),
1181            "payload length must be between 1 and 255 bytes"
1182        );
1183
1184        let deser_vars = self.emit_deserialize_vars();
1185        let serialize_vars = self.emit_serialize_vars();
1186        let const_default = self.emit_const_default(dialect_has_version);
1187        let default_impl = self.emit_default_impl();
1188
1189        let lifecycle = self.emit_lifecycle();
1190        let wip = self.emit_wip();
1191
1192        let description = self.emit_description();
1193
1194        quote! {
1195            #description
1196            #lifecycle
1197            #[derive(Debug, Clone, PartialEq)]
1198            #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1199            #[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
1200            #[cfg_attr(feature = "ts-rs", derive(TS))]
1201            #[cfg_attr(feature = "ts-rs", ts(export))]
1202            pub struct #msg_name {
1203                #(#name_types)*
1204            }
1205
1206            #wip
1207            impl #msg_name {
1208                pub const ENCODED_LEN: usize = #payload_encoded_size;
1209                #const_default
1210
1211                #[cfg(feature = "arbitrary")]
1212                pub fn random<R: rand::Rng>(rng: &mut R) -> Self {
1213                    use arbitrary::{Unstructured, Arbitrary};
1214                    let mut buf = [0u8; 1024];
1215                    rng.fill_bytes(&mut buf);
1216                    let mut unstructured = Unstructured::new(&buf);
1217                    Self::arbitrary(&mut unstructured).unwrap_or_default()
1218                }
1219            }
1220
1221            #wip
1222            #default_impl
1223
1224            #wip
1225            impl MessageData for #msg_name {
1226                type Message = MavMessage;
1227
1228                const ID: u32 = #id;
1229                const NAME: &'static str = #name;
1230                const EXTRA_CRC: u8 = #extra_crc;
1231                const ENCODED_LEN: usize = #payload_encoded_size;
1232
1233                fn deser(_version: MavlinkVersion, __input: &[u8]) -> Result<Self, ::mavlink_core::error::ParserError> {
1234                    #deser_vars
1235                }
1236
1237                fn ser(&self, version: MavlinkVersion, bytes: &mut [u8]) -> usize {
1238                    #serialize_vars
1239                }
1240            }
1241        }
1242    }
1243
1244    /// Ensures that a message does not contain duplicate field names.
1245    ///
1246    /// Duplicate field names would generate invalid Rust structs.
1247    fn validate_unique_fields(&self) {
1248        let mut seen: HashSet<&str> = HashSet::new();
1249        for f in &self.fields {
1250            let name: &str = &f.name;
1251            assert!(
1252                seen.insert(name),
1253                "Duplicate field '{}' found in message '{}' while generating bindings",
1254                name,
1255                self.name
1256            );
1257        }
1258    }
1259
1260    /// Ensure that the fields count is at least one and no more than 64
1261    fn validate_field_count(&self) {
1262        assert!(
1263            !self.fields.is_empty(),
1264            "Message '{}' does not any fields",
1265            self.name
1266        );
1267        assert!(
1268            self.fields.len() <= 64,
1269            "Message '{}' has more then 64 fields",
1270            self.name
1271        );
1272    }
1273}
1274
1275#[derive(Debug, PartialEq, Clone, Default)]
1276#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1277pub struct MavField {
1278    pub mavtype: MavType,
1279    pub name: String,
1280    pub description: Option<String>,
1281    pub enumtype: Option<String>,
1282    pub display: Option<String>,
1283    pub is_extension: bool,
1284    pub is_undersized: bool,
1285}
1286
1287impl MavField {
1288    /// Emit rust name of a given field
1289    #[inline(always)]
1290    fn emit_name(&self) -> TokenStream {
1291        let name = format_ident!("{}", self.name);
1292        quote!(#name)
1293    }
1294
1295    /// Emit rust type of the field
1296    #[inline(always)]
1297    fn emit_type(&self) -> TokenStream {
1298        let mavtype;
1299        if matches!(self.mavtype, MavType::Array(_, _)) {
1300            let rt = TokenStream::from_str(&self.mavtype.rust_type()).unwrap();
1301            mavtype = quote!(#rt);
1302        } else if let Some(enumname) = &self.enumtype {
1303            if self.is_undersized {
1304                let en = TokenStream::from_str(&format!(
1305                    "{}{}",
1306                    enumname,
1307                    self.mavtype.rust_primitive_type().to_uppercase()
1308                ))
1309                .unwrap();
1310                mavtype = quote!(#en);
1311            } else {
1312                let en = TokenStream::from_str(enumname).unwrap();
1313                mavtype = quote!(#en);
1314            }
1315        } else {
1316            let rt = TokenStream::from_str(&self.mavtype.rust_type()).unwrap();
1317            mavtype = quote!(#rt);
1318        }
1319        mavtype
1320    }
1321
1322    /// Generate description for the given field
1323    #[inline(always)]
1324    fn emit_description(&self) -> TokenStream {
1325        let mut ts = TokenStream::new();
1326        if let Some(val) = self.description.as_ref() {
1327            let desc = URL_REGEX.replace_all(val, "<$1>");
1328            ts.extend(quote!(#[doc = #desc]));
1329        }
1330        if self.is_undersized {
1331            ts.extend(quote!(#[doc = "This field can not store all possible values of its associated bitflag enum."]));
1332        }
1333        ts
1334    }
1335
1336    /// Combine rust name and type of a given field
1337    #[inline(always)]
1338    fn emit_name_type(&self) -> TokenStream {
1339        let name = self.emit_name();
1340        let fieldtype = self.emit_type();
1341        quote!(pub #name: #fieldtype,)
1342    }
1343
1344    /// Emit writer
1345    fn rust_writer(&self) -> TokenStream {
1346        let mut name = "self.".to_string() + &self.name.clone();
1347        if self.enumtype.is_some() {
1348            // casts are not necessary for arrays, because they are currently
1349            // generated as primitive arrays
1350            if !matches!(self.mavtype, MavType::Array(_, _)) {
1351                if let Some(dsp) = &self.display {
1352                    // potentially a bitflag
1353                    if dsp == "bitmask" {
1354                        // it is a bitflag
1355                        name += ".bits() as ";
1356                        name += &self.mavtype.rust_type();
1357                    } else {
1358                        panic!("Display option not implemented");
1359                    }
1360                } else {
1361                    // an enum, have to use "*foo as u8" cast
1362                    name += " as ";
1363                    name += &self.mavtype.rust_type();
1364                }
1365            }
1366        }
1367        let ts = TokenStream::from_str(&name).unwrap();
1368        let name = quote!(#ts);
1369        let buf = format_ident!("__tmp");
1370        self.mavtype.rust_writer(&name, buf)
1371    }
1372
1373    /// Emit reader
1374    fn rust_reader(&self) -> TokenStream {
1375        let _name = TokenStream::from_str(&self.name).unwrap();
1376
1377        let name = quote!(__struct.#_name);
1378        let buf = format_ident!("buf");
1379        if let Some(enum_name) = &self.enumtype {
1380            // TODO: handle enum arrays properly, rather than just generating
1381            // primitive arrays
1382            if let MavType::Array(_t, _size) = &self.mavtype {
1383                return self.mavtype.rust_reader(&name, buf);
1384            }
1385            if let Some(dsp) = &self.display {
1386                if dsp == "bitmask" {
1387                    // bitflags
1388                    let tmp = self.mavtype.rust_reader(&quote!(let tmp), buf);
1389                    let enum_name_ident = self.emit_type();
1390                    quote! {
1391                        #tmp
1392                        // Keep unknown bits for forward compatibility.
1393                        #name = #enum_name_ident::from_bits_retain(tmp as <#enum_name_ident as Flags>::Bits);
1394                    }
1395                } else {
1396                    panic!("Display option not implemented");
1397                }
1398            } else {
1399                // handle enum by FromPrimitive
1400                let tmp = self.mavtype.rust_reader(&quote!(let tmp), buf);
1401                let val = format_ident!("from_{}", &self.mavtype.rust_type());
1402                quote!(
1403                    #tmp
1404                    #name = FromPrimitive::#val(tmp)
1405                        .ok_or(::mavlink_core::error::ParserError::InvalidEnum { enum_type: #enum_name, value: tmp as u64 })?;
1406                )
1407            }
1408        } else {
1409            self.mavtype.rust_reader(&name, buf)
1410        }
1411    }
1412
1413    #[inline(always)]
1414    fn emit_default_initializer(&self, dialect_has_version: bool) -> TokenStream {
1415        let field = self.emit_name();
1416        // FIXME: Is this actually expected behaviour??
1417        if matches!(self.mavtype, MavType::Array(_, _)) {
1418            let default_value = self.mavtype.emit_default_value(dialect_has_version);
1419            quote!(#field: #default_value,)
1420        } else if self.enumtype.is_some() {
1421            let ty = self.emit_type();
1422            quote!(#field: #ty::DEFAULT,)
1423        } else {
1424            let default_value = self.mavtype.emit_default_value(dialect_has_version);
1425            quote!(#field: #default_value,)
1426        }
1427    }
1428}
1429
1430#[derive(Debug, PartialEq, Clone, Default, Hash, Eq)]
1431#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1432pub enum MavType {
1433    UInt8MavlinkVersion,
1434    #[default]
1435    UInt8,
1436    UInt16,
1437    UInt32,
1438    UInt64,
1439    Int8,
1440    Int16,
1441    Int32,
1442    Int64,
1443    Char,
1444    Float,
1445    Double,
1446    CharArray(usize),
1447    Array(Box<Self>, usize),
1448}
1449
1450impl MavType {
1451    fn parse_type(s: &str) -> Option<Self> {
1452        use self::MavType::*;
1453        match s {
1454            "uint8_t_mavlink_version" => Some(UInt8MavlinkVersion),
1455            "uint8_t" => Some(UInt8),
1456            "uint16_t" => Some(UInt16),
1457            "uint32_t" => Some(UInt32),
1458            "uint64_t" => Some(UInt64),
1459            "int8_t" => Some(Int8),
1460            "int16_t" => Some(Int16),
1461            "int32_t" => Some(Int32),
1462            "int64_t" => Some(Int64),
1463            "char" => Some(Char),
1464            "float" => Some(Float),
1465            "Double" => Some(Double),
1466            "double" => Some(Double),
1467            _ if s.starts_with("char[") => {
1468                let start = 4;
1469                let size = s[start + 1..(s.len() - 1)].parse::<usize>().ok()?;
1470                Some(CharArray(size))
1471            }
1472            _ if s.ends_with(']') => {
1473                let start = s.find('[')?;
1474                let size = s[start + 1..(s.len() - 1)].parse::<usize>().ok()?;
1475                let mtype = Self::parse_type(&s[0..start])?;
1476                Some(Array(Box::new(mtype), size))
1477            }
1478            _ => None,
1479        }
1480    }
1481
1482    /// Emit reader of a given type
1483    pub fn rust_reader(&self, val: &TokenStream, buf: Ident) -> TokenStream {
1484        use self::MavType::*;
1485        match self {
1486            Char => quote! {#val = #buf.get_u8()?;},
1487            UInt8 => quote! {#val = #buf.get_u8()?;},
1488            UInt16 => quote! {#val = #buf.get_u16_le()?;},
1489            UInt32 => quote! {#val = #buf.get_u32_le()?;},
1490            UInt64 => quote! {#val = #buf.get_u64_le()?;},
1491            UInt8MavlinkVersion => quote! {#val = #buf.get_u8()?;},
1492            Int8 => quote! {#val = #buf.get_i8()?;},
1493            Int16 => quote! {#val = #buf.get_i16_le()?;},
1494            Int32 => quote! {#val = #buf.get_i32_le()?;},
1495            Int64 => quote! {#val = #buf.get_i64_le()?;},
1496            Float => quote! {#val = #buf.get_f32_le()?;},
1497            Double => quote! {#val = #buf.get_f64_le()?;},
1498            CharArray(size) => {
1499                quote! {
1500                    let mut tmp = [0_u8; #size];
1501                    for v in &mut tmp {
1502                        *v = #buf.get_u8()?;
1503                    }
1504                    #val = CharArray::new(tmp);
1505                }
1506            }
1507            Array(t, _) => {
1508                let r = t.rust_reader(&quote!(let val), buf);
1509                quote! {
1510                    for v in &mut #val {
1511                        #r
1512                        *v = val;
1513                    }
1514                }
1515            }
1516        }
1517    }
1518
1519    /// Emit writer of a given type
1520    pub fn rust_writer(&self, val: &TokenStream, buf: Ident) -> TokenStream {
1521        use self::MavType::*;
1522        match self {
1523            UInt8MavlinkVersion => quote! {#buf.put_u8(#val);},
1524            UInt8 => quote! {#buf.put_u8(#val);},
1525            Char => quote! {#buf.put_u8(#val);},
1526            UInt16 => quote! {#buf.put_u16_le(#val);},
1527            UInt32 => quote! {#buf.put_u32_le(#val);},
1528            Int8 => quote! {#buf.put_i8(#val);},
1529            Int16 => quote! {#buf.put_i16_le(#val);},
1530            Int32 => quote! {#buf.put_i32_le(#val);},
1531            Float => quote! {#buf.put_f32_le(#val);},
1532            UInt64 => quote! {#buf.put_u64_le(#val);},
1533            Int64 => quote! {#buf.put_i64_le(#val);},
1534            Double => quote! {#buf.put_f64_le(#val);},
1535            CharArray(_) => {
1536                let w = Char.rust_writer(&quote!(*val), buf);
1537                quote! {
1538                    for val in &#val {
1539                        #w
1540                    }
1541                }
1542            }
1543            Array(t, _size) => {
1544                let w = t.rust_writer(&quote!(*val), buf);
1545                quote! {
1546                    for val in &#val {
1547                        #w
1548                    }
1549                }
1550            }
1551        }
1552    }
1553
1554    /// Encoded size of this MavType.
1555    pub fn size(&self) -> usize {
1556        use self::MavType::*;
1557        match self {
1558            UInt8MavlinkVersion | UInt8 | Int8 | Char => 1,
1559            UInt16 | Int16 => 2,
1560            UInt32 | Int32 | Float => 4,
1561            UInt64 | Int64 | Double => 8,
1562            CharArray(size) => *size,
1563            Array(t, size) => t.size() * size,
1564        }
1565    }
1566
1567    fn max_int_value(&self) -> u64 {
1568        match self {
1569            Self::UInt8MavlinkVersion | Self::UInt8 => u8::MAX as u64,
1570            Self::UInt16 => u16::MAX as u64,
1571            Self::UInt32 => u32::MAX as u64,
1572            Self::UInt64 => u64::MAX,
1573            Self::Int8 | Self::Char | Self::CharArray(_) => i8::MAX as u64,
1574            Self::Int16 => i16::MAX as u64,
1575            Self::Int32 => i32::MAX as u64,
1576            Self::Int64 => i64::MAX as u64,
1577            // maximum precisly representable value minus 1 for float types
1578            Self::Float => (1 << f32::MANTISSA_DIGITS) - 1,
1579            Self::Double => (1 << f64::MANTISSA_DIGITS) - 1,
1580            Self::Array(mav_type, _) => mav_type.max_int_value(),
1581        }
1582    }
1583
1584    /// Used for ordering of types
1585    fn order_len(&self) -> usize {
1586        use self::MavType::*;
1587        match self {
1588            UInt8MavlinkVersion | UInt8 | Int8 | Char | CharArray(_) => 1,
1589            UInt16 | Int16 => 2,
1590            UInt32 | Int32 | Float => 4,
1591            UInt64 | Int64 | Double => 8,
1592            Array(t, _) => t.size(),
1593        }
1594    }
1595
1596    /// Used for crc calculation
1597    pub fn primitive_type(&self) -> String {
1598        use self::MavType::*;
1599        match self {
1600            UInt8MavlinkVersion => "uint8_t".into(),
1601            UInt8 => "uint8_t".into(),
1602            Int8 => "int8_t".into(),
1603            Char => "char".into(),
1604            UInt16 => "uint16_t".into(),
1605            Int16 => "int16_t".into(),
1606            UInt32 => "uint32_t".into(),
1607            Int32 => "int32_t".into(),
1608            Float => "float".into(),
1609            UInt64 => "uint64_t".into(),
1610            Int64 => "int64_t".into(),
1611            Double => "double".into(),
1612            CharArray(_) => "char".into(),
1613            Array(t, _) => t.primitive_type(),
1614        }
1615    }
1616
1617    /// Return rust equivalent of a given Mavtype
1618    /// Used for generating struct fields.
1619    pub fn rust_type(&self) -> String {
1620        use self::MavType::*;
1621        match self {
1622            UInt8 | UInt8MavlinkVersion => "u8".into(),
1623            Int8 => "i8".into(),
1624            Char => "u8".into(),
1625            UInt16 => "u16".into(),
1626            Int16 => "i16".into(),
1627            UInt32 => "u32".into(),
1628            Int32 => "i32".into(),
1629            Float => "f32".into(),
1630            UInt64 => "u64".into(),
1631            Int64 => "i64".into(),
1632            Double => "f64".into(),
1633            CharArray(size) => format!("CharArray<{size}>"),
1634            Array(t, size) => format!("[{};{}]", t.rust_type(), size),
1635        }
1636    }
1637
1638    pub fn emit_default_value(&self, dialect_has_version: bool) -> TokenStream {
1639        use self::MavType::*;
1640        match self {
1641            UInt8 => quote!(0_u8),
1642            UInt8MavlinkVersion => {
1643                if dialect_has_version {
1644                    quote!(MINOR_MAVLINK_VERSION)
1645                } else {
1646                    quote!(0_u8)
1647                }
1648            }
1649            Int8 => quote!(0_i8),
1650            Char => quote!(0_u8),
1651            UInt16 => quote!(0_u16),
1652            Int16 => quote!(0_i16),
1653            UInt32 => quote!(0_u32),
1654            Int32 => quote!(0_i32),
1655            Float => quote!(0.0_f32),
1656            UInt64 => quote!(0_u64),
1657            Int64 => quote!(0_i64),
1658            Double => quote!(0.0_f64),
1659            CharArray(size) => quote!(CharArray::new([0_u8; #size])),
1660            Array(ty, size) => {
1661                let default_value = ty.emit_default_value(dialect_has_version);
1662                quote!([#default_value; #size])
1663            }
1664        }
1665    }
1666
1667    /// Return rust equivalent of the primitive type of a MavType. The primitive
1668    /// type is the type itself for all except arrays, in which case it is the
1669    /// element type.
1670    pub fn rust_primitive_type(&self) -> String {
1671        use self::MavType::*;
1672        match self {
1673            Array(t, _) => t.rust_primitive_type(),
1674            _ => self.rust_type(),
1675        }
1676    }
1677
1678    /// Compare two MavTypes
1679    pub fn compare(&self, other: &Self) -> Ordering {
1680        let len = self.order_len();
1681        (-(len as isize)).cmp(&(-(other.order_len() as isize)))
1682    }
1683}
1684
1685#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1686#[derive(Debug, PartialEq, Eq, Clone)]
1687pub enum MavLifecycleType {
1688    Deprecated {
1689        replaced_by: Option<String>,
1690        remove_on_date: Option<String>,
1691    },
1692    Superseded {
1693        replaced_by: Option<String>,
1694    },
1695    WIP,
1696}
1697
1698impl Display for MavLifecycleType {
1699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1700        match self {
1701            Self::Deprecated { .. } => f.write_str("Deprecated"),
1702            Self::Superseded { .. } => f.write_str("Superseded"),
1703            Self::WIP => f.write_str("WIP"),
1704        }
1705    }
1706}
1707
1708#[derive(Debug, PartialEq, Eq, Clone)]
1709#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1710pub struct MavLifecycle {
1711    // YYYY-MM
1712    pub since: String,
1713    pub lifecycle_type: MavLifecycleType,
1714    pub note: Option<String>,
1715}
1716
1717impl MavLifecycle {
1718    pub fn emit_tokens(&self) -> TokenStream {
1719        let note = match &self.note {
1720            Some(str) if str.is_empty() || str.ends_with(".") => str.clone(),
1721            Some(str) => format!("{str}."),
1722            None => String::new(),
1723        };
1724        match &self.lifecycle_type {
1725            MavLifecycleType::Deprecated { replaced_by, .. }
1726            | MavLifecycleType::Superseded { replaced_by } => {
1727                let replaced_by = match replaced_by {
1728                    Some(str) if str.starts_with('`') => format!("See {str}"),
1729                    Some(str) => format!("See `{str}`"),
1730                    None => String::new(),
1731                };
1732                let remove_on_date = match &self.lifecycle_type {
1733                    MavLifecycleType::Deprecated {
1734                        remove_on_date: Some(date),
1735                        ..
1736                    } => format!("Scheduled for removal on {date}. "),
1737                    _ => String::new(),
1738                };
1739                let message = format!(
1740                    "{note} {remove_on_date}{replaced_by} ({} since {})",
1741                    self.lifecycle_type, self.since
1742                );
1743                quote!(#[deprecated = #message])
1744            }
1745            MavLifecycleType::WIP => {
1746                let note_since = if self.since.is_empty() {
1747                    note
1748                } else {
1749                    format!("{} Introduced {}.", note, self.since)
1750                };
1751                quote! {
1752                    #[doc = "# Availability"]
1753                    #[doc = "**WORK IN PROGRESS**: Do not use in stable production environments (it may change)."]
1754                    #[doc = #note_since]
1755                    #[cfg(feature = "wip-messages")]
1756                }
1757            }
1758        }
1759    }
1760
1761    pub fn emit_wip_tokens(&self) -> TokenStream {
1762        match self.lifecycle_type {
1763            MavLifecycleType::WIP => quote! { #[cfg(feature = "wip-messages")] },
1764            _ => quote! {},
1765        }
1766    }
1767}
1768
1769#[derive(Debug, PartialEq, Eq, Clone, Copy)]
1770#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1771#[cfg_attr(feature = "serde", serde(tag = "type"))]
1772pub enum MavXmlElement {
1773    Version,
1774    Mavlink,
1775    Dialect,
1776    Include,
1777    Enums,
1778    Enum,
1779    Entry,
1780    Description,
1781    Param,
1782    Messages,
1783    Message,
1784    Field,
1785    Deprecated,
1786    Wip,
1787    Extensions,
1788    Superseded,
1789}
1790
1791const fn identify_element(s: &[u8]) -> Option<MavXmlElement> {
1792    use self::MavXmlElement::*;
1793    match s {
1794        b"version" => Some(Version),
1795        b"mavlink" => Some(Mavlink),
1796        b"dialect" => Some(Dialect),
1797        b"include" => Some(Include),
1798        b"enums" => Some(Enums),
1799        b"enum" => Some(Enum),
1800        b"entry" => Some(Entry),
1801        b"description" => Some(Description),
1802        b"param" => Some(Param),
1803        b"messages" => Some(Messages),
1804        b"message" => Some(Message),
1805        b"field" => Some(Field),
1806        b"deprecated" => Some(Deprecated),
1807        b"wip" => Some(Wip),
1808        b"extensions" => Some(Extensions),
1809        b"superseded" => Some(Superseded),
1810        _ => None,
1811    }
1812}
1813
1814fn is_valid_parent(p: Option<MavXmlElement>, s: MavXmlElement) -> bool {
1815    use self::MavXmlElement::*;
1816    match s {
1817        Version => p == Some(Mavlink),
1818        Mavlink => p.is_none(),
1819        Dialect => p == Some(Mavlink),
1820        Include => p == Some(Mavlink),
1821        Enums => p == Some(Mavlink),
1822        Enum => p == Some(Enums),
1823        Entry => p == Some(Enum),
1824        Description => p == Some(Entry) || p == Some(Message) || p == Some(Enum),
1825        Param => p == Some(Entry),
1826        Messages => p == Some(Mavlink),
1827        Message => p == Some(Messages),
1828        Field => p == Some(Message),
1829        Deprecated => p == Some(Entry) || p == Some(Message) || p == Some(Enum),
1830        Wip => p == Some(Entry) || p == Some(Message) || p == Some(Enum),
1831        Extensions => p == Some(Message),
1832        Superseded => p == Some(Entry) || p == Some(Message) || p == Some(Enum),
1833    }
1834}
1835
1836pub fn parse_profile(
1837    definitions_dir: &Path,
1838    definition_file: &Path,
1839    parsed_files: &mut HashSet<PathBuf>,
1840) -> Result<MavProfile, BindGenError> {
1841    let in_path = Path::new(&definitions_dir).join(definition_file);
1842    parsed_files.insert(in_path.clone()); // Keep track of which files have been parsed
1843
1844    let mut stack: Vec<MavXmlElement> = vec![];
1845
1846    let mut text = None;
1847
1848    let mut profile = MavProfile::default();
1849    let mut field = MavField::default();
1850    let mut message = MavMessage::default();
1851    let mut mavenum = MavEnum::default();
1852    let mut entry = MavEnumEntry::default();
1853    let mut param_index: Option<usize> = None;
1854    let mut param_label: Option<String> = None;
1855    let mut param_units: Option<String> = None;
1856    let mut param_enum: Option<String> = None;
1857    let mut param_increment: Option<f32> = None;
1858    let mut param_min_value: Option<f32> = None;
1859    let mut param_max_value: Option<f32> = None;
1860    let mut param_reserved = false;
1861    let mut param_default: Option<f32> = None;
1862    let mut lifecycle: Option<MavLifecycle> = None;
1863
1864    let mut xml_filter = MavXmlFilter::default();
1865    let mut events: Vec<Result<Event, quick_xml::Error>> = Vec::new();
1866    let xml = std::fs::read_to_string(&in_path).map_err(|e| {
1867        BindGenError::CouldNotReadDefinitionFile {
1868            source: e,
1869            path: in_path.clone(),
1870        }
1871    })?;
1872    let mut reader = Reader::from_str(&xml);
1873    reader.config_mut().trim_text(true);
1874    reader.config_mut().expand_empty_elements = true;
1875
1876    loop {
1877        match reader.read_event() {
1878            Ok(Event::Eof) => {
1879                events.push(Ok(Event::Eof));
1880                break;
1881            }
1882            Ok(event) => events.push(Ok(event.into_owned())),
1883            Err(why) => events.push(Err(why)),
1884        }
1885    }
1886    xml_filter.filter(&mut events);
1887    let mut is_in_extension = false;
1888    for e in events {
1889        match e {
1890            Ok(Event::Start(bytes)) => {
1891                let Some(id) = identify_element(bytes.name().into_inner()) else {
1892                    panic!(
1893                        "unexpected element {:?}",
1894                        String::from_utf8_lossy(bytes.name().into_inner())
1895                    );
1896                };
1897
1898                assert!(
1899                    is_valid_parent(stack.last().copied(), id),
1900                    "not valid parent {:?} of {id:?}",
1901                    stack.last(),
1902                );
1903
1904                match id {
1905                    MavXmlElement::Extensions => {
1906                        is_in_extension = true;
1907                    }
1908                    MavXmlElement::Message => {
1909                        message = MavMessage::default();
1910                    }
1911                    MavXmlElement::Field => {
1912                        field = MavField {
1913                            is_extension: is_in_extension,
1914                            ..Default::default()
1915                        };
1916                    }
1917                    MavXmlElement::Enum => {
1918                        mavenum = MavEnum::default();
1919                    }
1920                    MavXmlElement::Entry => {
1921                        if mavenum.entries.is_empty() {
1922                            mavenum.lifecycle = lifecycle;
1923                        }
1924                        lifecycle = None;
1925                        entry = MavEnumEntry::default();
1926                    }
1927                    MavXmlElement::Param => {
1928                        param_index = None;
1929                        param_increment = None;
1930                        param_min_value = None;
1931                        param_max_value = None;
1932                        param_reserved = false;
1933                        param_default = None;
1934                    }
1935                    MavXmlElement::Deprecated => {
1936                        lifecycle = Some(MavLifecycle {
1937                            since: String::new(),
1938                            lifecycle_type: MavLifecycleType::Deprecated {
1939                                replaced_by: None,
1940                                remove_on_date: None,
1941                            },
1942                            note: None,
1943                        });
1944                    }
1945                    MavXmlElement::Superseded => {
1946                        lifecycle = Some(MavLifecycle {
1947                            since: String::new(),
1948                            lifecycle_type: MavLifecycleType::Superseded { replaced_by: None },
1949                            note: None,
1950                        });
1951                    }
1952                    MavXmlElement::Wip => {
1953                        lifecycle = Some(MavLifecycle {
1954                            since: String::new(),
1955                            lifecycle_type: MavLifecycleType::WIP,
1956                            note: None,
1957                        });
1958                    }
1959                    _ => (),
1960                }
1961                stack.push(id);
1962
1963                for attr in bytes.attributes() {
1964                    let attr = attr.unwrap();
1965                    match stack.last() {
1966                        Some(&MavXmlElement::Enum) => {
1967                            if attr.key.into_inner() == b"name" {
1968                                mavenum.name = to_pascal_case(attr.value);
1969                                //mavenum.name = attr.value.clone();
1970                            } else if attr.key.into_inner() == b"bitmask" {
1971                                mavenum.bitmask = true;
1972                            }
1973                        }
1974                        Some(&MavXmlElement::Entry) => {
1975                            match attr.key.into_inner() {
1976                                b"name" => {
1977                                    entry.name = String::from_utf8_lossy(&attr.value).to_string();
1978                                }
1979                                b"value" => {
1980                                    let value = String::from_utf8_lossy(&attr.value);
1981                                    // Deal with hexadecimal numbers
1982                                    let (src, radix) = value
1983                                        .strip_prefix("0x")
1984                                        .map(|value| (value, 16))
1985                                        .unwrap_or((value.as_ref(), 10));
1986                                    entry.value = Some(
1987                                        u64::from_str_radix(src, radix)
1988                                            .expect("invalid enum entry value"),
1989                                    );
1990                                }
1991                                _ => (),
1992                            }
1993                        }
1994                        Some(&MavXmlElement::Message) => {
1995                            match attr.key.into_inner() {
1996                                b"name" => {
1997                                    /*message.name = attr
1998                                    .value
1999                                    .clone()
2000                                    .split("_")
2001                                    .map(|x| x.to_lowercase())
2002                                    .map(|x| {
2003                                        let mut v: Vec<char> = x.chars().collect();
2004                                        v[0] = v[0].to_uppercase().nth(0).unwrap();
2005                                        v.into_iter().collect()
2006                                    })
2007                                    .collect::<Vec<String>>()
2008                                    .join("");
2009                                    */
2010                                    message.name = String::from_utf8_lossy(&attr.value).to_string();
2011                                }
2012                                b"id" => {
2013                                    message.id =
2014                                        String::from_utf8_lossy(&attr.value).parse().unwrap();
2015                                }
2016                                _ => (),
2017                            }
2018                        }
2019                        Some(&MavXmlElement::Field) => {
2020                            match attr.key.into_inner() {
2021                                b"name" => {
2022                                    let name = String::from_utf8_lossy(&attr.value);
2023                                    field.name = if name == "type" {
2024                                        "mavtype".to_string()
2025                                    } else {
2026                                        name.to_string()
2027                                    };
2028                                }
2029                                b"type" => {
2030                                    let r#type = String::from_utf8_lossy(&attr.value);
2031                                    field.mavtype = MavType::parse_type(&r#type).unwrap();
2032                                }
2033                                b"enum" => {
2034                                    field.enumtype = Some(to_pascal_case(&attr.value));
2035
2036                                    // Update field display if enum is a bitmask
2037                                    if let Some(e) =
2038                                        profile.enums.get(field.enumtype.as_ref().unwrap())
2039                                        && e.bitmask
2040                                    {
2041                                        field.display = Some("bitmask".to_string());
2042                                    }
2043                                }
2044                                b"display" => {
2045                                    field.display =
2046                                        Some(String::from_utf8_lossy(&attr.value).to_string());
2047                                }
2048                                _ => (),
2049                            }
2050                        }
2051                        Some(&MavXmlElement::Param) => {
2052                            if entry.params.is_none() {
2053                                entry.params = Some(vec![]);
2054                            }
2055                            match attr.key.into_inner() {
2056                                b"index" => {
2057                                    let value = String::from_utf8_lossy(&attr.value)
2058                                        .parse()
2059                                        .expect("failed to parse param index");
2060                                    assert!(
2061                                        (1..=7).contains(&value),
2062                                        "param index must be between 1 and 7"
2063                                    );
2064                                    param_index = Some(value);
2065                                }
2066                                b"label" => {
2067                                    param_label =
2068                                        std::str::from_utf8(&attr.value).ok().map(str::to_owned);
2069                                }
2070                                b"increment" => {
2071                                    param_increment = Some(
2072                                        String::from_utf8_lossy(&attr.value)
2073                                            .parse()
2074                                            .expect("failed to parse param increment"),
2075                                    );
2076                                }
2077                                b"minValue" => {
2078                                    param_min_value = Some(
2079                                        String::from_utf8_lossy(&attr.value)
2080                                            .parse()
2081                                            .expect("failed to parse param minValue"),
2082                                    );
2083                                }
2084                                b"maxValue" => {
2085                                    param_max_value = Some(
2086                                        String::from_utf8_lossy(&attr.value)
2087                                            .parse()
2088                                            .expect("failed to parse param maxValue"),
2089                                    );
2090                                }
2091                                b"units" => {
2092                                    param_units =
2093                                        std::str::from_utf8(&attr.value).ok().map(str::to_owned);
2094                                }
2095                                b"enum" => {
2096                                    param_enum =
2097                                        std::str::from_utf8(&attr.value).ok().map(to_pascal_case);
2098                                }
2099                                b"reserved" => {
2100                                    param_reserved = attr.value.as_ref() == b"true";
2101                                }
2102                                b"default" => {
2103                                    param_default = Some(
2104                                        String::from_utf8_lossy(&attr.value)
2105                                            .parse()
2106                                            .expect("failed to parse param maxValue"),
2107                                    );
2108                                }
2109                                _ => (),
2110                            }
2111                        }
2112                        Some(&MavXmlElement::Deprecated) => match attr.key.into_inner() {
2113                            b"since" => {
2114                                lifecycle.as_mut().unwrap().since =
2115                                    String::from_utf8_lossy(&attr.value).to_string();
2116                            }
2117                            b"replaced_by" => {
2118                                let value = String::from_utf8_lossy(&attr.value);
2119                                if !value.is_empty()
2120                                    && let MavLifecycleType::Deprecated { replaced_by, .. } =
2121                                        &mut lifecycle.as_mut().unwrap().lifecycle_type
2122                                {
2123                                    *replaced_by = Some(value.to_string());
2124                                }
2125                            }
2126                            b"remove_on_date" => {
2127                                if let MavLifecycleType::Deprecated { remove_on_date, .. } =
2128                                    &mut lifecycle.as_mut().unwrap().lifecycle_type
2129                                {
2130                                    *remove_on_date =
2131                                        Some(String::from_utf8_lossy(&attr.value).to_string());
2132                                }
2133                            }
2134                            _ => (),
2135                        },
2136                        Some(&MavXmlElement::Superseded) => match attr.key.into_inner() {
2137                            b"since" => {
2138                                lifecycle.as_mut().unwrap().since =
2139                                    String::from_utf8_lossy(&attr.value).to_string();
2140                            }
2141                            b"replaced_by" => {
2142                                lifecycle.as_mut().unwrap().lifecycle_type =
2143                                    MavLifecycleType::Superseded {
2144                                        replaced_by: Some(
2145                                            String::from_utf8_lossy(&attr.value).to_string(),
2146                                        ),
2147                                    };
2148                            }
2149                            _ => (),
2150                        },
2151                        Some(&MavXmlElement::Wip) if attr.key.into_inner() == b"since" => {
2152                            lifecycle.as_mut().unwrap().since =
2153                                String::from_utf8_lossy(&attr.value).to_string();
2154                        }
2155                        _ => (),
2156                    }
2157                }
2158            }
2159            Ok(Event::Text(bytes)) => {
2160                let s = String::from_utf8_lossy(&bytes);
2161
2162                use self::MavXmlElement::*;
2163                match (stack.last(), stack.get(stack.len() - 2)) {
2164                    (Some(&Description), Some(&Message))
2165                    | (Some(&Field), Some(&Message))
2166                    | (Some(&Description), Some(&Enum))
2167                    | (Some(&Description), Some(&Entry))
2168                    | (Some(&Include), Some(&Mavlink))
2169                    | (Some(&Version), Some(&Mavlink))
2170                    | (Some(&Dialect), Some(&Mavlink))
2171                    | (Some(&Param), Some(&Entry))
2172                    | (Some(Deprecated), _)
2173                    | (Some(Superseded), _) => {
2174                        text = Some(text.map(|t| t + s.as_ref()).unwrap_or(s.to_string()));
2175                    }
2176                    data => {
2177                        panic!("unexpected text data {data:?} reading {s:?}");
2178                    }
2179                }
2180            }
2181            Ok(Event::GeneralRef(bytes)) => {
2182                let entity = String::from_utf8_lossy(&bytes);
2183                let decoded = resolve_xml_entity(&entity)
2184                    .map(str::to_owned)
2185                    .unwrap_or_else(|| format!("&{entity};"));
2186
2187                text = Some(text.map(|t| t + &decoded).unwrap_or(decoded));
2188            }
2189            Ok(Event::End(_)) => {
2190                match stack.last() {
2191                    Some(&MavXmlElement::Field) => {
2192                        field.description = text.map(|t| t.replace('\n', " "));
2193                        message.fields.push(field.clone());
2194                    }
2195                    Some(&MavXmlElement::Entry) => {
2196                        entry.lifecycle = lifecycle;
2197                        lifecycle = None;
2198                        mavenum.entries.push(entry.clone());
2199                    }
2200                    Some(&MavXmlElement::Message) => {
2201                        message.lifecycle = lifecycle;
2202
2203                        lifecycle = None;
2204                        is_in_extension = false;
2205                        // Follow mavlink ordering specification: https://mavlink.io/en/guide/serialization.html#field_reordering
2206                        let mut not_extension_fields = message.fields.clone();
2207                        let mut extension_fields = message.fields.clone();
2208
2209                        not_extension_fields.retain(|field| !field.is_extension);
2210                        extension_fields.retain(|field| field.is_extension);
2211
2212                        // Only not mavlink 1 fields need to be sorted
2213                        not_extension_fields.sort_by(|a, b| a.mavtype.compare(&b.mavtype));
2214
2215                        // Update msg fields and add the new message
2216                        let mut msg = message.clone();
2217                        msg.fields.clear();
2218                        msg.fields.extend(not_extension_fields);
2219                        msg.fields.extend(extension_fields);
2220
2221                        // Validate there are no duplicate field names
2222                        msg.validate_unique_fields();
2223                        // Validate field count must be between 1 and 64
2224                        msg.validate_field_count();
2225
2226                        profile.add_message(&msg);
2227                    }
2228                    Some(&MavXmlElement::Enum) => {
2229                        profile.add_enum(&mavenum);
2230                    }
2231                    Some(&MavXmlElement::Include) => {
2232                        let include =
2233                            PathBuf::from(text.map(|t| t.replace('\n', "")).unwrap_or_default());
2234                        let include_file = Path::new(&definitions_dir).join(include.clone());
2235                        if !parsed_files.contains(&include_file) {
2236                            let included_profile =
2237                                parse_profile(definitions_dir, &include, parsed_files)?;
2238                            for message in included_profile.messages.values() {
2239                                profile.add_message(message);
2240                            }
2241                            for enm in included_profile.enums.values() {
2242                                profile.add_enum(enm);
2243                            }
2244                            if profile.version.is_none() {
2245                                profile.version = included_profile.version;
2246                            }
2247                        }
2248                    }
2249                    Some(&MavXmlElement::Description) => match stack.get(stack.len() - 2) {
2250                        Some(&MavXmlElement::Message) => {
2251                            message.description = text.map(|t| t.replace('\n', " "));
2252                        }
2253                        Some(&MavXmlElement::Enum) => {
2254                            mavenum.description = text.map(|t| t.replace('\n', " "));
2255                        }
2256                        Some(&MavXmlElement::Entry) => {
2257                            entry.description = text.map(|t| t.replace('\n', " "));
2258                        }
2259                        _ => (),
2260                    },
2261                    Some(&MavXmlElement::Version) => {
2262                        if let Some(t) = text {
2263                            profile.version =
2264                                Some(t.parse().expect("Invalid minor version number format"));
2265                        }
2266                    }
2267                    Some(&MavXmlElement::Dialect) => {
2268                        if let Some(t) = text {
2269                            profile.dialect =
2270                                Some(t.parse().expect("Invalid dialect number format"));
2271                        }
2272                    }
2273                    Some(&MavXmlElement::Deprecated)
2274                    | Some(&MavXmlElement::Superseded)
2275                    | Some(&MavXmlElement::Wip) => {
2276                        if let Some(t) = text {
2277                            lifecycle.as_mut().unwrap().note = Some(t);
2278                        }
2279                    }
2280                    Some(&MavXmlElement::Param) => {
2281                        if let Some(params) = entry.params.as_mut() {
2282                            // Some messages can jump between values, like: 1, 2, 7
2283                            let param_index = param_index.expect("entry params must have an index");
2284                            while params.len() < param_index {
2285                                params.push(MavParam {
2286                                    index: params.len() + 1,
2287                                    description: None,
2288                                    ..Default::default()
2289                                });
2290                            }
2291                            if let Some((min, max)) = param_min_value.zip(param_max_value) {
2292                                assert!(
2293                                    min <= max,
2294                                    "param minValue must not be greater than maxValue"
2295                                );
2296                            }
2297                            params[param_index - 1] = MavParam {
2298                                index: param_index,
2299                                description: text.map(|t| t.replace('\n', " ")),
2300                                label: param_label,
2301                                units: param_units,
2302                                enum_used: param_enum,
2303                                increment: param_increment,
2304                                max_value: param_max_value,
2305                                min_value: param_min_value,
2306                                reserved: param_reserved,
2307                                default: param_default,
2308                            };
2309                            param_label = None;
2310                            param_units = None;
2311                            param_enum = None;
2312                        }
2313                    }
2314                    _ => (),
2315                }
2316                text = None;
2317                stack.pop();
2318                // println!("{}-{}", indent(depth), name);
2319            }
2320            Err(e) => {
2321                eprintln!("Error: {e}");
2322                break;
2323            }
2324            _ => {}
2325        }
2326    }
2327
2328    Ok(profile.update_enums())
2329}
2330
2331/// Generate protobuf represenation of mavlink message set
2332/// Generate rust representation of mavlink message set with appropriate conversion methods
2333pub fn generate<W: Write>(
2334    definitions_dir: &Path,
2335    definition_file: &Path,
2336    output_rust: &mut W,
2337) -> Result<(), BindGenError> {
2338    let mut parsed_files: HashSet<PathBuf> = HashSet::new();
2339    let profile = parse_profile(definitions_dir, definition_file, &mut parsed_files)?;
2340
2341    let dialect_name = util::to_dialect_name(definition_file);
2342
2343    // rust file
2344    let rust_tokens = profile.emit_rust(&dialect_name);
2345    writeln!(output_rust, "{rust_tokens}").unwrap();
2346
2347    Ok(())
2348}
2349
2350/// CRC operates over names of the message and names of its fields
2351/// Hence we have to preserve the original uppercase names delimited with an underscore
2352/// For field names, we replace "type" with "mavtype" to make it rust compatible (this is
2353/// needed for generating sensible rust code), but for calculating crc function we have to
2354/// use the original name "type"
2355pub fn extra_crc(msg: &MavMessage) -> u8 {
2356    // calculate a 8-bit checksum of the key fields of a message, so we
2357    // can detect incompatible XML changes
2358    let mut crc = CRCu16::crc16mcrf4cc();
2359
2360    crc.digest(msg.name.as_bytes());
2361    crc.digest(b" ");
2362
2363    let mut f = msg.fields.clone();
2364    // only mavlink 1 fields should be part of the extra_crc
2365    f.retain(|f| !f.is_extension);
2366    f.sort_by(|a, b| a.mavtype.compare(&b.mavtype));
2367    for field in &f {
2368        crc.digest(field.mavtype.primitive_type().as_bytes());
2369        crc.digest(b" ");
2370        if field.name == "mavtype" {
2371            crc.digest(b"type");
2372        } else {
2373            crc.digest(field.name.as_bytes());
2374        }
2375        crc.digest(b" ");
2376        if let MavType::Array(_, size) | MavType::CharArray(size) = field.mavtype {
2377            crc.digest(&[size as u8]);
2378        }
2379    }
2380
2381    let crcval = crc.get_crc();
2382    ((crcval & 0xFF) ^ (crcval >> 8)) as u8
2383}
2384
2385#[cfg(not(feature = "mav2-message-extensions"))]
2386struct ExtensionFilter {
2387    pub is_in: bool,
2388}
2389
2390struct MessageFilter {
2391    pub is_in: bool,
2392    pub messages: Vec<String>,
2393}
2394
2395impl MessageFilter {
2396    pub fn new() -> Self {
2397        Self {
2398            is_in: false,
2399            messages: vec![],
2400        }
2401    }
2402}
2403
2404struct MavXmlFilter {
2405    #[cfg(not(feature = "mav2-message-extensions"))]
2406    extension_filter: ExtensionFilter,
2407    message_filter: MessageFilter,
2408}
2409
2410impl Default for MavXmlFilter {
2411    fn default() -> Self {
2412        Self {
2413            #[cfg(not(feature = "mav2-message-extensions"))]
2414            extension_filter: ExtensionFilter { is_in: false },
2415            message_filter: MessageFilter::new(),
2416        }
2417    }
2418}
2419
2420impl MavXmlFilter {
2421    pub fn filter(&mut self, elements: &mut Vec<Result<Event, quick_xml::Error>>) {
2422        elements.retain(|x| self.filter_extension(x) && self.filter_messages(x));
2423    }
2424
2425    #[cfg(feature = "mav2-message-extensions")]
2426    pub fn filter_extension(&mut self, _element: &Result<Event, quick_xml::Error>) -> bool {
2427        true
2428    }
2429
2430    /// Ignore extension fields
2431    #[cfg(not(feature = "mav2-message-extensions"))]
2432    pub fn filter_extension(&mut self, element: &Result<Event, quick_xml::Error>) -> bool {
2433        match element {
2434            Ok(content) => {
2435                match content {
2436                    Event::Start(bytes) | Event::Empty(bytes) => {
2437                        let Some(id) = identify_element(bytes.name().into_inner()) else {
2438                            panic!(
2439                                "unexpected element {:?}",
2440                                String::from_utf8_lossy(bytes.name().into_inner())
2441                            );
2442                        };
2443                        if id == MavXmlElement::Extensions {
2444                            self.extension_filter.is_in = true;
2445                        }
2446                    }
2447                    Event::End(bytes) => {
2448                        let Some(id) = identify_element(bytes.name().into_inner()) else {
2449                            panic!(
2450                                "unexpected element {:?}",
2451                                String::from_utf8_lossy(bytes.name().into_inner())
2452                            );
2453                        };
2454
2455                        if id == MavXmlElement::Message {
2456                            self.extension_filter.is_in = false;
2457                        }
2458                    }
2459                    _ => {}
2460                }
2461                !self.extension_filter.is_in
2462            }
2463            Err(error) => panic!("Failed to filter XML: {error}"),
2464        }
2465    }
2466
2467    /// Filters messages by their name
2468    pub fn filter_messages(&mut self, element: &Result<Event, quick_xml::Error>) -> bool {
2469        match element {
2470            Ok(content) => {
2471                match content {
2472                    Event::Start(bytes) | Event::Empty(bytes) => {
2473                        let Some(id) = identify_element(bytes.name().into_inner()) else {
2474                            panic!(
2475                                "unexpected element {:?}",
2476                                String::from_utf8_lossy(bytes.name().into_inner())
2477                            );
2478                        };
2479                        if id == MavXmlElement::Message {
2480                            for attr in bytes.attributes() {
2481                                let attr = attr.unwrap();
2482                                if attr.key.into_inner() == b"name" {
2483                                    let value = String::from_utf8_lossy(&attr.value).into_owned();
2484                                    if self.message_filter.messages.contains(&value) {
2485                                        self.message_filter.is_in = true;
2486                                        return false;
2487                                    }
2488                                }
2489                            }
2490                        }
2491                    }
2492                    Event::End(bytes) => {
2493                        let Some(id) = identify_element(bytes.name().into_inner()) else {
2494                            panic!(
2495                                "unexpected element {:?}",
2496                                String::from_utf8_lossy(bytes.name().into_inner())
2497                            );
2498                        };
2499
2500                        if id == MavXmlElement::Message && self.message_filter.is_in {
2501                            self.message_filter.is_in = false;
2502                            return false;
2503                        }
2504                    }
2505                    _ => {}
2506                }
2507                !self.message_filter.is_in
2508            }
2509            Err(error) => panic!("Failed to filter XML: {error}"),
2510        }
2511    }
2512}
2513
2514#[inline(always)]
2515fn to_pascal_case(text: impl AsRef<[u8]>) -> String {
2516    let input = text.as_ref();
2517    let mut result = String::with_capacity(input.len());
2518    let mut capitalize = true;
2519
2520    for &b in input {
2521        if b == b'_' {
2522            capitalize = true;
2523            continue;
2524        }
2525
2526        if capitalize {
2527            result.push((b as char).to_ascii_uppercase());
2528            capitalize = false;
2529        } else {
2530            result.push((b as char).to_ascii_lowercase());
2531        }
2532    }
2533
2534    result
2535}
2536
2537#[cfg(test)]
2538mod tests {
2539    use super::*;
2540
2541    #[test]
2542    fn emits_target_id_match_arms() {
2543        // Build a minimal profile containing one message with target fields and one without
2544        let mut profile = MavProfile::default();
2545
2546        let msg_with_targets = MavMessage {
2547            id: 300,
2548            name: "COMMAND_INT".to_string(),
2549            description: None,
2550            fields: vec![
2551                MavField {
2552                    mavtype: MavType::UInt8,
2553                    name: "target_system".to_string(),
2554                    description: None,
2555                    enumtype: None,
2556                    display: None,
2557                    is_extension: false,
2558                    is_undersized: false,
2559                },
2560                MavField {
2561                    mavtype: MavType::UInt8,
2562                    name: "target_component".to_string(),
2563                    description: None,
2564                    enumtype: None,
2565                    display: None,
2566                    is_extension: false,
2567                    is_undersized: false,
2568                },
2569            ],
2570            lifecycle: None,
2571        };
2572
2573        let msg_without_targets = MavMessage {
2574            id: 0,
2575            name: "HEARTBEAT".to_string(),
2576            description: None,
2577            fields: vec![MavField {
2578                mavtype: MavType::UInt32,
2579                name: "custom_mode".to_string(),
2580                description: None,
2581                enumtype: None,
2582                display: None,
2583                is_extension: false,
2584                is_undersized: false,
2585            }],
2586            lifecycle: None,
2587        };
2588
2589        profile.add_message(&msg_with_targets);
2590        profile.add_message(&msg_without_targets);
2591
2592        let tokens = profile.emit_rust("common");
2593        let mut code = tokens.to_string();
2594        code.retain(|c| !c.is_whitespace());
2595
2596        // Check the code contains the target_system/component_id functions
2597        assert!(code.contains("fntarget_system_id(&self)->Option<u8>"));
2598        assert!(code.contains("fntarget_component_id(&self)->Option<u8>"));
2599        assert!(code.contains("fntarget_system_id_mut(&mutself)->Option<&mutu8>"));
2600        assert!(code.contains("fntarget_component_id_mut(&mutself)->Option<&mutu8>"));
2601
2602        // Check the generated impl contains arms referencing COMMAND_INT(inner).target_system/component
2603        assert!(code.contains("Self::COMMAND_INT(inner)=>Some(inner.target_system)"));
2604        assert!(code.contains("Self::COMMAND_INT(inner)=>Some(inner.target_component)"));
2605        assert!(code.contains("Self::COMMAND_INT(inner)=>Some(&mutinner.target_system)"));
2606        assert!(code.contains("Self::COMMAND_INT(inner)=>Some(&mutinner.target_component)"));
2607
2608        // Ensure a message without target fields returns None
2609        assert!(!code.contains("Self::HEARTBEAT(inner)=>Some(inner.target_system)"));
2610        assert!(!code.contains("Self::HEARTBEAT(inner)=>Some(inner.target_component)"));
2611        assert!(!code.contains("Self::HEARTBEAT(inner)=>Some(&mutinner.target_system)"));
2612        assert!(!code.contains("Self::HEARTBEAT(inner)=>Some(&mutinner.target_component)"));
2613    }
2614
2615    #[test]
2616    fn validate_unique_fields_allows_unique() {
2617        let msg = MavMessage {
2618            id: 1,
2619            name: "FOO".to_string(),
2620            description: None,
2621            fields: vec![
2622                MavField {
2623                    mavtype: MavType::UInt8,
2624                    name: "a".to_string(),
2625                    description: None,
2626                    enumtype: None,
2627                    display: None,
2628                    is_extension: false,
2629                    is_undersized: false,
2630                },
2631                MavField {
2632                    mavtype: MavType::UInt16,
2633                    name: "b".to_string(),
2634                    description: None,
2635                    enumtype: None,
2636                    display: None,
2637                    is_extension: false,
2638                    is_undersized: false,
2639                },
2640            ],
2641            lifecycle: None,
2642        };
2643        // Should not panic
2644        msg.validate_unique_fields();
2645    }
2646
2647    #[test]
2648    #[should_panic(expected = "Duplicate field")]
2649    fn validate_unique_fields_panics_on_duplicate() {
2650        let msg = MavMessage {
2651            id: 2,
2652            name: "BAR".to_string(),
2653            description: None,
2654            fields: vec![
2655                MavField {
2656                    mavtype: MavType::UInt8,
2657                    name: "target_system".to_string(),
2658                    description: None,
2659                    enumtype: None,
2660                    display: None,
2661                    is_extension: false,
2662                    is_undersized: false,
2663                },
2664                MavField {
2665                    mavtype: MavType::UInt8,
2666                    name: "target_system".to_string(),
2667                    description: None,
2668                    enumtype: None,
2669                    display: None,
2670                    is_extension: false,
2671                    is_undersized: false,
2672                },
2673            ],
2674            lifecycle: None,
2675        };
2676        // Should panic due to duplicate field names
2677        msg.validate_unique_fields();
2678    }
2679
2680    #[test]
2681    fn validate_field_count_ok() {
2682        let msg = MavMessage {
2683            id: 2,
2684            name: "FOO".to_string(),
2685            description: None,
2686            fields: vec![
2687                MavField {
2688                    mavtype: MavType::UInt8,
2689                    name: "a".to_string(),
2690                    description: None,
2691                    enumtype: None,
2692                    display: None,
2693                    is_extension: false,
2694                    is_undersized: false,
2695                },
2696                MavField {
2697                    mavtype: MavType::UInt8,
2698                    name: "b".to_string(),
2699                    description: None,
2700                    enumtype: None,
2701                    display: None,
2702                    is_extension: false,
2703                    is_undersized: false,
2704                },
2705            ],
2706            lifecycle: None,
2707        };
2708        // Should not panic
2709        msg.validate_field_count();
2710    }
2711
2712    #[test]
2713    #[should_panic]
2714    fn validate_field_count_too_many() {
2715        let mut fields = vec![];
2716        for i in 0..65 {
2717            let field = MavField {
2718                mavtype: MavType::UInt8,
2719                name: format!("field_{i}"),
2720                description: None,
2721                enumtype: None,
2722                display: None,
2723                is_extension: false,
2724                is_undersized: false,
2725            };
2726            fields.push(field);
2727        }
2728        let msg = MavMessage {
2729            id: 2,
2730            name: "BAZ".to_string(),
2731            description: None,
2732            fields,
2733            lifecycle: None,
2734        };
2735        // Should panic due to 65 fields
2736        msg.validate_field_count();
2737    }
2738
2739    #[test]
2740    #[should_panic]
2741    fn validate_field_count_empty() {
2742        let msg = MavMessage {
2743            id: 2,
2744            name: "BAM".to_string(),
2745            description: None,
2746            fields: vec![],
2747            lifecycle: None,
2748        };
2749        // Should panic due to no fields
2750        msg.validate_field_count();
2751    }
2752
2753    #[test]
2754    fn test_fmt_mav_param_values() {
2755        let enum_param = MavParam {
2756            enum_used: Some("ENUM_NAME".to_string()),
2757            ..Default::default()
2758        };
2759        assert_eq!(enum_param.format_valid_values(), "[`ENUM_NAME`]");
2760
2761        let reserved_param = MavParam {
2762            reserved: true,
2763            default: Some(f32::NAN),
2764            ..Default::default()
2765        };
2766        assert_eq!(reserved_param.format_valid_values(), "Reserved (use NaN)");
2767
2768        let unrestricted_param = MavParam::default();
2769        assert_eq!(unrestricted_param.format_valid_values(), "");
2770
2771        let int_param = MavParam {
2772            increment: Some(1.0),
2773            ..Default::default()
2774        };
2775        assert_eq!(int_param.format_valid_values(), "Multiples of 1");
2776
2777        let pos_param = MavParam {
2778            min_value: Some(0.0),
2779            ..Default::default()
2780        };
2781        assert_eq!(pos_param.format_valid_values(), "&ge; 0");
2782
2783        let max_param = MavParam {
2784            max_value: Some(5.5),
2785            ..Default::default()
2786        };
2787        assert_eq!(max_param.format_valid_values(), "&le; 5.5");
2788
2789        let pos_int_param = MavParam {
2790            min_value: Some(0.0),
2791            increment: Some(1.0),
2792            ..Default::default()
2793        };
2794        assert_eq!(pos_int_param.format_valid_values(), "0, 1, ..");
2795
2796        let max_inc_param = MavParam {
2797            increment: Some(1.0),
2798            max_value: Some(360.0),
2799            ..Default::default()
2800        };
2801        assert_eq!(max_inc_param.format_valid_values(), ".., 359, 360");
2802
2803        let range_param = MavParam {
2804            min_value: Some(0.0),
2805            max_value: Some(10.0),
2806            ..Default::default()
2807        };
2808        assert_eq!(range_param.format_valid_values(), "0 .. 10");
2809
2810        let int_range_param = MavParam {
2811            min_value: Some(0.0),
2812            max_value: Some(10.0),
2813            increment: Some(1.0),
2814            ..Default::default()
2815        };
2816        assert_eq!(int_range_param.format_valid_values(), "0, 1, .. , 10");
2817
2818        let close_inc_range_param = MavParam {
2819            min_value: Some(-2.0),
2820            max_value: Some(2.0),
2821            increment: Some(2.0),
2822            ..Default::default()
2823        };
2824        assert_eq!(close_inc_range_param.format_valid_values(), "-2, 0, 2");
2825
2826        let bin_range_param = MavParam {
2827            min_value: Some(0.0),
2828            max_value: Some(1.0),
2829            increment: Some(1.0),
2830            ..Default::default()
2831        };
2832        assert_eq!(bin_range_param.format_valid_values(), "0, 1");
2833    }
2834
2835    #[test]
2836    fn test_emit_doc_row() {
2837        let param = MavParam {
2838            index: 3,
2839            label: Some("test param".to_string()),
2840            min_value: Some(0.0),
2841            units: Some("m/s".to_string()),
2842            ..Default::default()
2843        };
2844        // test with all variations of columns
2845        assert_eq!(
2846            param.emit_doc_row(false, false).to_string(),
2847            quote! {#[doc = "| 3 (test param)|             |"]}.to_string()
2848        );
2849        assert_eq!(
2850            param.emit_doc_row(false, true).to_string(),
2851            quote! {#[doc = "| 3 (test param)|             | m/s |"]}.to_string()
2852        );
2853        assert_eq!(
2854            param.emit_doc_row(true, false).to_string(),
2855            quote! {#[doc = "| 3 (test param)|             | &ge; 0 |"]}.to_string()
2856        );
2857        assert_eq!(
2858            param.emit_doc_row(true, true).to_string(),
2859            quote! {#[doc = "| 3 (test param)|             | &ge; 0 | m/s |"]}.to_string()
2860        );
2861
2862        let unlabeled_param = MavParam {
2863            index: 2,
2864            ..Default::default()
2865        };
2866        assert_eq!(
2867            unlabeled_param.emit_doc_row(false, false).to_string(),
2868            quote! {#[doc = "| 2         |             |"]}.to_string()
2869        );
2870    }
2871}