mavspec_rust_gen 0.6.7

Rust code generation module for MAVSpec.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use crate::consts::{MAV_CMD, MAV_CMD_MISSION_SUBSETS};
use crate::conventions::{
    description_doc_comment_line, dialect_mod_name, enum_bitmask_entry_name, enum_entry_name,
    enum_mod_name, enum_rust_name, enum_specta_name,
};
use crate::conventions::{microservice_doc_mention, microservice_enum_specta_name};
use crate::specs::dialects::dialect::enums::{
    EnumImplModuleSpec, EnumInheritedModuleSpec, EnumsRootModuleSpec,
};
use crate::specs::Spec;
use crate::templates::helpers::{make_serde_derive_annotation, make_specta_derive_annotation};
use quote::{format_ident, quote};

pub(crate) fn enums_root_module(spec: &EnumsRootModuleSpec) -> syn::File {
    let module_doc_comment = match spec.msrv_name() {
        Some(msrv_name) => {
            format!(
                "# MAVLink enums for {} microservice of `{}` dialect",
                microservice_doc_mention(msrv_name),
                spec.dialect_canonical_name()
            )
        }
        None => format!(
            " MAVLink enums of `{}` dialect.",
            spec.dialect_canonical_name()
        ),
    };

    let enum_modules_and_imports = spec.enums().iter().map(|enm| {
        let enum_mod_name = format_ident!("{}", enum_mod_name(enm.name()));
        let enum_rust_name = format_ident!("{}", enum_rust_name(enm.name()));
        quote! {
            pub mod #enum_mod_name;
            pub use #enum_mod_name::#enum_rust_name;
        }
    });

    syn::parse2(quote! {
        #![doc = #module_doc_comment]

        #(#enum_modules_and_imports)*
    })
    .unwrap()
}

pub(crate) fn enum_module(spec: &EnumImplModuleSpec) -> syn::File {
    let module_doc_comment = match spec.msrv_name() {
        Some(msrv_name) => {
            format!(
                "# MAVLink `{}` enum implementation for {} microservice of `{}` dialect",
                spec.name(),
                microservice_doc_mention(msrv_name),
                spec.dialect().name(),
            )
        }
        None => format!(
            " MAVLink `{}` enum implementation for `{}` dialect.",
            spec.name(),
            spec.dialect().name(),
        ),
    };

    let mavspec_import = spec.params().mavspec_import();

    let bitmask_impl = make_bitmask_enum(spec);
    let enum_impl = make_enum(spec);

    syn::parse2(quote! {
        #![doc = #module_doc_comment]

        #mavspec_import

        #bitmask_impl
        #enum_impl
    })
    .unwrap()
}

