vpp-plugin-api-gen 0.2.1

Rust code generator for VPP API files.
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
//! Generate Rust code for VPP API files
//!
//! A small Rust-based code generator that produces Rust bindings and helper scaffolding for VPP
//! `.api` files for implementing VPP plugins. This crate can be run from a build script (see
//! [`Builder`]) and emits both Rust source and a JSON representation of the parsed API.
//!
//! # Design rationale (why a Rust crate, not an extension to `vppapigen.py`)
//!
//! - Insulation against upstream changes: integrating with vppapigen.py via code outside of the vpp
//!   repository like this would need to make the assumption that the vppapigen.py internal API
//!   doesn't change in non-backwards-compatible ways which would be unreasonable to
//!   assume. Implementing the parser standalone avoids that issue, although it does now mean that
//!   any extensions to the API grammer used by plugins or their imports would need to be
//!   implemented here.
//! - Dependency control: shipping the generator as a crate avoids introducing an extra Python
//!   dependencies into build systems that cannot be expressed via crate dependencies.
//! - Robustness against environment: performing a `cargo build` when set into an unrelated Python
//!   venv could lead to spurious failures if the venv doesn't have all of the Python dependencies
//!   needed by vppapigen.py. Implementing in Rust avoids that.
//!
//! # Parsing strategy: why PEG (Parsing Expression Grammar) over CFG
//!
//! The implementation chooses a PEG-style parser (implemented in `parser.rs`) rather than a
//! traditional context-free grammar (CFG) parser generator for several practical reasons:
//!
//! - Determinism and simplicity: PEGs are deterministic and describe a single unambiguous parse for
//!   any input (given the grammar and choice ordering).
//!   For the `.api` format — which is relatively small, regular and unambiguous — a PEG results in
//!   simpler grammars and parsing code without needing extra disambiguation rules.
//! - Ergonomics in Rust: mature PEG libraries and small hand-written PEG parsers are
//!   straightforward to implement and embed in a Rust crate. CFG tools (LR, LALR) are typically
//!   geared toward generating parser tables and a runtime which is less ergonomic to integrate into
//!   a small generator crate and tends to complicate error reporting and tooling.
//! - Better error locality: PEGs (and hand-written recursive-descent parsers) make it easier to
//!   attach localized error messages and recover cleanly for diagnostics or partial parsing.
//!
//! Trade-offs and caveats:
//! - PEG grammars do not support left-recursive rules naturally. For the `.api` grammar this is not
//!   a practical limitation because the syntax is not left-recursive and is well-suited to a PEG
//!   style.
//! - CFG-based parser generators can handle certain ambiguous grammars more naturally and can
//!   produce more compact parser tables for very large and complex grammars. Here, the space of
//!   constructs is small and well-bounded, so the simplicity and determinism of PEG were preferred.

#![warn(
    missing_docs,
    missing_copy_implementations,
    missing_debug_implementations
)]

use std::{
    env,
    fs::{DirBuilder, File},
    io::Write,
    path::Path,
};

use thiserror::Error;

use crate::{
    json::generate_json,
    parser::{
        Alias, ApiParser, CountDescriptor, Enum, Field, FieldSize, Message, Type, Union,
        VL_API_PREFIX, VL_API_SUFFIX,
    },
};

mod json;
mod parser;

