buffa-codegen 0.3.0

Shared code generation logic for buffa (descriptor → Rust source)
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
//! Proto3 codegen: WKT auto-mapping, enums, TYPE_URL, message fields, repeated.

use super::*;

#[test]
fn test_wkt_auto_mapping_not_suppressed_by_sub_package() {
    // Regression: mapping .google.protobuf.compiler (a SUB-package) used
    // to suppress the WKT auto-mapping for .google.protobuf, breaking
    // Timestamp/Duration/etc. resolve_extern_prefix's longest-prefix
    // matching handles both coexisting correctly.
    let config = CodeGenConfig {
        extern_paths: vec![(
            ".google.protobuf.compiler".into(),
            "::compiler_protos".into(),
        )],
        ..Default::default()
    };
    let effective = effective_extern_paths(&[], &[], &config);
    // The sub-package mapping is preserved...
    assert!(effective
        .iter()
        .any(|(p, _)| p == ".google.protobuf.compiler"));
    // ...AND the WKT auto-mapping is still injected.
    assert!(
        effective.iter().any(|(p, _)| p == ".google.protobuf"),
        "WKT auto-mapping must coexist with sub-package extern_path"
    );
}

#[test]
fn test_wkt_auto_mapping_suppressed_by_exact_match() {
    let config = CodeGenConfig {
        extern_paths: vec![(".google.protobuf".into(), "::my_wkts".into())],
        ..Default::default()
    };
    let effective = effective_extern_paths(&[], &[], &config);
    // Exactly one .google.protobuf mapping (user's), not two.
    let count = effective
        .iter()
        .filter(|(p, _)| p == ".google.protobuf")
        .count();
    assert_eq!(count, 1);
    // It's the user's, not the auto-injection.
    assert!(effective
        .iter()
        .any(|(p, r)| p == ".google.protobuf" && r == "::my_wkts"));
}

#[test]
fn test_empty_file() {
    let file = proto3_file("empty.proto");
    let result = generate(
        &[file],
        &["empty.proto".to_string()],
        &CodeGenConfig::default(),
    );
    let files = result.expect("empty file should generate without error");
    assert_eq!(files.len(), 1);
    assert_eq!(files[0].name, "empty.rs");
    assert!(
        files[0].content.contains("@generated by protoc-gen-buffa"),
        "missing header comment"
    );
}

#[test]
fn test_proto_path_to_rust_module() {
    assert_eq!(
        proto_path_to_rust_module("google/protobuf/timestamp.proto"),
        "google.protobuf.timestamp.rs"
    );
    assert_eq!(proto_path_to_rust_module("foo.proto"), "foo.rs");
    assert_eq!(proto_path_to_rust_module("no_extension"), "no_extension.rs");
}

#[test]
fn test_simple_enum() {
    let mut file = proto3_file("status.proto");
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Status".to_string()),
        value: vec![
            enum_value("UNKNOWN", 0),
            enum_value("ACTIVE", 1),
            enum_value("INACTIVE", 2),
        ],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["status.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("simple enum should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub enum Status"),
        "missing enum: {content}"
    );
    assert!(
        content.contains("UNKNOWN = 0"),
        "missing UNKNOWN: {content}"
    );
    assert!(content.contains("ACTIVE = 1"), "missing ACTIVE: {content}");
    assert!(
        content.contains("INACTIVE = 2"),
        "missing INACTIVE: {content}"
    );
    assert!(
        content.contains("impl ::buffa::Enumeration for Status"),
        "missing Enumeration impl: {content}"
    );
    assert!(
        content.contains("impl ::core::default::Default for Status"),
        "missing Default impl: {content}"
    );
}