fn make_bitmask_enum(spec: &EnumImplModuleSpec) -> proc_macro2::TokenStream {
    let leading_doc_comment = match spec.msrv_name() {
        Some(msrv_name) => {
            format!(
                "# MAVLink bitmask enum `{}` of {} microservice for `{}` dialect",
                spec.name(),
                microservice_doc_mention(msrv_name),
                spec.dialect().name(),
            )
        }
        None => format!(
            " MAVLink bitmask enum `{}` for `{}` dialect.",
            spec.name(),
            spec.dialect().name(),
        ),
    };

    let specta_name = match spec.msrv_name() {
        Some(msrv_name) => microservice_enum_specta_name(msrv_name, spec.name(), None),
        None => enum_specta_name(spec.name(), spec.dialect().canonical_name()),
    };

    let description_doc_comments = spec.description().iter().map(description_doc_comment_line);
    let derive_serde = make_serde_derive_annotation(spec.params().serde);
    let derive_specta =
        make_specta_derive_annotation(spec.params().specta, Some(specta_name.as_str()));
    let enum_ident = format_ident!("{}", enum_rust_name(spec.name()));
    let enum_inferred_type = format_ident!("{}", spec.inferred_type().rust_type());

    let entry_consts = spec.entries().iter().map(|entry| {
        let name_doc_comment = format!("`{}` flag.", entry.name());
        let description_doc_comments = entry.description().iter().map(description_doc_comment_line);
        let flag_ident = format_ident!("{}", enum_bitmask_entry_name(entry.name_stripped()));
        let flag_value = entry.value_expr();

        quote! {
            #[doc = #name_doc_comment]
            ///
            #(#description_doc_comments)*
            const #flag_ident = #flag_value;
        }
    });

    if spec.is_bitmask() {
        quote! {
            use mavspec::rust::spec::bitflags::bitflags;

            #[allow(rustdoc::bare_urls)]
            #[allow(rustdoc::broken_intra_doc_links)]
            #[allow(rustdoc::invalid_rust_codeblocks)]
            #[doc = #leading_doc_comment]
            ///
            #(#description_doc_comments)*
            #[derive(core::marker::Copy, core::clone::Clone, core::fmt::Debug, core::default::Default, core::cmp::PartialEq)]
            #derive_specta
            #derive_serde
            pub struct #enum_ident(#enum_inferred_type);

            bitflags! {
                impl #enum_ident: #enum_inferred_type {
                    #(#entry_consts)*
                }
            }
        }
    } else {
        quote!()
    }
}

fn make_enum(spec: &EnumImplModuleSpec) -> proc_macro2::TokenStream {
    if spec.is_bitmask() {
        quote!()
    } else {
        let leading_doc_comment = match spec.msrv_name() {
            Some(msrv_name) => {
                format!(
                    "# MAVLink enum `{}` of {} microservice for `{}` dialect",
                    spec.name(),
                    microservice_doc_mention(msrv_name),
                    spec.dialect().name(),
                )
            }
            None => format!(
                " MAVLink enum `{}` for `{}` dialect.",
                spec.name(),
                spec.dialect().name(),
            ),
        };

        let specta_name = match spec.msrv_name() {
            Some(msrv_name) => microservice_enum_specta_name(msrv_name, spec.name(), None),
            None => enum_specta_name(spec.name(), spec.dialect().canonical_name()),
        };

        let description_doc_comments = spec.description().iter().map(description_doc_comment_line);
        let derive_serde = make_serde_derive_annotation(spec.params().serde);
        let derive_specta =
            make_specta_derive_annotation(spec.params().specta, Some(specta_name.as_str()));
        let enum_ident = format_ident!("{}", enum_rust_name(spec.name()));
        let enum_inferred_type = format_ident!("{}", spec.inferred_type().rust_type());

        let enum_variants = spec.entries().iter().map(|entry| {
            let name_doc_comment = format!(" MAVLink enum entry `{}`.", entry.name());
            let description_doc_comments =
                entry.description().iter().map(description_doc_comment_line);
            let entry_ident = format_ident!("{}", enum_entry_name(entry.name_stripped()));
            let entry_value = entry.value_expr();

            quote! {
                #[doc = #name_doc_comment]
                ///
                #(#description_doc_comments)*
                #entry_ident = #entry_value,
            }
        });

        let default = if !spec.entries().is_empty() {
            quote! {
                #[default]
            }
        } else {
            quote!()
        };

        let conversions = generate_enum_conventions(spec);
        let metadata = generate_enum_metadata(spec);

        quote! {
            #[allow(rustdoc::bare_urls)]
            #[allow(rustdoc::broken_intra_doc_links)]
            #[allow(rustdoc::invalid_rust_codeblocks)]
            #[doc = #leading_doc_comment]
            ///
            #(#description_doc_comments)*
            #[derive(mavspec::rust::derive::Enum)]
            #[derive(core::marker::Copy, core::clone::Clone, core::fmt::Debug, core::default::Default, core::cmp::PartialEq)]
            #[repr(#enum_inferred_type)]
            #derive_specta
            #derive_serde
            pub enum #enum_ident {
                #default
                #(#enum_variants)*
            }

            #conversions

            #metadata
        }
    }
}