/// Errors that can occur during API file parsing and code generation
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// Parser error
    #[error("Parser error")]
    Parser(#[from] parser::Error),
    /// Input/output error
    #[error("I/O error")]
    Io(#[from] std::io::Error),
    /// Error whilst generating JSON
    #[error("Failed to generate JSON")]
    Json(#[from] serde_json::Error),
    /// Attempt to use functionality that isn't yet implemented
    #[error("{0}")]
    Unimplemented(String),
}

fn to_upper_camel_case(s: &str) -> String {
    s.split('_')
        .flat_map(|word| {
            let word = word.to_ascii_lowercase();
            let mut chars = word.chars();
            let capital = chars.next().map(|x| x.to_ascii_uppercase());
            capital.into_iter().chain(chars).collect::<Vec<_>>()
        })
        .collect()
}

trait ApiParserRustExt {
    fn to_rust_type(&self, r#type: &str) -> Result<String, Error>;
    fn to_rust_vla_elem_type(&self, r#type: &str) -> Result<String, Error>;
}

impl ApiParserRustExt for ApiParser {
    fn to_rust_type(&self, r#type: &str) -> Result<String, Error> {
        Ok(
            if let Some(t) = r#type.strip_prefix(VL_API_PREFIX)
                && let Some(t) = t.strip_suffix(VL_API_SUFFIX)
            {
                let global_type = self.lookup_global_type(t)?;
                if let Some(import_module) = global_type.import_module() {
                    format!("super::{}_api::{}", import_module, to_upper_camel_case(t))
                } else {
                    to_upper_camel_case(t)
                }
            } else {
                r#type.to_string()
            },
        )
    }

    fn to_rust_vla_elem_type(&self, r#type: &str) -> Result<String, Error> {
        Ok(match r#type {
            // Note: u8 excluded here as it already has an alignment of 1 byte
            "u16" | "i16" | "u32" | "i32" | "u64" | "i64" | "f64" => {
                format!(
                    "::vpp_plugin::vlibapi::num_unaligned::Unaligned{}",
                    to_upper_camel_case(r#type)
                )
            }
            _ => self.to_rust_type(r#type)?,
        })
    }
}

/// Generate Rust code for the VPP handling of APIs of from a `.api` file
///
/// # Examples
///
/// Example of use from a build script:
///
/// ```no_run
/// use std::{env, path::PathBuf};
///
/// let output_dir = PathBuf::from(env::var("OUT_DIR").unwrap()).join("src");
/// vpp_plugin_api_gen::Builder::new("example.api", &output_dir.to_string_lossy())
///     .expect("unable to generate API binding")
///     .generate()
///     .expect("unable to generate API binding");
/// ```
///
/// This can then be include in the plugin as follows:
///
/// ```ignore
/// mod example_api {
///     include!(concat!(env!("OUT_DIR"), "/src/example_api.rs"));
/// }
/// ```
#[derive(Debug)]
pub struct Builder {
    parser: ApiParser,

    module: String,
    output_file: File,
    output_json_file: File,
}

impl Builder {
    /// Construct a new `Builder` for the given input file and outputting to the given directory
    ///
    /// Both a `<api-module>_api.rs` and a `<api-module>.api.json` file will be generated in
    /// the output directory.
    pub fn new(input_file: &str, output_dir: &str) -> Result<Self, Error> {
        let in_build_script = env::var("OUT_DIR").is_ok() && env::var("CARGO_MANIFEST_DIR").is_ok();
        if in_build_script {
            println!("cargo:cargo-rerun-if-changed={}", input_file);
        }

        // Get file name without path
        let input_file_name = Path::new(input_file).iter().next_back().unwrap();
        let module = Path::new(input_file_name)
            .file_stem()
            .unwrap()
            .to_string_lossy()
            .to_string();

        DirBuilder::new().recursive(true).create(output_dir)?;
        let output_file = Path::new(output_dir).join(format!("{}_api.rs", module));
        let output_json_file = Path::new(output_dir).join(format!("{}.api.json", module));

        let parser = ApiParser::new(input_file)?;

        if in_build_script {
            for import in parser.imports() {
                println!("cargo:cargo-rerun-if-changed={}", import);
            }
        }

        Ok(Self {
            parser,
            module,
            output_file: File::create(&output_file)?,
            output_json_file: File::create(&output_json_file)?,
        })
    }

    /// Generate Rust code for the API file
    ///
    /// Both a `<api-module>_api.rs` and a `<api-module>.api.json` file will be generated in
    /// the output directory.
    pub fn generate(self) -> Result<(), Error> {
        ApiGenContext {
            parser: &self.parser,
            module: self.module,
            output_file: self.output_file,
            output_json_file: self.output_json_file,
        }
        .generate()
    }
}

enum EndianSwapInput<'a> {
    Fields(&'a [Field]),
    Alias(&'a Field),
}

/// Helper structure for API code generation
///
/// Mark parser as non-mutable to avoid borrow-check errors when passing references obtained from
/// parser into `&mut self` methods.
struct ApiGenContext<'a> {
    parser: &'a ApiParser,

    module: String,
    output_file: File,
    output_json_file: File,
}

impl ApiGenContext<'_> {
    fn generate_field(&mut self, field: &Field) -> Result<(), Error> {
        if field.r#type == "string" {
            match &field.size {
                Some(FieldSize::Fixed(size)) => {
                    writeln!(
                        self.output_file,
                        "    pub {}: ::vpp_plugin::vlibapi::ApiFixedString<{}>,",
                        field.name, size,
                    )?;
                    return Ok(());
                }
                Some(FieldSize::Variable(None)) => {
                    writeln!(
                        self.output_file,
                        "    pub {}: ::vpp_plugin::vlibapi::ApiString,",
                        field.name,
                    )?;
                    return Ok(());
                }
                _ => {}
            }
        }

        match &field.size {
            Some(FieldSize::Fixed(size)) => {
                writeln!(
                    self.output_file,
                    "    pub {}: [{}; {}],",
                    field.name,
                    self.parser.to_rust_type(&field.r#type)?,
                    size,
                )?;
            }
            Some(FieldSize::Variable(_)) => {
                writeln!(
                    self.output_file,
                    "    pub {}: [{}; 0],",
                    field.name,
                    self.parser.to_rust_vla_elem_type(&field.r#type)?,
                )?;
            }
            None => {
                writeln!(
                    self.output_file,
                    "    pub {}: {},",
                    field.name,
                    self.parser.to_rust_type(&field.r#type)?,
                )?;
            }
        }
        Ok(())
    }

    fn generate_debug_trait(&mut self, name: &str, fields: &[Field]) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(name);

        writeln!(
            self.output_file,
            "impl ::std::fmt::Debug for {} {{",
            upper_camel_name
        )?;
        // Suppress warnings about tmp__vl_msg_id (and any similar)
        writeln!(self.output_file, "    #[allow(non_snake_case)]")?;
        writeln!(
            self.output_file,
            "    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {{"
        )?;
        for field in fields {
            if !matches!(field.size, Some(FieldSize::Variable(_))) {
                writeln!(
                    self.output_file,
                    "        let tmp_{} = self.{};",
                    field.name, field.name
                )?;
            }
        }
        writeln!(
            self.output_file,
            "        f.debug_struct(\"{}\")",
            upper_camel_name
        )?;
        for field in fields {
            if !matches!(field.size, Some(FieldSize::Variable(_))) {
                writeln!(
                    self.output_file,
                    "            .field(\"{}\", &tmp_{})",
                    field.name, field.name
                )?;
            }
        }
        writeln!(self.output_file, "            .finish_non_exhaustive()")?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        Ok(())
    }

    fn generate_vla_accessors(&mut self, count_field: &str, field: &Field) -> Result<(), Error> {
        let vla_elem_type = self.parser.to_rust_vla_elem_type(&field.r#type)?;
        writeln!(self.output_file, "    #[allow(dead_code)]")?;
        writeln!(
            self.output_file,
            "    pub unsafe fn {}(&self) -> &[{}] {{",
            field.name, vla_elem_type
        )?;
        writeln!(self.output_file, "        unsafe {{",)?;
        writeln!(
            self.output_file,
            "            ::std::slice::from_raw_parts(std::ptr::addr_of!(self.{}).cast(), self.{} as usize)",
            field.name, count_field
        )?;
        writeln!(self.output_file, "        }}",)?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file)?;
        writeln!(self.output_file, "    #[allow(dead_code)]")?;
        writeln!(
            self.output_file,
            "    pub unsafe fn {}_mut(&mut self) -> &mut [{}] {{",
            field.name, vla_elem_type
        )?;
        writeln!(self.output_file, "        unsafe {{",)?;
        writeln!(
            self.output_file,
            "            std::slice::from_raw_parts_mut(std::ptr::addr_of_mut!(self.{}).cast(), self.{} as usize)",
            field.name, count_field
        )?;
        writeln!(self.output_file, "        }}",)?;
        writeln!(self.output_file, "    }}")?;

        Ok(())
    }

    fn generate_message(&mut self, id: usize, message: &Message) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(message.name());

        if let Some(comment) = message.comment() {
            writeln!(
                self.output_file,
                "#[doc = \"{}\"]",
                comment.replace("\"", "\\\"")
            )?;
        }
        let opt_derives = if message.manual_print() || message.vla_non_recursive().is_some() {
            ""
        } else if message.vla(self.parser).is_some() {
            "Debug, "
        } else {
            "Debug, PartialEq, "
        };
        writeln!(self.output_file, "#[derive({}Copy, Clone)]", opt_derives)?;
        writeln!(self.output_file, "#[repr(C, packed)]")?;
        writeln!(self.output_file, "pub struct {} {{", upper_camel_name)?;
        for field in message.fields() {
            self.generate_field(field)?;
        }
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(self.output_file, "impl {} {{", upper_camel_name)?;
        writeln!(self.output_file, "    pub const MSG_ID: u16 = {};", id)?;
        writeln!(self.output_file)?;
        writeln!(self.output_file, "    pub fn msg_id() -> u16 {{")?;
        writeln!(self.output_file, "        msg_id_base() + Self::MSG_ID")?;
        writeln!(self.output_file, "    }}")?;
        if let Some((field, count_descr)) = message.vla(self.parser) {
            writeln!(self.output_file)?;
            if let Some(FieldSize::Variable(Some(count_field))) = &field.size {
                self.generate_vla_accessors(count_field, field)?;
                writeln!(self.output_file)?;
            }
            writeln!(self.output_file, "    #[allow(dead_code)]")?;
            match count_descr {
                CountDescriptor::Field { path, r#type } => {
                    let var_name = path.last().cloned().unwrap_or_default();
                    writeln!(
                        self.output_file,
                        "    pub fn new_message({}: {}) -> ::vpp_plugin::vlibapi::Message<Self> {{",
                        var_name, r#type
                    )?;
                    // Avoid clippy::unnecessary_cast warning by only casting when the count field isn't a u32
                    let count_expr = if r#type == "u32" {
                        var_name.clone()
                    } else {
                        format!("{} as u32", var_name)
                    };
                    writeln!(
                        self.output_file,
                        "        let size = ::std::mem::size_of::<Self>() as u32 + {} * ::std::mem::size_of::<{}>() as u32;",
                        count_expr,
                        self.parser.to_rust_type(&field.r#type)?,
                    )?;
                    writeln!(
                        self.output_file,
                        "        let mut message = unsafe {{ ::std::mem::transmute::<::vpp_plugin::vlibapi::Message<u8>, ::vpp_plugin::vlibapi::Message<Self>>(::vpp_plugin::vlibapi::Message::new_bytes(size)) }};",
                    )?;
                    writeln!(
                        self.output_file,
                        "        message._vl_msg_id = Self::msg_id();",
                    )?;
                    writeln!(
                        self.output_file,
                        "        message.{} = {};",
                        path.join("."),
                        var_name,
                    )?;
                }
                CountDescriptor::String(path) => {
                    writeln!(
                        self.output_file,
                        "    pub fn new_message(length: u32) -> ::vpp_plugin::vlibapi::Message<Self> {{",
                    )?;
                    writeln!(
                        self.output_file,
                        "        let size = ::std::mem::size_of::<Self>() as u32 + length;",
                    )?;
                    writeln!(
                        self.output_file,
                        "        let mut message = unsafe {{ ::std::mem::transmute::<::vpp_plugin::vlibapi::Message<u8>, ::vpp_plugin::vlibapi::Message<Self>>(::vpp_plugin::vlibapi::Message::new_bytes(size)) }};",
                    )?;
                    writeln!(
                        self.output_file,
                        "        message._vl_msg_id = Self::msg_id();",
                    )?;
                    writeln!(
                        self.output_file,
                        "        unsafe {{ message.{}.set_len(length); }}",
                        path.join("."),
                    )?;
                }
            }
            writeln!(self.output_file, "        message",)?;
            writeln!(self.output_file, "    }}")?;
            writeln!(self.output_file)?;
        }
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(self.output_file, "impl Default for {} {{", upper_camel_name)?;
        writeln!(self.output_file, "    fn default() -> Self {{")?;
        writeln!(self.output_file, "        Self {{")?;
        for field in message.fields() {
            if field.name == "_vl_msg_id" {
                writeln!(self.output_file, "            _vl_msg_id: Self::msg_id(),")?;
            } else {
                writeln!(
                    self.output_file,
                    "            {}: Default::default(),",
                    field.name,
                )?;
            }
        }
        writeln!(self.output_file, "        }}")?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        self.generate_endian_swap(message.name(), EndianSwapInput::Fields(message.fields()))?;

        // Manually implement fmt::Debug so that the zero-length (but actually variable-length)
        // field isn't printed to avoid misleading anyone looking at the output
        if message.vla_non_recursive().is_some() {
            self.generate_debug_trait(message.name(), message.fields())?;
        }

        writeln!(
            self.output_file,
            "unsafe extern \"C\" fn {}_endian(a: *mut {}, to_net: bool) {{",
            message.name(),
            upper_camel_name
        )?;
        writeln!(self.output_file, "    unsafe {{")?;
        writeln!(
            self.output_file,
            "        ::vpp_plugin::vlibapi::EndianSwap::endian_swap(&mut *a, to_net);"
        )?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(
            self.output_file,
            "unsafe extern \"C\" fn {}_format(s: *mut u8, args: *mut ::vpp_plugin::bindings::va_list) -> *mut u8 {{",
            message.name()
        )?;
        writeln!(self.output_file, "    unsafe {{")?;
        writeln!(
            self.output_file,
            "        let mut args = ::std::mem::transmute::<*mut ::vpp_plugin::bindings::va_list, ::vpp_plugin::macro_support::va_list::VaList<'_>>(args);"
        )?;
        writeln!(
            self.output_file,
            "        let t = args.get::<*const {}>();",
            upper_camel_name
        )?;
        writeln!(
            self.output_file,
            "        let mut s = ::vpp_plugin::vppinfra::vec::Vec::from_raw(s);"
        )?;
        writeln!(
            self.output_file,
            "        s.extend(format!(\"{{:?}}\", &*t).as_bytes());"
        )?;
        writeln!(self.output_file, "        s.into_raw()")?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;
        if let Some((field, count_descr)) = message.vla(self.parser) {
            write!(self.output_file, "pub ",)?;
            writeln!(
                self.output_file,
                "unsafe extern \"C\" fn {}_calc_size(a: *mut {}) -> ::vpp_plugin::bindings::uword {{",
                message.name(),
                upper_camel_name
            )?;
            writeln!(self.output_file, "    unsafe {{")?;
            write!(
                self.output_file,
                "        ::std::mem::size_of::<{}>() as ::vpp_plugin::bindings::uword",
                upper_camel_name,
            )?;
            match count_descr {
                CountDescriptor::Field {
                    path: count_path,
                    r#type: count_type,
                } => match count_type.as_str() {
                    "u8" => {
                        writeln!(
                            self.output_file,
                            " + (*a).{} as ::vpp_plugin::bindings::uword * ::std::mem::size_of::<{}>() as ::vpp_plugin::bindings::uword",
                            count_path.join("."),
                            self.parser.to_rust_type(&field.r#type)?,
                        )?;
                    }
                    "u16" | "u32" | "u64" | "i16" | "i32" | "i64" => {
                        writeln!(
                            self.output_file,
                            " + {}::from_be((*a).{}) as ::vpp_plugin::bindings::uword * ::std::mem::size_of::<{}>() as ::vpp_plugin::bindings::uword",
                            self.parser.to_rust_type(&count_type)?,
                            count_path.join("."),
                            self.parser.to_rust_type(&field.r#type)?,
                        )?;
                    }
                    _ => {
                        return Err(Error::Unimplemented(format!(
                            "Unexpected type of variable-length array count field {} in message {}",
                            count_path.join("."),
                            message.name()
                        )));
                    }
                },
                CountDescriptor::String(string_path) => {
                    writeln!(
                        self.output_file,
                        " + u32::from_be((*a).{}.len()) as ::vpp_plugin::bindings::uword",
                        string_path.join("."),
                    )?;
                }
            }
            writeln!(self.output_file, "    }}")?;
        } else {
            writeln!(
                self.output_file,
                "unsafe extern \"C\" fn {}_calc_size(_a: *mut {}) -> ::vpp_plugin::bindings::uword {{",
                message.name(),
                upper_camel_name
            )?;
            writeln!(
                self.output_file,
                "    ::std::mem::size_of::<{}>() as ::vpp_plugin::bindings::uword",
                upper_camel_name
            )?;
        }
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;
        Ok(())
    }

    fn generate_messages(&mut self) -> Result<(), Error> {
        for (id, message) in self.parser.messages().iter().enumerate() {
            self.generate_message(id, message)?;
        }
        Ok(())
    }

    fn generate_alias(&mut self, alias: &Alias) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(&alias.field().name);

        let opt_derives = if alias.manual_print() {
            ""
        } else {
            "Debug, PartialEq, Default, "
        };
        writeln!(self.output_file, "#[derive({}Copy, Clone)]", opt_derives)?;
        writeln!(self.output_file, "#[repr(C, packed)]")?;
        if let Some(FieldSize::Fixed(length)) = alias.field().size {
            writeln!(
                self.output_file,
                "pub struct {}(pub[{}; {}]);",
                upper_camel_name,
                self.parser.to_rust_type(&alias.field().r#type)?,
                length
            )?;
        } else {
            writeln!(
                self.output_file,
                "pub struct {}(pub {});",
                upper_camel_name,
                self.parser.to_rust_type(&alias.field().r#type)?
            )?;
        }
        if !alias.manual_endian() {
            self.generate_endian_swap(&alias.field().name, EndianSwapInput::Alias(alias.field()))?;
        }

        Ok(())
    }

    fn generate_aliases(&mut self) -> Result<(), Error> {
        for message in self.parser.aliases() {
            self.generate_alias(message)?;
        }
        Ok(())
    }

    fn generate_enum(&mut self, e: &Enum) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(&e.name);

        // Since:
        // 1. We don't parse the memory and instead cast the message pointer due to VPP API
        //    restrictions (no length passed to message handler); and
        // 2. In Rust it's UB to construct an instance of an enum that doesn't match one of its
        //    variants;
        // then we cannot use generate an enum type here. Instead, the best that can be done to
        // help with type safety is to use a newtype wrapper around the primitive type.

        writeln!(
            self.output_file,
            "#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]",
        )?;
        writeln!(self.output_file, "#[repr(C, packed)]")?;
        writeln!(
            self.output_file,
            "pub struct {}(pub {});",
            upper_camel_name, &e.size,
        )?;

        writeln!(self.output_file)?;

        for variant in &e.variants {
            writeln!(
                self.output_file,
                "pub const {}: {} = {}({});",
                variant.id, upper_camel_name, upper_camel_name, variant.value,
            )?;
        }
        if !e.variants.is_empty() {
            writeln!(self.output_file)?;
        }

        writeln!(
            self.output_file,
            "impl ::std::fmt::Debug for {} {{",
            upper_camel_name
        )?;
        writeln!(
            self.output_file,
            "    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {{"
        )?;
        writeln!(self.output_file, "        match *self {{")?;
        for variant in &e.variants {
            writeln!(
                self.output_file,
                "            {} => f.write_str(\"{}\"),",
                variant.id, variant.id,
            )?;
        }
        writeln!(self.output_file, "            _ => {{")?;
        writeln!(self.output_file, "                let tmp = self.0;")?;
        writeln!(self.output_file, "                tmp.fmt(f)")?;
        writeln!(self.output_file, "            }}")?;
        writeln!(self.output_file, "        }}")?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(
            self.output_file,
            "impl ::vpp_plugin::vlibapi::EndianSwap for {} {{",
            upper_camel_name
        )?;
        writeln!(
            self.output_file,
            "    unsafe fn endian_swap(&mut self, to_net: bool) {{",
        )?;
        // Suppress potential used variable warning
        writeln!(self.output_file, "        let _ = to_net;",)?;
        match e.size.as_str() {
            "u8" => {
                writeln!(self.output_file, "        // *self = Self(self.0) (no-op)",)?;
            }
            "u16" | "u32" | "u64" | "i16" | "i32" | "i64" => {
                writeln!(self.output_file, "        *self = Self(self.0.to_be());",)?;
            }
            _ => {
                return Err(Error::Unimplemented(format!(
                    "Unexpected size type {} for enum {}",
                    e.size, e.name
                )));
            }
        }
        writeln!(self.output_file, "    }}",)?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        Ok(())
    }

    fn generate_enumflag(&mut self, e: &Enum) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(&e.name);

        writeln!(
            self.output_file,
            "#[derive(Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]",
        )?;
        writeln!(self.output_file, "#[repr(C, packed)]")?;
        writeln!(
            self.output_file,
            "pub struct {}({});",
            upper_camel_name, &e.size,
        )?;
        writeln!(self.output_file)?;
        writeln!(self.output_file, "::vpp_plugin::bitflags::bitflags! {{",)?;
        writeln!(
            self.output_file,
            "    impl {}: {} {{",
            upper_camel_name, &e.size,
        )?;

        let upper_name = format!("{}_", e.name.to_uppercase());
        for variant in &e.variants {
            // For ease of use, strip off the enumflag name being used as part of each defined
            // flag, since this is redundant as the flags are already namespaced by the enumflag
            // type
            let id = variant
                .id
                .strip_prefix(&upper_name)
                .unwrap_or(variant.id.as_str());
            writeln!(
                self.output_file,
                "        const {} = {};",
                id, variant.value,
            )?;
        }
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(
            self.output_file,
            "impl ::std::fmt::Debug for {} {{",
            upper_camel_name
        )?;
        writeln!(
            self.output_file,
            "    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {{"
        )?;
        writeln!(
            self.output_file,
            "        ::vpp_plugin::bitflags::parser::to_writer(self, f)"
        )?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(
            self.output_file,
            "impl ::vpp_plugin::vlibapi::EndianSwap for {} {{",
            upper_camel_name
        )?;
        writeln!(
            self.output_file,
            "    unsafe fn endian_swap(&mut self, to_net: bool) {{",
        )?;
        // Suppress potential used variable warning
        writeln!(self.output_file, "        let _ = to_net;",)?;
        match e.size.as_str() {
            "u8" => {
                writeln!(
                    self.output_file,
                    "        // *self = Self::from_bits_retain(self.bits()) (no-op)",
                )?;
            }
            "u16" | "u32" | "u64" | "i16" | "i32" | "i64" => {
                writeln!(
                    self.output_file,
                    "        *self = Self::from_bits_retain(self.bits().to_be());",
                )?;
            }
            _ => {
                return Err(Error::Unimplemented(format!(
                    "Unexpected size type {} for enum {}",
                    e.size, e.name
                )));
            }
        }
        writeln!(self.output_file, "    }}",)?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        Ok(())
    }

    fn generate_enums(&mut self) -> Result<(), Error> {
        for e in self.parser.enums() {
            self.generate_enum(e)?;
        }
        for e in self.parser.enumflags() {
            self.generate_enumflag(e)?;
        }
        Ok(())
    }

    fn generate_union(&mut self, un: &Union) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(un.name());

        if let Some(comment) = un.comment() {
            writeln!(
                self.output_file,
                "#[doc = \"{}\"]",
                comment.replace("\"", "\\\"")
            )?;
        }
        writeln!(self.output_file, "#[derive(Copy, Clone)]",)?;
        writeln!(self.output_file, "#[repr(C, packed)]")?;
        writeln!(self.output_file, "pub union {} {{", upper_camel_name)?;
        for field in un.fields() {
            self.generate_field(field)?;
        }
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;
        // TODO: enforce manual_endian for unions?

        // Note: no use of variable-length arrays is already enforced by the parser

        Ok(())
    }

    fn generate_unions(&mut self) -> Result<(), Error> {
        for un in self.parser.unions() {
            self.generate_union(un)?;
        }
        Ok(())
    }

    fn generate_endian_swap(&mut self, name: &str, input: EndianSwapInput) -> Result<(), Error> {
        writeln!(
            self.output_file,
            "impl ::vpp_plugin::vlibapi::EndianSwap for {} {{",
            to_upper_camel_case(name)
        )?;
        writeln!(
            self.output_file,
            "    unsafe fn endian_swap(&mut self, to_net: bool) {{",
        )?;
        // Suppress potential used variable warning
        writeln!(self.output_file, "        let _ = to_net;")?;
        // To avoid complicating the code generation further
        writeln!(self.output_file, "        #[allow(unused_unsafe)]")?;
        writeln!(self.output_file, "        unsafe {{")?;
        let fields = match input {
            EndianSwapInput::Fields(fields) => fields,
            EndianSwapInput::Alias(field) => std::slice::from_ref(field),
        };
        for field in fields {
            let field_name = match input {
                EndianSwapInput::Fields(_) => &field.name,
                EndianSwapInput::Alias(_) => "0",
            };

            let mut gen_count_variable = |count_field| {
                let count_field = fields
                    .iter()
                    .find(|field| &field.name == count_field)
                    .ok_or_else(|| {
                        Error::Unimplemented(format!(
                            "Unable to find variable count field {}",
                            count_field
                        ))
                    })?;
                let vla_elem_type = self.parser.to_rust_vla_elem_type(&field.r#type)?;
                writeln!(self.output_file, "            let count = if to_net {{",)?;
                writeln!(
                    self.output_file,
                    "                {}::from_be(self.{})",
                    count_field.r#type, count_field.name,
                )?;
                writeln!(self.output_file, "            }} else {{",)?;
                writeln!(
                    self.output_file,
                    "                self.{}",
                    count_field.name,
                )?;
                writeln!(self.output_file, "            }};",)?;
                writeln!(
                    self.output_file,
                    "            let array = ::std::slice::from_raw_parts_mut(std::ptr::addr_of_mut!(self.{}) as *mut {}, count as usize);",
                    field_name, vla_elem_type,
                )?;
                Ok::<_, Error>(())
            };

            match field.r#type.as_str() {
                "u8" | "bool" => {
                    writeln!(
                        self.output_file,
                        "            // self.{} = self.{} (no-op)",
                        field_name, field_name
                    )?;
                }
                "string" => {
                    writeln!(
                        self.output_file,
                        "            ::vpp_plugin::vlibapi::EndianSwap::endian_swap(&mut self.{}, to_net);",
                        field_name,
                    )?;
                }
                "u16" | "u32" | "u64" | "i16" | "i32" | "i64" => match &field.size {
                    Some(FieldSize::Fixed(size)) => {
                        writeln!(self.output_file, "            for i in 0..{} {{", size)?;
                        writeln!(
                            self.output_file,
                            "                self.{}[i] = self.{}[i].to_be();",
                            field_name, field_name
                        )?;
                        writeln!(self.output_file, "        }}",)?;
                    }
                    Some(FieldSize::Variable(Some(count_field))) => {
                        gen_count_variable(count_field)?;
                        writeln!(self.output_file, "            for elem in array {{")?;
                        writeln!(self.output_file, "                *elem = elem.to_be();",)?;
                        writeln!(self.output_file, "            }}")?;
                    }
                    Some(FieldSize::Variable(None)) => {
                        return Err(Error::Unimplemented(format!(
                            "variable length array field {} without count",
                            field_name
                        )));
                    }
                    None => {
                        writeln!(
                            self.output_file,
                            "            self.{} = self.{}.to_be();",
                            field_name, field.name
                        )?;
                    }
                },
                "f64" => {
                    writeln!(
                        self.output_file,
                        "            // self.{} = self.{} (no-op according to VPP API)",
                        field_name, field_name
                    )?;
                }
                _ => match &field.size {
                    Some(FieldSize::Fixed(size)) => {
                        writeln!(self.output_file, "            for i in 0..{} {{", size)?;
                        writeln!(
                            self.output_file,
                            "                ::vpp_plugin::vlibapi::EndianSwap::endian_swap(&mut self.{}[i], to_net);",
                            field_name
                        )?;
                        writeln!(self.output_file, "            }}",)?;
                    }
                    Some(FieldSize::Variable(Some(count_field))) => {
                        gen_count_variable(count_field)?;
                        writeln!(self.output_file, "            for elem in array {{")?;
                        writeln!(
                            self.output_file,
                            "                ::vpp_plugin::vlibapi::EndianSwap::endian_swap(elem, to_net);",
                        )?;
                        writeln!(self.output_file, "            }}",)?;
                    }
                    Some(FieldSize::Variable(None)) => {
                        return Err(Error::Unimplemented(format!(
                            "variable length array field {} without count",
                            field_name
                        )));
                    }
                    None => {
                        // Copy out the value to a temporary since the structs are packed and so it
                        // may not be properly aligned
                        writeln!(
                            self.output_file,
                            "            ::vpp_plugin::vlibapi::EndianSwap::endian_swap(&mut self.{}, to_net);",
                            field_name,
                        )?;
                    }
                },
            }
        }
        writeln!(self.output_file, "        }}",)?;
        writeln!(self.output_file, "    }}",)?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        Ok(())
    }

    fn generate_type(&mut self, t: &Type) -> Result<(), Error> {
        let upper_camel_name = to_upper_camel_case(t.name());

        let opt_derives = if t.manual_print() {
            ""
        } else if t.vla_non_recursive().is_some() {
            "Default, "
        } else {
            "Debug, PartialEq, Default, "
        };
        writeln!(self.output_file, "#[derive({}Copy, Clone)]", opt_derives)?;
        writeln!(self.output_file, "#[repr(C, packed)]")?;
        writeln!(self.output_file, "pub struct {} {{", upper_camel_name)?;
        for field in t.fields() {
            self.generate_field(field)?;
        }
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        if let Some((field, _)) = t.vla(self.parser)
            && let Some(FieldSize::Variable(Some(count_field))) = &field.size
        {
            writeln!(self.output_file, "impl {} {{", upper_camel_name)?;
            self.generate_vla_accessors(count_field, field)?;
            writeln!(self.output_file, "}}")?;
            writeln!(self.output_file)?;
        }

        // Manually implement fmt::Debug so that the zero-length (but actually variable-length)
        // field isn't printed to avoid misleading anyone looking at the output
        if t.vla_non_recursive().is_some() {
            self.generate_debug_trait(t.name(), t.fields())?;
        }

        if !t.manual_endian() {
            self.generate_endian_swap(t.name(), EndianSwapInput::Fields(t.fields()))?;
        }
        Ok(())
    }

    fn generate_types(&mut self) -> Result<(), Error> {
        for t in self.parser.types() {
            self.generate_type(t)?;
        }
        Ok(())
    }

    fn generate_register(&mut self) -> Result<(), Error> {
        // Avoid generating empty, unused traits/functions
        if self.parser.services().is_empty() {
            return Ok(());
        }

        writeln!(self.output_file, "pub trait Handlers {{")?;
        for service in self.parser.services() {
            let caller_upper_camel = to_upper_camel_case(service.caller());
            let caller_message = self.parser.message(service.caller());
            let reply_message = if service.reply() == "null" {
                None
            } else {
                self.parser.message(service.reply())
            };
            let caller_message_vla = caller_message
                .map(|message| message.vla(self.parser).is_some())
                .unwrap_or(false);
            let reply_message_vla = reply_message
                .map(|message| message.vla(self.parser).is_some())
                .unwrap_or(false);
            // If the caller message is a VLA, then it's the callers of the trait have a responsibility to ensure the memory for any VLA VLA is valid, consistent with the count field.
            // If the reply message is a VLA, then it's the trait implementation's responsibility to ensure the memory for any VLA in the reply is valid, consistent with the count field.
            let unsafe_str = if caller_message_vla || reply_message_vla {
                "unsafe "
            } else {
                ""
            };
            if service.reply() == "null" {
                writeln!(
                    self.output_file,
                    "    {}fn {}(vm: &::vpp_plugin::vlib::BarrierHeldMainRef, mp: &{});",
                    unsafe_str,
                    service.caller(),
                    caller_upper_camel
                )?;
            } else {
                let reply_message = format!(
                    "::vpp_plugin::vlibapi::Message<{}>",
                    to_upper_camel_case(service.reply())
                );
                let retval_in_reply_msg = self
                    .parser
                    .message(service.reply())
                    .map(|reply| reply.has_retval())
                    .unwrap_or_default();
                if let Some(stream_message) = service.stream_message() {
                    let stream_message = format!(
                        "::vpp_plugin::vlibapi::Stream<{}>",
                        to_upper_camel_case(stream_message),
                    );
                    if retval_in_reply_msg {
                        writeln!(
                            self.output_file,
                            "    {}fn {}(vm: &::vpp_plugin::vlib::BarrierHeldMainRef, mp: &{}, stream: {}) -> Result<{}, i32>;",
                            unsafe_str,
                            service.caller(),
                            caller_upper_camel,
                            stream_message,
                            reply_message
                        )?;
                    } else {
                        writeln!(
                            self.output_file,
                            "    {}fn {}(vm: &::vpp_plugin::vlib::BarrierHeldMainRef, mp: &{}, stream: {}) -> {};",
                            unsafe_str,
                            service.caller(),
                            caller_upper_camel,
                            stream_message,
                            reply_message
                        )?;
                    }
                } else if service.stream() {
                    writeln!(
                        self.output_file,
                        "    {}fn {}(vm: &::vpp_plugin::vlib::BarrierHeldMainRef, mp: &{}, stream: ::vpp_plugin::vlibapi::Stream<{}>);",
                        unsafe_str,
                        service.caller(),
                        caller_upper_camel,
                        to_upper_camel_case(service.reply()),
                    )?;
                } else if retval_in_reply_msg {
                    writeln!(
                        self.output_file,
                        "    {}fn {}(vm: &::vpp_plugin::vlib::BarrierHeldMainRef, mp: &{}) -> Result<{}, i32>;",
                        unsafe_str,
                        service.caller(),
                        caller_upper_camel,
                        reply_message
                    )?;
                } else {
                    writeln!(
                        self.output_file,
                        "    {}fn {}(vm: &::vpp_plugin::vlib::BarrierHeldMainRef, mp: &{}) -> {};",
                        unsafe_str,
                        service.caller(),
                        caller_upper_camel,
                        reply_message
                    )?;
                }
            }
        }
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        for service in self.parser.services() {
            let caller_upper_camel = to_upper_camel_case(service.caller());
            writeln!(
                self.output_file,
                "unsafe extern \"C\" fn {}_handler_raw<H: Handlers>(mp: *mut {}) {{",
                service.caller(),
                caller_upper_camel
            )?;
            writeln!(self.output_file, "    unsafe {{")?;
            writeln!(
                self.output_file,
                "        let vm = ::vpp_plugin::vlib::BarrierHeldMainRef::from_ptr_mut("
            )?;
            writeln!(
                self.output_file,
                "            ::vpp_plugin::bindings::vlib_get_main_not_inline(),"
            )?;
            writeln!(self.output_file, "        );")?;
            writeln!(self.output_file, "        let mp = &*mp;")?;
            if service.reply() == "null" {
                writeln!(self.output_file, "        H::{}(vm, mp);", service.caller())?;
            } else {
                writeln!(
                    self.output_file,
                    "        ::vpp_plugin::vlibapi::registration_scope(|s| {{"
                )?;
                // TODO: check for client_index field in caller
                // TODO: check for context field in caller and reply
                writeln!(
                    self.output_file,
                    "            if let Some(reg) = s.from_client_index(vm, mp.client_index) {{"
                )?;
                let retval_in_reply_msg = self
                    .parser
                    .message(service.reply())
                    .map(|reply| reply.has_retval())
                    .unwrap_or_default();
                let stream_message_arg = if service.stream_message().is_some() {
                    ", ::vpp_plugin::vlibapi::Stream::new(reg)"
                } else {
                    ""
                };
                if service.stream() && service.stream_message().is_none() {
                    writeln!(
                        self.output_file,
                        "                H::{}(vm, mp, ::vpp_plugin::vlibapi::Stream::new(reg));",
                        service.caller()
                    )?;
                } else if retval_in_reply_msg {
                    writeln!(
                        self.output_file,
                        "                let mut reply = match H::{}(vm, mp{}) {{",
                        service.caller(),
                        stream_message_arg,
                    )?;
                    writeln!(self.output_file, "                    Ok(reply) => reply,")?;
                    writeln!(
                        self.output_file,
                        "                    Err(retval) => {} {{",
                        to_upper_camel_case(service.reply())
                    )?;
                    writeln!(self.output_file, "                        retval,")?;
                    writeln!(
                        self.output_file,
                        "                        ..Default::default()"
                    )?;
                    writeln!(self.output_file, "                    }}")?;
                    writeln!(self.output_file, "                    .into(),")?;
                    writeln!(self.output_file, "                }};")?;
                } else {
                    writeln!(
                        self.output_file,
                        "                let mut reply = H::{}(vm, mp{});",
                        service.caller(),
                        stream_message_arg,
                    )?;
                }
                if !service.stream() || service.stream_message().is_some() {
                    writeln!(
                        self.output_file,
                        "                reply.context = mp.context;",
                    )?;
                    writeln!(
                        self.output_file,
                        "                {}_endian(::std::ptr::addr_of_mut!(*reply), true);",
                        service.reply()
                    )?;
                    writeln!(self.output_file, "                reg.send_message(reply);")?;
                }
                writeln!(self.output_file, "            }}")?;
                writeln!(self.output_file, "        }})")?;
                writeln!(self.output_file, "    }}")?;
            }
            writeln!(self.output_file, "}}")?;
            writeln!(self.output_file)?;
        }

        writeln!(
            self.output_file,
            "pub const MESSAGE_COUNT: u16 = {};",
            self.parser.messages().len()
        )?;
        writeln!(self.output_file)?;

        writeln!(
            self.output_file,
            "static MSG_ID_BASE: ::std::sync::atomic::AtomicU16 = ::std::sync::atomic::AtomicU16::new(0);"
        )?;
        writeln!(self.output_file)?;
        writeln!(self.output_file, "pub fn msg_id_base() -> u16 {{")?;
        writeln!(
            self.output_file,
            "    MSG_ID_BASE.load(::std::sync::atomic::Ordering::Relaxed)"
        )?;
        writeln!(self.output_file, "}}")?;
        writeln!(self.output_file)?;

        writeln!(
            self.output_file,
            "pub fn {}_register_messages<H: Handlers>() {{",
            self.module
        )?;
        writeln!(self.output_file, "    unsafe {{")?;
        writeln!(
            self.output_file,
            "        let am = ::vpp_plugin::bindings::vlibapi_helper_get_main();"
        )?;
        writeln!(
            self.output_file,
            "        let mut json_api_repr = ::vpp_plugin::vppinfra::vec::Vec::from_raw((*am).json_api_repr);"
        )?;
        writeln!(self.output_file, "        json_api_repr.push(",)?;
        writeln!(
            self.output_file,
            "            concat!(include_str!(\"{}.api.json\"), \"\\0\")",
            self.module
        )?;
        writeln!(self.output_file, "                .as_ptr()",)?;
        writeln!(self.output_file, "                .cast_mut(),",)?;
        writeln!(self.output_file, "        );",)?;
        writeln!(
            self.output_file,
            "        (*am).json_api_repr = json_api_repr.into_raw();"
        )?;
        writeln!(self.output_file)?;
        writeln!(
            self.output_file,
            "        let msg_id_base = ::vpp_plugin::bindings::vl_msg_api_get_msg_ids(",
        )?;
        writeln!(
            self.output_file,
            "            c\"{}_{:08x}\".as_ptr() as *mut ::std::os::raw::c_char,",
            self.module,
            self.parser.file_crc()
        )?;
        writeln!(self.output_file, "            MESSAGE_COUNT as i32,",)?;
        writeln!(self.output_file, "        );",)?;
        writeln!(self.output_file)?;
        for message in self.parser.messages() {
            writeln!(
                self.output_file,
                "        ::vpp_plugin::bindings::vl_msg_api_add_msg_name_crc("
            )?;
            writeln!(self.output_file, "            am,")?;
            writeln!(
                self.output_file,
                "            c\"{}_{:08x}\".as_ptr() as *mut ::std::os::raw::c_char,",
                message.name(),
                message.crc()
            )?;
            writeln!(
                self.output_file,
                "            {}::MSG_ID as u32 + msg_id_base as u32,",
                to_upper_camel_case(message.name()),
            )?;
            writeln!(self.output_file, "        );")?;
            writeln!(self.output_file)?;
        }
        for service in self.parser.services() {
            let caller = self.parser.message(service.caller()).unwrap();
            let caller_upper_camel = to_upper_camel_case(service.caller());
            writeln!(
                self.output_file,
                "        let mut c = vpp_plugin::bindings::vl_msg_api_msg_config_t {{"
            )?;
            writeln!(
                self.output_file,
                "            id: {}::MSG_ID as i32 + msg_id_base as i32,",
                caller_upper_camel,
            )?;
            writeln!(
                self.output_file,
                "            name: c\"{}\".as_ptr() as *mut ::std::os::raw::c_char,",
                service.caller()
            )?;
            writeln!(
                self.output_file,
                "            handler: {}_handler_raw::<H> as *mut ::std::os::raw::c_void,",
                service.caller()
            )?;
            writeln!(
                self.output_file,
                "            endian: {}_endian as *mut ::std::os::raw::c_void,",
                service.caller()
            )?;
            writeln!(
                self.output_file,
                "            format_fn: {}_format as *mut ::std::os::raw::c_void,",
                service.caller()
            )?;
            writeln!(
                self.output_file,
                "            tojson: std::ptr::null_mut(),"
            )?;
            writeln!(
                self.output_file,
                "            fromjson: std::ptr::null_mut(),"
            )?;
            writeln!(
                self.output_file,
                "            calc_size: {}_calc_size as *mut ::std::os::raw::c_void,",
                service.caller()
            )?;
            writeln!(self.output_file, "            ..Default::default()")?;
            writeln!(self.output_file, "        }};")?;
            writeln!(self.output_file, "        c.set_traced(1);")?;
            writeln!(self.output_file, "        c.set_replay(1);")?;
            // TODO: enforce always auto-endian?
            if caller.auto_endian() {
                writeln!(self.output_file, "        c.set_is_autoendian(1);")?;
            }
            writeln!(
                self.output_file,
                "        ::vpp_plugin::bindings::vl_msg_api_config(std::ptr::addr_of_mut!(c));"
            )?;
            writeln!(self.output_file)?;

            if service.reply() != "null" {
                let reply = self.parser.message(service.reply()).unwrap();
                let reply_upper_camel = to_upper_camel_case(service.reply());
                writeln!(
                    self.output_file,
                    "        let mut c = vpp_plugin::bindings::vl_msg_api_msg_config_t {{"
                )?;
                writeln!(
                    self.output_file,
                    "            id: {}::MSG_ID as i32 + msg_id_base as i32,",
                    reply_upper_camel
                )?;
                writeln!(
                    self.output_file,
                    "            name: c\"{}\".as_ptr() as *mut ::std::os::raw::c_char,",
                    service.reply()
                )?;
                writeln!(
                    self.output_file,
                    "            handler: ::std::ptr::null_mut(),"
                )?;
                writeln!(
                    self.output_file,
                    "            endian: {}_endian as *mut ::std::os::raw::c_void,",
                    service.reply()
                )?;
                writeln!(
                    self.output_file,
                    "            format_fn: {}_format as *mut ::std::os::raw::c_void,",
                    service.reply()
                )?;
                writeln!(
                    self.output_file,
                    "            tojson: std::ptr::null_mut(),"
                )?;
                writeln!(
                    self.output_file,
                    "            fromjson: std::ptr::null_mut(),"
                )?;
                writeln!(
                    self.output_file,
                    "            calc_size: {}_calc_size as *mut ::std::os::raw::c_void,",
                    service.reply()
                )?;
                writeln!(self.output_file, "            ..Default::default()")?;
                writeln!(self.output_file, "        }};")?;
                writeln!(self.output_file, "        c.set_traced(1);")?;
                writeln!(self.output_file, "        c.set_replay(1);")?;
                // TODO: enforce always auto-endian?
                if reply.auto_endian() {
                    writeln!(self.output_file, "        c.set_is_autoendian(1);")?;
                }
                writeln!(
                    self.output_file,
                    "        ::vpp_plugin::bindings::vl_msg_api_config(std::ptr::addr_of_mut!(c));"
                )?;
                writeln!(self.output_file)?;
            }

            if let Some(stream_message_name) = service.stream_message() {
                let stream_message = self.parser.message(stream_message_name).unwrap();
                let stream_message_upper_camel = to_upper_camel_case(stream_message_name);
                writeln!(
                    self.output_file,
                    "        let mut c = vpp_plugin::bindings::vl_msg_api_msg_config_t {{"
                )?;
                writeln!(
                    self.output_file,
                    "            id: {}::MSG_ID as i32 + msg_id_base as i32,",
                    stream_message_upper_camel
                )?;
                writeln!(
                    self.output_file,
                    "            name: c\"{}\".as_ptr() as *mut ::std::os::raw::c_char,",
                    stream_message_name
                )?;
                writeln!(
                    self.output_file,
                    "            handler: ::std::ptr::null_mut(),"
                )?;
                writeln!(
                    self.output_file,
                    "            endian: {}_endian as *mut ::std::os::raw::c_void,",
                    stream_message_name
                )?;
                writeln!(
                    self.output_file,
                    "            format_fn: {}_format as *mut ::std::os::raw::c_void,",
                    stream_message_name
                )?;
                writeln!(
                    self.output_file,
                    "            tojson: std::ptr::null_mut(),"
                )?;
                writeln!(
                    self.output_file,
                    "            fromjson: std::ptr::null_mut(),"
                )?;
                writeln!(
                    self.output_file,
                    "            calc_size: {}_calc_size as *mut ::std::os::raw::c_void,",
                    stream_message_name
                )?;
                writeln!(self.output_file, "            ..Default::default()")?;
                writeln!(self.output_file, "        }};")?;
                writeln!(self.output_file, "        c.set_traced(1);")?;
                writeln!(self.output_file, "        c.set_replay(1);")?;
                // TODO: enforce always auto-endian?
                if stream_message.auto_endian() {
                    writeln!(self.output_file, "        c.set_is_autoendian(1);")?;
                }
                writeln!(
                    self.output_file,
                    "        ::vpp_plugin::bindings::vl_msg_api_config(std::ptr::addr_of_mut!(c));"
                )?;
                writeln!(self.output_file)?;
            }
        }

        writeln!(
            self.output_file,
            "        MSG_ID_BASE.store(msg_id_base, ::std::sync::atomic::Ordering::Relaxed);"
        )?;
        writeln!(self.output_file, "    }}")?;
        writeln!(self.output_file, "}}")?;

        Ok(())
    }

    fn generate(mut self) -> Result<(), Error> {
        self.output_json_file
            .write_all(generate_json(self.parser)?.as_bytes())?;
        self.generate_aliases()?;
        self.generate_enums()?;
        self.generate_unions()?;
        self.generate_types()?;
        self.generate_messages()?;
        self.generate_register()?;
        Ok(())
    }
}