#[test]
fn test_enum_with_alias() {
    let mut file = proto3_file("code.proto");
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Code".to_string()),
        value: vec![
            enum_value("OK", 0),
            enum_value("SUCCESS", 0), // alias for OK
            enum_value("ERROR", 1),
        ],
        options: (crate::generated::descriptor::EnumOptions {
            allow_alias: Some(true),
            ..Default::default()
        })
        .into(),
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["code.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("aliased enum should generate");
    let content = &files[0].content;
    // OK is a primary variant; SUCCESS is a const alias.
    assert!(content.contains("OK = 0"), "missing primary: {content}");
    assert!(
        content.contains("pub const SUCCESS"),
        "alias not emitted as const: {content}"
    );
    assert!(
        !content.contains("SUCCESS = 0"),
        "alias must not be a variant: {content}"
    );
}

#[test]
fn test_file_not_found_error() {
    let file = proto3_file("other.proto");
    let result = generate(
        &[file],
        &["missing.proto".to_string()],
        &CodeGenConfig::default(),
    );
    assert!(
        matches!(result, Err(CodeGenError::FileNotFound(_))),
        "expected FileNotFound error"
    );
}

#[test]
fn test_type_url_top_level_with_package() {
    let mut file = proto3_file("person.proto");
    file.package = Some("my.company".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Person".to_string()),
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["person.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &files[0].content;
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/my.company.Person""#),
        "wrong or missing TYPE_URL: {content}"
    );
}

#[test]
fn test_type_url_top_level_no_package() {
    let mut file = proto3_file("root.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Root".to_string()),
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["root.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &files[0].content;
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/Root""#),
        "wrong or missing TYPE_URL for no-package message: {content}"
    );
}

#[test]
fn test_type_url_nested_message() {
    let mut file = proto3_file("nested_type_url.proto");
    file.package = Some("acme".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Outer".to_string()),
        nested_type: vec![DescriptorProto {
            name: Some("Inner".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["nested_type_url.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &files[0].content;
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/acme.Outer""#),
        "wrong Outer TYPE_URL: {content}"
    );
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/acme.Outer.Inner""#),
        "wrong Inner TYPE_URL: {content}"
    );
}

#[test]
fn test_type_url_nested_no_package() {
    // Empty package + nested message: FQN should be "Outer.Inner", no leading dot.
    let mut file = proto3_file("nested_nopackage.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Outer".to_string()),
        nested_type: vec![DescriptorProto {
            name: Some("Inner".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["nested_nopackage.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &files[0].content;
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/Outer""#),
        "wrong Outer TYPE_URL: {content}"
    );
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/Outer.Inner""#),
        "wrong Inner TYPE_URL (no package): {content}"
    );
}

#[test]
fn test_type_url_doubly_nested() {
    // Three levels: pkg.Outer.Middle.Inner — verifies recursive FQN propagation.
    let mut file = proto3_file("doubly_nested.proto");
    file.package = Some("pkg".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Outer".to_string()),
        nested_type: vec![DescriptorProto {
            name: Some("Middle".to_string()),
            nested_type: vec![DescriptorProto {
                name: Some("Inner".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["doubly_nested.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("should generate");
    let content = &files[0].content;
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/pkg.Outer""#),
        "wrong Outer TYPE_URL: {content}"
    );
    assert!(
        content.contains(r#"TYPE_URL: &'static str = "type.googleapis.com/pkg.Outer.Middle""#),
        "wrong Middle TYPE_URL: {content}"
    );
    assert!(
        content
            .contains(r#"TYPE_URL: &'static str = "type.googleapis.com/pkg.Outer.Middle.Inner""#),
        "wrong Inner TYPE_URL: {content}"
    );
}

#[test]
fn test_message_scalar_fields() {
    let mut file = proto3_file("scalars.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Scalars".to_string()),
        field: vec![
            make_field("count", 1, Label::LABEL_OPTIONAL, Type::TYPE_INT32),
            make_field("active", 2, Label::LABEL_OPTIONAL, Type::TYPE_BOOL),
            make_field("score", 3, Label::LABEL_OPTIONAL, Type::TYPE_DOUBLE),
        ],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["scalars.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("scalar fields message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub struct Scalars"),
        "missing struct: {content}"
    );
    assert!(
        content.contains("pub count: i32"),
        "missing count field: {content}"
    );
    assert!(
        content.contains("pub active: bool"),
        "missing active field: {content}"
    );
    assert!(
        content.contains("pub score: f64"),
        "missing score field: {content}"
    );
    assert!(
        content.contains("unsafe impl ::buffa::DefaultInstance for Scalars"),
        "missing DefaultInstance impl: {content}"
    );
    assert!(
        content.contains("impl ::buffa::Message for Scalars"),
        "missing Message impl: {content}"
    );
    assert!(
        content.contains("fn compute_size"),
        "missing compute_size: {content}"
    );
    assert!(
        content.contains("fn merge_field"),
        "missing merge_field: {content}"
    );
}

#[test]
fn test_message_nested_message_field() {
    let mut file = proto3_file("nested.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Inner".to_string()),
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("Outer".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("inner".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_OPTIONAL),
            r#type: Some(Type::TYPE_MESSAGE),
            type_name: Some(".Inner".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["nested.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("nested message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub struct Outer"),
        "missing Outer: {content}"
    );
    assert!(
        content.contains("pub inner: ::buffa::MessageField<Inner>"),
        "missing MessageField: {content}"
    );
    // impl Message should use the two-pass size computation for sub-messages.
    assert!(
        content.contains("compute_size"),
        "missing compute_size call for sub-message: {content}"
    );
    assert!(
        content.contains("merge_length_delimited"),
        "missing merge_length_delimited for sub-message: {content}"
    );
    assert!(
        content.contains("get_or_insert_default"),
        "missing get_or_insert_default in merge: {content}"
    );
}

#[test]
fn test_message_map_field() {
    let mut file = proto3_file("withmap.proto");
    // Synthetic map entry: key=string, value=int32
    let map_entry = DescriptorProto {
        name: Some("AttrsEntry".to_string()),
        field: vec![
            make_field("key", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
            make_field("value", 2, Label::LABEL_OPTIONAL, Type::TYPE_INT32),
        ],
        options: (MessageOptions {
            map_entry: Some(true),
            ..Default::default()
        })
        .into(),
        ..Default::default()
    };
    file.message_type.push(DescriptorProto {
        name: Some("WithMap".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("attrs".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_REPEATED),
            r#type: Some(Type::TYPE_MESSAGE),
            type_name: Some(".WithMap.AttrsEntry".to_string()),
            ..Default::default()
        }],
        nested_type: vec![map_entry],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["withmap.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("map field message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub struct WithMap"),
        "missing struct: {content}"
    );
    assert!(
        content.contains("pub attrs:"),
        "missing attrs field: {content}"
    );
    assert!(
        content.contains("::buffa::__private::HashMap"),
        "map field must use ::buffa::__private::HashMap, got: {content}"
    );
}

#[test]
fn test_message_oneof() {
    let mut file = proto3_file("oneof.proto");
    file.message_type.push(DescriptorProto {
        name: Some("WithOneof".to_string()),
        field: vec![
            FieldDescriptorProto {
                name: Some("count".to_string()),
                number: Some(1),
                label: Some(Label::LABEL_OPTIONAL),
                r#type: Some(Type::TYPE_INT32),
                oneof_index: Some(0),
                ..Default::default()
            },
            FieldDescriptorProto {
                name: Some("name".to_string()),
                number: Some(2),
                label: Some(Label::LABEL_OPTIONAL),
                r#type: Some(Type::TYPE_STRING),
                oneof_index: Some(0),
                ..Default::default()
            },
        ],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("kind".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["oneof.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("oneof message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub struct WithOneof"),
        "missing struct: {content}"
    );
    assert!(
        content.contains("pub kind:"),
        "missing oneof field: {content}"
    );
    assert!(
        content.contains("pub mod with_oneof"),
        "missing message module: {content}"
    );
    assert!(
        content.contains("pub enum Kind"),
        "missing oneof enum: {content}"
    );
    assert!(
        content.contains("Count(i32)"),
        "missing Count variant: {content}"
    );
    assert!(
        content.contains("impl ::buffa::Oneof for Kind"),
        "missing Oneof impl: {content}"
    );
}

#[test]
fn test_message_proto3_optional() {
    let mut file = proto3_file("proto3opt.proto");
    // Proto3 optional fields are assigned to a synthetic oneof.
    file.message_type.push(DescriptorProto {
        name: Some("WithOptional".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("count".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_OPTIONAL),
            r#type: Some(Type::TYPE_INT32),
            oneof_index: Some(0),
            proto3_optional: Some(true),
            ..Default::default()
        }],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("_count".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["proto3opt.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("proto3 optional message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub struct WithOptional"),
        "missing struct: {content}"
    );
    assert!(
        content.contains("pub count: Option<i32>"),
        "missing optional field: {content}"
    );
    // impl Message should use if-let pattern for optional
    assert!(
        content.contains("if let Some"),
        "missing if-let in impl: {content}"
    );
    assert!(
        content.contains("Option::Some"),
        "missing Some assignment in merge: {content}"
    );
}

#[test]
fn test_message_proto3_optional_string() {
    let mut file = proto3_file("optstr.proto");
    file.message_type.push(DescriptorProto {
        name: Some("WithOptStr".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("label".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_OPTIONAL),
            r#type: Some(Type::TYPE_STRING),
            oneof_index: Some(0),
            proto3_optional: Some(true),
            ..Default::default()
        }],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("_label".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["optstr.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("proto3 optional string should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub label: Option<::buffa::alloc::string::String>"),
        "missing optional string field: {content}"
    );
    assert!(
        content.contains("encode_string"),
        "missing encode_string in write_to: {content}"
    );
    assert!(
        content.contains("merge_string"),
        "missing merge_string in merge: {content}"
    );
}

#[test]
fn test_message_proto3_optional_enum() {
    let mut file = proto3_file("optenu.proto");
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Color".to_string()),
        value: vec![enum_value("RED", 0), enum_value("BLUE", 1)],
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("WithOptEnum".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("color".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_OPTIONAL),
            r#type: Some(Type::TYPE_ENUM),
            type_name: Some(".Color".to_string()),
            oneof_index: Some(0),
            proto3_optional: Some(true),
            ..Default::default()
        }],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("_color".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["optenu.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("proto3 optional enum should generate");
    let content = &files[0].content;
    // Enum optional must resolve to EnumValue<Color>, not ()
    assert!(
        content.contains("Option<::buffa::EnumValue<Color>>"),
        "wrong type for optional enum: {content}"
    );
    assert!(
        content.contains("EnumValue::from"),
        "missing EnumValue::from in merge: {content}"
    );
}

#[test]
fn test_message_proto3_optional_bytes_and_bool() {
    let mut file = proto3_file("optmisc.proto");
    file.message_type.push(DescriptorProto {
        name: Some("WithOptMisc".to_string()),
        field: vec![
            FieldDescriptorProto {
                name: Some("data".to_string()),
                number: Some(1),
                label: Some(Label::LABEL_OPTIONAL),
                r#type: Some(Type::TYPE_BYTES),
                oneof_index: Some(0),
                proto3_optional: Some(true),
                ..Default::default()
            },
            FieldDescriptorProto {
                name: Some("flag".to_string()),
                number: Some(2),
                label: Some(Label::LABEL_OPTIONAL),
                r#type: Some(Type::TYPE_BOOL),
                oneof_index: Some(1),
                proto3_optional: Some(true),
                ..Default::default()
            },
        ],
        oneof_decl: vec![
            OneofDescriptorProto {
                name: Some("_data".to_string()),
                ..Default::default()
            },
            OneofDescriptorProto {
                name: Some("_flag".to_string()),
                ..Default::default()
            },
        ],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["optmisc.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("proto3 optional bytes/bool should generate");
    let content = &files[0].content;
    assert!(
        content.contains("Option<::buffa::alloc::vec::Vec<u8>>"),
        "missing optional bytes field: {content}"
    );
    assert!(
        content.contains("Option<bool>"),
        "missing optional bool field: {content}"
    );
    // Bool is fixed-size: compute_size should use is_some(), not if-let
    assert!(
        content.contains("is_some()"),
        "fixed-size optional should use is_some(): {content}"
    );
    // Bytes uses encode_bytes
    assert!(
        content.contains("encode_bytes"),
        "missing encode_bytes for optional bytes: {content}"
    );
}

#[test]
fn test_message_string_and_bytes_fields() {
    let mut file = proto3_file("strings.proto");
    file.message_type.push(DescriptorProto {
        name: Some("WithStrings".to_string()),
        field: vec![
            make_field("name", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
            make_field("data", 2, Label::LABEL_OPTIONAL, Type::TYPE_BYTES),
        ],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["strings.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("string/bytes message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub name: ::buffa::alloc::string::String"),
        "missing string field: {content}"
    );
    assert!(
        content.contains("pub data: ::buffa::alloc::vec::Vec<u8>"),
        "missing bytes field: {content}"
    );
    // impl Message should encode/decode these fields
    assert!(
        content.contains("encode_string"),
        "missing encode_string: {content}"
    );
    assert!(
        content.contains("merge_string"),
        "missing merge_string: {content}"
    );
    assert!(
        content.contains("string_encoded_len"),
        "missing string_encoded_len: {content}"
    );
    assert!(
        content.contains("encode_bytes"),
        "missing encode_bytes: {content}"
    );
    assert!(
        content.contains("merge_bytes"),
        "missing merge_bytes: {content}"
    );
    assert!(
        content.contains("bytes_encoded_len"),
        "missing bytes_encoded_len: {content}"
    );
}

#[test]
fn test_message_enum_field() {
    let mut file = proto3_file("enumfield.proto");
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Status".to_string()),
        value: vec![enum_value("UNKNOWN", 0), enum_value("ACTIVE", 1)],
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("WithEnum".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("status".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_OPTIONAL),
            r#type: Some(Type::TYPE_ENUM),
            type_name: Some(".Status".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["enumfield.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("enum field message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub status: ::buffa::EnumValue<Status>"),
        "missing enum field: {content}"
    );
    // impl Message should encode via to_i32() and decode via EnumValue::from
    assert!(
        content.contains("to_i32()"),
        "missing to_i32 in generated code: {content}"
    );
    assert!(
        content.contains("int32_encoded_len"),
        "missing int32_encoded_len in compute_size: {content}"
    );
    assert!(
        content.contains("EnumValue::from"),
        "missing EnumValue::from in generated code: {content}"
    );
}

#[test]
fn test_repeated_packed_scalar() {
    let mut file = proto3_file("repeatedscalar.proto");
    file.message_type.push(DescriptorProto {
        name: Some("WithRepeated".to_string()),
        field: vec![
            make_field("ids", 1, Label::LABEL_REPEATED, Type::TYPE_INT32),
            make_field("scores", 2, Label::LABEL_REPEATED, Type::TYPE_DOUBLE),
        ],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["repeatedscalar.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("repeated scalar message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub ids: ::buffa::alloc::vec::Vec<i32>"),
        "missing ids field: {content}"
    );
    assert!(
        content.contains("pub scores: ::buffa::alloc::vec::Vec<f64>"),
        "missing scores field: {content}"
    );
    // Packed encoding: payload written as a single LengthDelimited blob.
    assert!(
        content.contains("is_empty()"),
        "packed repeated should check is_empty: {content}"
    );
    assert!(
        content.contains("int32_encoded_len"),
        "missing int32_encoded_len in payload size: {content}"
    );
    assert!(
        content.contains("encode_int32"),
        "missing encode_int32 in write_to: {content}"
    );
    assert!(
        content.contains("decode_int32"),
        "missing decode_int32 in merge: {content}"
    );
    // Merge must accept both packed and unpacked.
    assert!(
        content.contains("WireType::LengthDelimited"),
        "missing packed merge branch: {content}"
    );
}

#[test]
fn test_repeated_unpacked_string() {
    let mut file = proto3_file("repeatedstr.proto");
    file.message_type.push(DescriptorProto {
        name: Some("WithRepeatedStr".to_string()),
        field: vec![make_field(
            "tags",
            1,
            Label::LABEL_REPEATED,
            Type::TYPE_STRING,
        )],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["repeatedstr.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("repeated string message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub tags: ::buffa::alloc::vec::Vec<::buffa::alloc::string::String>"),
        "missing tags field: {content}"
    );
    // Unpacked: each element has its own tag (for loop, no payload length).
    assert!(
        content.contains("string_encoded_len"),
        "missing string_encoded_len: {content}"
    );
    assert!(
        content.contains("encode_string"),
        "missing encode_string: {content}"
    );
    assert!(
        content.contains("decode_string"),
        "missing decode_string: {content}"
    );
}

#[test]
fn test_repeated_message_field() {
    let mut file = proto3_file("repeatedmsg.proto");
    file.message_type.push(DescriptorProto {
        name: Some("Item".to_string()),
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("Container".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("items".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_REPEATED),
            r#type: Some(Type::TYPE_MESSAGE),
            type_name: Some(".Item".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["repeatedmsg.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("repeated message should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub items: ::buffa::alloc::vec::Vec<Item>"),
        "missing items field: {content}"
    );
    // Uses two-pass size model for each element.
    assert!(
        content.contains("merge_length_delimited"),
        "missing merge_length_delimited for repeated msg: {content}"
    );
    assert!(
        content.contains("cached_size"),
        "missing cached_size in write_to: {content}"
    );
}

#[test]
fn test_repeated_enum_field() {
    let mut file = proto3_file("repeatedenu.proto");
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Status".to_string()),
        value: vec![enum_value("UNKNOWN", 0), enum_value("ACTIVE", 1)],
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("WithRepeatedEnum".to_string()),
        field: vec![FieldDescriptorProto {
            name: Some("statuses".to_string()),
            number: Some(1),
            label: Some(Label::LABEL_REPEATED),
            r#type: Some(Type::TYPE_ENUM),
            type_name: Some(".Status".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });

    let files = generate(
        &[file],
        &["repeatedenu.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("repeated enum should generate");
    let content = &files[0].content;
    assert!(
        content.contains("pub statuses: ::buffa::alloc::vec::Vec<::buffa::EnumValue<Status>>"),
        "missing statuses field: {content}"
    );
    // Packed enum encoding uses to_i32() and EnumValue::from.
    assert!(
        content.contains("to_i32()"),
        "missing to_i32 for packed enum write: {content}"
    );
    assert!(
        content.contains("EnumValue::from"),
        "missing EnumValue::from in packed decode: {content}"
    );
}

#[test]
fn extension_set_impl_on_generated_options() {
    // Smoke test: the bootstrap-generated FieldOptions implements
    // ExtensionSet, and extension get/set roundtrips through its
    // __buffa_unknown_fields storage.
    use crate::generated::descriptor::FieldOptions;
    use buffa::extension::codecs::{Int32, StringCodec};
    use buffa::{Extension, ExtensionSet};

    // Use the bootstrap-generated PROTO_FQN so the extendee check passes.
    const WEIGHT: Extension<Int32> = Extension::new(50001, FieldOptions::PROTO_FQN);
    const TAG: Extension<StringCodec> = Extension::new(50002, FieldOptions::PROTO_FQN);

    let mut opts = FieldOptions::default();
    assert!(!opts.has_extension(&WEIGHT));

    opts.set_extension(&WEIGHT, -7);
    opts.set_extension(&TAG, "hello".to_string());

    assert_eq!(opts.extension(&WEIGHT), Some(-7));
    assert_eq!(opts.extension(&TAG), Some("hello".to_string()));
    assert!(opts.has_extension(&WEIGHT));

    // Roundtrip through wire encoding: the extension bytes live in
    // __buffa_unknown_fields and are re-encoded by Message::write_to.
    use buffa::Message;
    let bytes = opts.encode_to_vec();
    let decoded = FieldOptions::decode_from_slice(&bytes).expect("decode");
    assert_eq!(decoded.extension(&WEIGHT), Some(-7));
    assert_eq!(decoded.extension(&TAG), Some("hello".to_string()));

    // And an ExtensionSet impl was emitted in the generated output.
    let file = proto3_file("ext.proto");
    let files = generate(
        &[FileDescriptorProto {
            message_type: vec![DescriptorProto {
                name: Some("M".to_string()),
                ..Default::default()
            }],
            ..file
        }],
        &["ext.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("generate");
    assert!(
        files[0]
            .content
            .contains("impl ::buffa::ExtensionSet for M"),
        "missing ExtensionSet impl: {}",
        files[0].content
    );
}

#[test]
fn editions_delimited_message_encoding() {
    // Editions 2023 `features.message_encoding = DELIMITED`: the descriptor
    // field type stays TYPE_MESSAGE, but the codegen must route it through
    // the group (wire types 3/4) encode/decode paths via effective_type.
    //
    // Also verifies the map-entry exemption: map values are always
    // length-prefixed (protobuf spec hard rule), even under a file-level
    // DELIMITED default.
    use crate::generated::descriptor::{
        feature_set::MessageEncoding as FsMessageEncoding, Edition, FeatureSet, FieldOptions,
        FileOptions,
    };

    let inner_msg = DescriptorProto {
        name: Some("Inner".to_string()),
        field: vec![make_field("x", 1, Label::LABEL_OPTIONAL, Type::TYPE_INT32)],
        ..Default::default()
    };

    // Field with per-field LENGTH_PREFIXED override (common pattern in
    // test_messages_edition2023.proto to opt specific fields back out).
    let mut lp_field = make_field("lp_child", 2, Label::LABEL_OPTIONAL, Type::TYPE_MESSAGE);
    lp_field.type_name = Some(".Inner".to_string());
    lp_field.options = FieldOptions {
        features: FeatureSet {
            message_encoding: Some(FsMessageEncoding::LENGTH_PREFIXED),
            ..Default::default()
        }
        .into(),
        ..Default::default()
    }
    .into();

    // Field that inherits the file-level DELIMITED default.
    let mut delim_field = make_field("delim_child", 3, Label::LABEL_OPTIONAL, Type::TYPE_MESSAGE);
    delim_field.type_name = Some(".Inner".to_string());

    // Map field with message value — must stay length-prefixed.
    let mut map_field = make_field("inners", 4, Label::LABEL_REPEATED, Type::TYPE_MESSAGE);
    map_field.type_name = Some(".Outer.InnersEntry".to_string());
    let mut map_val = make_field("value", 2, Label::LABEL_OPTIONAL, Type::TYPE_MESSAGE);
    map_val.type_name = Some(".Inner".to_string());
    let map_entry = DescriptorProto {
        name: Some("InnersEntry".to_string()),
        field: vec![
            make_field("key", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
            map_val,
        ],
        options: MessageOptions {
            map_entry: Some(true),
            ..Default::default()
        }
        .into(),
        ..Default::default()
    };

    let outer_msg = DescriptorProto {
        name: Some("Outer".to_string()),
        field: vec![lp_field, delim_field, map_field],
        nested_type: vec![map_entry],
        ..Default::default()
    };

    let file = FileDescriptorProto {
        name: Some("delim.proto".to_string()),
        edition: Some(Edition::EDITION_2023),
        options: FileOptions {
            features: FeatureSet {
                message_encoding: Some(FsMessageEncoding::DELIMITED),
                ..Default::default()
            }
            .into(),
            ..Default::default()
        }
        .into(),
        message_type: vec![inner_msg, outer_msg],
        ..Default::default()
    };

    let files = generate(
        &[file],
        &["delim.proto".to_string()],
        &CodeGenConfig::default(),
    )
    .expect("generate");
    let content = &files[0].content;

    // Field 3 (delim_child): inherits DELIMITED → StartGroup/EndGroup.
    assert!(
        content
            .contains("::buffa::encoding::Tag::new(3u32, ::buffa::encoding::WireType::StartGroup)"),
        "delim_child should encode as group: {content}"
    );
    assert!(
        content.contains("merge_group"),
        "delim_child should decode via merge_group: {content}"
    );

    // Field 2 (lp_child): explicit LENGTH_PREFIXED → regular message encoding.
    // prettyplease wraps Tag::new across lines for this field number, so
    // check the decode arm instead (single-line wire-type check).
    assert!(
        content.contains("2u32 => {\n                if tag.wire_type() != ::buffa::encoding::WireType::LengthDelimited"),
        "lp_child should decode as length-delimited: {content}"
    );
    // And it should NOT have a StartGroup encode for field 2.
    assert!(
        !content.contains("Tag::new(2u32, ::buffa::encoding::WireType::StartGroup)"),
        "lp_child should not encode as group"
    );

    // Map entry value: must NOT be group-encoded despite file-level DELIMITED.
    // If the map-entry exemption fails, codegen panics in type_encoded_size_expr
    // (TYPE_GROUP is unreachable there), so reaching this line is the key
    // evidence. Spot-check group-decode call counts: only delim_child should
    // use them (merge_group in owned impl, borrow_group in view).
    assert_eq!(
        content.matches("merge_group").count(),
        1,
        "owned: {content}"
    );
    assert_eq!(
        content.matches("borrow_group").count(),
        1,
        "view: {content}"
    );
}