pub(crate) fn enum_inherited_module(spec: &EnumInheritedModuleSpec) -> syn::File {
    let module_doc_comment = format!(
        " MAVLink enum `{}` of `{}` dialect inherited from `{}` dialect.",
        spec.name(),
        spec.dialect_canonical_name(),
        spec.original_dialect_name()
    );
    let module_doc_comment = match spec.msrv_name() {
        Some(msrv_name) => format!(
            " MAVLink enum `{}` of {} microservice for `{}` dialect inherited from `{}` dialect.",
            spec.name(),
            microservice_doc_mention(msrv_name),
            spec.dialect_canonical_name(),
            spec.original_dialect_name()
        ),
        None => module_doc_comment,
    };

    let enum_ident = format_ident!("{}", enum_rust_name(spec.name()));
    let original_dialect_mod_ident =
        format_ident!("{}", dialect_mod_name(spec.original_dialect_name()));

    let original_dialect_import_path = quote! { super::super::super::#original_dialect_mod_ident };
    let original_dialect_import_path = match spec.msrv_name() {
        Some(_) => quote! { super::super::#original_dialect_import_path },
        None => original_dialect_import_path,
    };

    let enum_mod_ident = format_ident!("{}", enum_mod_name(spec.name()));
    let enum_doc_comment = format!(" Originally defined in [`{original_dialect_mod_ident}::enums::{enum_mod_ident}`](dialect::enums::{enum_ident})");

    syn::parse2(quote! {
        #![doc = #module_doc_comment]

        use #original_dialect_import_path as dialect;

        #[doc = #enum_doc_comment]
        pub type #enum_ident = dialect::enums::#enum_mod_ident::#enum_ident;
    })
    .unwrap()
}

fn generate_enum_conventions(spec: &EnumImplModuleSpec) -> proc_macro2::TokenStream {
    match spec.msrv() {
        Some(msrv) => {
            let enum_ident = format_ident!("{}", enum_rust_name(spec.name()));
            let enum_name = spec.name().to_string();

            let mav_cmd_conversion = if MAV_CMD_MISSION_SUBSETS.contains(&spec.name()) {
                let mav_cmd_enum_ident = format_ident!("{}", enum_rust_name(MAV_CMD));

                let from_sub_enum_to_mav_cmd_match_arms = spec.entries().iter().map(|entry| {
                    let sub_entry_ident =
                        format_ident!("{}", enum_entry_name(entry.name_stripped()));

                    let mav_cmd_entry = spec.dialect()
                        .get_enum_by_name(MAV_CMD)
                        .expect("'MAV_CMD' should be in dialect")
                        .get_entry_by_name(entry.name())
                        .expect("'MAV_CMD' should contain an entry");
                    let mav_cmd_entry_ident = format_ident!("{}", enum_entry_name(mav_cmd_entry.name_stripped()));

                    quote! {
                            #enum_ident::#sub_entry_ident => super::#mav_cmd_enum_ident::#mav_cmd_entry_ident,
                        }
                });

                let from_mav_cmd_to_sub_enum_match_arms = spec.entries().iter().map(|entry| {
                    let sub_entry_ident =
                        format_ident!("{}", enum_entry_name(entry.name_stripped()));

                    let mav_cmd_entry = spec.dialect()
                        .get_enum_by_name(MAV_CMD)
                        .expect("'MAV_CMD' should be in dialect")
                        .get_entry_by_name(entry.name())
                        .expect("'MAV_CMD' should contain an entry");
                    let mav_cmd_entry_ident = format_ident!("{}", enum_entry_name(mav_cmd_entry.name_stripped()));

                    quote! {
                            super::#mav_cmd_enum_ident::#mav_cmd_entry_ident => #enum_ident::#sub_entry_ident,
                        }
                });

                quote! {
                   impl core::convert::From<#enum_ident> for super::#mav_cmd_enum_ident {
                        fn from(value: #enum_ident) -> Self {
                            #[allow(unreachable_patterns)]
                            match value {
                                #(#from_sub_enum_to_mav_cmd_match_arms)*
                                _ => unreachable!()
                            }
                        }
                    }

                    impl core::convert::TryFrom<super::#mav_cmd_enum_ident> for #enum_ident {
                        type Error = mavspec::rust::spec::SpecError;

                        fn try_from(value: super::#mav_cmd_enum_ident) -> Result<Self, Self::Error> {
                            #[allow(unreachable_patterns)]
                            Ok(match value {
                                #(#from_mav_cmd_to_sub_enum_match_arms)*
                                _ => return Err(Self::Error::InvalidEnumValue {
                                    enum_name: #enum_name
                                }),
                            })
                        }
                    }
                }
            } else {
                quote! {}
            };

            let parent_enum_conversions = if msrv.parent().contains_enum_with_name(spec.name()) {
                let parent_enum_ident = quote! { super::super::super::super::enums::#enum_ident };
                let from_enum_to_parent_match_arms = spec.entries().iter().map(|entry| {
                    let entry_ident = format_ident!("{}", enum_entry_name(entry.name_stripped()));
                    quote! {
                        #enum_ident::#entry_ident => #parent_enum_ident::#entry_ident,
                    }
                });
                let from_parent_enum_to_enum_match_arms = spec.entries().iter().map(|entry| {
                    let entry_ident = format_ident!("{}", enum_entry_name(entry.name_stripped()));
                    quote! {
                        #parent_enum_ident::#entry_ident => #enum_ident::#entry_ident,
                    }
                });

                quote! {
                    impl core::convert::From<#enum_ident> for #parent_enum_ident {
                        fn from(value: #enum_ident) -> Self {
                            #[allow(unreachable_patterns)]
                            match value {
                                #(#from_enum_to_parent_match_arms)*
                                _ => unreachable!()
                            }
                        }
                    }

                    impl core::convert::TryFrom<#parent_enum_ident> for #enum_ident {
                        type Error = mavspec::rust::spec::SpecError;

                        fn try_from(value: #parent_enum_ident) -> Result<Self, Self::Error> {
                            Ok(match value {
                                #(#from_parent_enum_to_enum_match_arms)*
                                _ => return Err(Self::Error::InvalidEnumValue{
                                    enum_name: #enum_name
                                }),
                            })
                        }
                    }
                }
            } else {
                quote! {}
            };

            quote! {
                #parent_enum_conversions
                #mav_cmd_conversion
            }
        }
        None => quote! {},
    }
}

fn generate_enum_metadata(spec: &EnumImplModuleSpec) -> proc_macro2::TokenStream {
    if !spec.params().metadata {
        return quote! {};
    }

    let name = spec.name();

    let enum_ident = format_ident!("{}", enum_rust_name(spec.name()));
    let entry_variants = spec.entries().iter().map(|entry| {
        let entry_ident = format_ident!("{}", enum_entry_name(entry.name_stripped()));

        quote! {
            Self::#entry_ident
        }
    });

    let enum_inferred_type = format_ident!("{}", spec.inferred_type().rust_type());

    quote! {
        impl #enum_ident {
            /// Returns a canonical MAVLink name
            #[inline]
            pub fn name() -> &'static str {
                #name
            }

            /// Iterator over all entries within this enum.
            ///
            /// Requires `metadata` feature flag to be enabled.
            pub fn entries() -> impl Iterator<Item=Self> {
                [#(#entry_variants,)*].iter().copied()
            }

            /// Returns value of this enum variant.
            ///
            /// Requires `metadata` feature flag to be enabled.
            #[inline]
            pub fn value(&self) -> #enum_inferred_type {
                self.clone() as #enum_inferred_type
            }
        }
    }
}