reallyme-buffa-codegen 0.1.0

ReallyMe fork: 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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
//! `[deprecated = true]`: generated declarations carry `#[deprecated]` the way
//! prost-build emits it (fields and enum values), and the generated items that
//! must visit every field carry `#[allow(deprecated)]` so a deprecated member
//! does not flood the build with warnings from the generated code itself.

use super::*;
use crate::generated::descriptor::{EnumValueOptions, FieldOptions, MessageOptions};

/// Strip all whitespace so assertions are immune to prettyplease line wrapping.
fn squash(s: &str) -> String {
    s.chars().filter(|c| !c.is_whitespace()).collect()
}

fn deprecated(mut field: FieldDescriptorProto) -> FieldDescriptorProto {
    field.options = FieldOptions {
        deprecated: Some(true),
        ..Default::default()
    }
    .into();
    field
}

fn deprecated_value(mut value: EnumValueDescriptorProto) -> EnumValueDescriptorProto {
    value.options = EnumValueOptions {
        deprecated: Some(true),
        ..Default::default()
    }
    .into();
    value
}

/// `Widget` with one deprecated and one live field, plus a `Size` enum whose
/// `SMALL` value is deprecated and aliased by `TINY`.
fn deprecated_file() -> FileDescriptorProto {
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![
            deprecated(make_field(
                "legacy_name",
                1,
                Label::LABEL_OPTIONAL,
                Type::TYPE_STRING,
            )),
            make_field("label", 2, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
        ],
        ..Default::default()
    });
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![
            enum_value("SIZE_UNSPECIFIED", 0),
            deprecated_value(enum_value("SMALL", 1)),
            deprecated_value(enum_value("TINY", 1)),
        ],
        ..Default::default()
    });
    file
}

/// A file with no deprecation anywhere — its output must be untouched.
fn clean_file() -> FileDescriptorProto {
    let mut file = proto3_file("clean.proto");
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![make_field(
            "legacy_name",
            1,
            Label::LABEL_OPTIONAL,
            Type::TYPE_STRING,
        )],
        ..Default::default()
    });
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![enum_value("SIZE_UNSPECIFIED", 0), enum_value("SMALL", 1)],
        ..Default::default()
    });
    file
}

/// [`deprecated_file`] with `[debug_redact = true]` on the live field, which
/// swaps each view's `Debug` derive for an impl that names every field.
fn deprecated_file_with_redacted_label() -> FileDescriptorProto {
    let mut file = deprecated_file();
    file.message_type[0].field[1].options = FieldOptions {
        debug_redact: Some(true),
        ..Default::default()
    }
    .into();
    file
}

/// `Widget` whose only deprecated field is a member of the oneof `choice`.
fn oneof_only_file() -> FileDescriptorProto {
    let mut member = make_field("legacy_choice", 3, Label::LABEL_OPTIONAL, Type::TYPE_STRING);
    member.oneof_index = Some(0);
    let mut msg = DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![
            deprecated(member),
            make_field("label", 2, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
        ],
        ..Default::default()
    };
    msg.oneof_decl.push(OneofDescriptorProto {
        name: Some("choice".to_string()),
        ..Default::default()
    });
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(msg);
    file
}

fn generate_squashed(file: FileDescriptorProto, config: &CodeGenConfig) -> String {
    let name = file.name.clone().unwrap_or_default();
    let files = generate(&[file], &[name], config).expect("should generate");
    squash(&joined(&files))
}

// ── field markers ───────────────────────────────────────────────────

#[test]
fn deprecated_field_carries_marker() {
    let content = generate_squashed(deprecated_file(), &CodeGenConfig::default());
    assert!(
        content.contains(r#"#[deprecated]publegacy_name:"#),
        "deprecated field must carry #[deprecated]: {content}"
    );
    assert!(
        !content.contains(r#"#[deprecated]publabel:"#),
        "a live field must not carry the marker"
    );
}

#[test]
fn codec_and_debug_impls_allow_deprecated() {
    let config = CodeGenConfig {
        generate_text: true,
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    for impl_head in [
        "impl::buffa::MessageforWidget",
        "impl::core::fmt::DebugforWidget",
        "impl::buffa::text::TextFormatforWidget",
    ] {
        assert!(
            content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "{impl_head} visits every field, so it must be guarded: {content}"
        );
    }
}

#[test]
fn setters_allow_deprecated() {
    // `with_*` setters exist only for explicit-presence fields, so the
    // deprecated field has to be `optional`.
    let mut file = deprecated_file();
    let msg = &mut file.message_type[0];
    msg.field[0].proto3_optional = Some(true);
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content.contains("#[allow(deprecated)]implWidget{"),
        "the with_* setter assigns the deprecated field: {content}"
    );
}

#[test]
fn reflection_impl_allows_deprecated() {
    let config = CodeGenConfig {
        generate_reflection: true,
        generate_reflection_vtable: true,
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    assert!(
        content.contains(
            "#[allow(deprecated)]impl::buffa_descriptor::reflect::ReflectMessageforWidget"
        ),
        "the vtable reads fields by index: {content}"
    );
}

#[test]
fn json_deserialize_impl_allows_deprecated() {
    // The hand-written Deserialize impl is emitted when a oneof forces it.
    let mut msg = DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![
            deprecated(make_field(
                "legacy_name",
                1,
                Label::LABEL_OPTIONAL,
                Type::TYPE_STRING,
            )),
            make_field("label", 2, Label::LABEL_OPTIONAL, Type::TYPE_STRING),
        ],
        ..Default::default()
    };
    let mut in_oneof = make_field("alias", 3, Label::LABEL_OPTIONAL, Type::TYPE_STRING);
    in_oneof.oneof_index = Some(0);
    msg.field.push(in_oneof);
    msg.oneof_decl.push(OneofDescriptorProto {
        name: Some("name_choice".to_string()),
        ..Default::default()
    });
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(msg);

    let config = CodeGenConfig {
        generate_json: true,
        ..Default::default()
    };
    let content = generate_squashed(file, &config);
    assert!(
        content.contains("#[allow(deprecated)]impl<'de>::serde::Deserialize<'de>forWidget"),
        "the visitor assigns the deprecated field: {content}"
    );
}

// ── enum value markers ──────────────────────────────────────────────

#[test]
fn deprecated_enum_value_carries_marker_on_variant_and_alias() {
    let content = generate_squashed(deprecated_file(), &CodeGenConfig::default());
    assert!(
        content.contains("#[deprecated]SMALL=1"),
        "deprecated enum value must mark its variant: {content}"
    );
    assert!(
        content
            .contains("#[deprecated]#[allow(non_upper_case_globals)]pubconstTINY:Self=Self::SMALL"),
        "an alias of a deprecated value is deprecated too: {content}"
    );
    assert!(
        !content.contains("#[deprecated]SIZE_UNSPECIFIED=0"),
        "a live value must not carry the marker"
    );
}

#[test]
fn idiomatic_alias_inherits_deprecation() {
    let content = generate_squashed(deprecated_file(), &CodeGenConfig::default());
    assert!(
        content.contains(
            "#[deprecated]#[allow(non_upper_case_globals)]pubconstSmall:Self=Self::SMALL"
        ),
        "the CamelCase alias must not be a quiet way to reach a deprecated value: {content}"
    );
}

#[test]
fn enum_impls_that_name_variants_allow_deprecated() {
    let content = generate_squashed(deprecated_file(), &CodeGenConfig::default());
    for impl_head in [
        // `values()` lists both variants, `from_i32`/`proto_name` name them.
        "impl::buffa::EnumerationforSize",
        // The `allow_alias` const and the idiomatic consts reference `SMALL`.
        "implSize{",
    ] {
        assert!(
            content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "{impl_head} names a deprecated variant, so it must be guarded: {content}"
        );
    }
    // `Default` returns only the first value, which is live here, so it must
    // not be guarded — the guard tracks what an item actually names.
    assert!(
        !content.contains("#[allow(deprecated)]impl::core::default::DefaultforSize"),
        "Default names SIZE_UNSPECIFIED only: {content}"
    );
}

#[test]
fn first_value_deprecation_does_not_change_default() {
    // The declared default stays the first value even when it is deprecated —
    // the guard is what keeps that legal without warnings.
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![
            deprecated_value(enum_value("SIZE_UNSPECIFIED", 0)),
            enum_value("SMALL", 1),
        ],
        ..Default::default()
    });
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content.contains("#[allow(deprecated)]impl::core::default::DefaultforSize{fndefault()"),
        "Default returns the deprecated first value: {content}"
    );
}

// ── guard reach: generated surfaces that must stay quiet ────────────

/// A proto2 file whose only deprecation is an enum value named by a field's
/// `[default = …]`: the message has no deprecated field, yet the generated
/// default expression spells out `Size::OLD`. `required` is the shape that
/// carries the default into generated code (an `optional` field is `None` until
/// set, so its proto default never appears as an expression).
fn enum_default_file() -> FileDescriptorProto {
    let mut field = make_field("size", 1, Label::LABEL_REQUIRED, Type::TYPE_ENUM);
    field.type_name = Some(".deprecate.test.Size".to_string());
    field.default_value = Some("OLD".to_string());

    let mut file = proto3_file("enum_default.proto");
    file.syntax = Some("proto2".to_string());
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Holder".to_string()),
        field: vec![field],
        ..Default::default()
    });
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![deprecated_value(enum_value("OLD", 1)), enum_value("NEW", 2)],
        ..Default::default()
    });
    file
}

#[test]
fn enum_default_naming_deprecated_value_guards_codec() {
    let content = generate_squashed(enum_default_file(), &CodeGenConfig::default());
    assert!(
        content.contains("#[allow(deprecated)]impl::buffa::MessageforHolder"),
        "the codec's clear/default spells out Size::OLD, so it must be guarded: {content}"
    );
    assert!(
        content.contains("Size::OLD"),
        "fixture sanity: the default must reach the generated code: {content}"
    );
    assert!(
        content.contains("#[allow(deprecated)]impl::core::default::DefaultforHolder"),
        "the custom Default spells out Size::OLD: {content}"
    );
    // The field itself is live, so it must not be marked.
    assert!(
        !content.contains("#[deprecated]pubsize:"),
        "a live field must not carry the marker: {content}"
    );
}

#[test]
fn enum_default_naming_alias_of_deprecated_value_guards_codec() {
    // `SMALL` carries no option of its own; it is deprecated as an alias of
    // `OLD`, and the default expression names it.
    let mut file = enum_default_file();
    file.enum_type[0].value.insert(1, enum_value("SMALL", 1));
    file.message_type[0].field[0].default_value = Some("SMALL".to_string());
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content
            .contains("#[deprecated]#[allow(non_upper_case_globals)]pubconstSMALL:Self=Self::OLD"),
        "fixture sanity: the alias inherits the marker: {content}"
    );
    assert!(
        content.contains("Size::SMALL"),
        "fixture sanity: the default must reach the generated code: {content}"
    );
    assert!(
        content.contains("#[allow(deprecated)]impl::buffa::MessageforHolder"),
        "the codec spells out Size::SMALL, so it must be guarded: {content}"
    );
    assert!(
        content.contains("#[allow(deprecated)]impl::core::default::DefaultforHolder"),
        "the custom Default spells out Size::SMALL: {content}"
    );
}

#[test]
fn arbitrary_keeps_the_derive_when_only_an_alias_is_deprecated() {
    // The derive names variants only, and every variant here is live.
    let config = CodeGenConfig {
        generate_arbitrary: true,
        ..Default::default()
    };
    let mut file = enum_default_file();
    file.enum_type[0].value = vec![
        enum_value("BIG", 1),
        deprecated_value(enum_value("LARGE", 1)),
        enum_value("NEW", 2),
    ];
    file.message_type[0].field[0].default_value = Some("NEW".to_string());
    let content = generate_squashed(file, &config);
    assert!(
        !content.contains("impl<'a>::arbitrary::Arbitrary<'a>forSize"),
        "no variant is deprecated, so the derive stays: {content}"
    );
    assert_eq!(
        content
            .matches("#[cfg_attr(feature=\"arbitrary\",derive(::arbitrary::Arbitrary))]")
            .count(),
        2,
        "`Holder` and `Size` both derive: {content}"
    );
}

#[test]
fn idiomatic_const_of_an_alias_inherits_the_variant_marker() {
    // `SIZE_SMALL` has no option of its own; it is an alias of the deprecated
    // variant `SIZE_OLD`, so `Size::Small` is marked as `Size::SIZE_SMALL` is.
    let config = CodeGenConfig {
        idiomatic_enum_aliases: true,
        ..Default::default()
    };
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![
            deprecated_value(enum_value("SIZE_OLD", 0)),
            enum_value("SIZE_SMALL", 0),
        ],
        ..Default::default()
    });
    let content = generate_squashed(file, &config);
    assert!(
        content.contains(
            "#[deprecated]#[allow(non_upper_case_globals)]pubconstSmall:Self=Self::SIZE_OLD"
        ),
        "the idiomatic const of an inheriting alias carries the marker: {content}"
    );
}

#[test]
fn idiomatic_const_of_a_deprecated_alias_is_deprecated() {
    // `SIZE_LARGE` is deprecated by its own option while its variant
    // `SIZE_BIG` is live; `Size::Large` names the alias, so it is marked, and
    // `Size::Big` is not.
    let config = CodeGenConfig {
        idiomatic_enum_aliases: true,
        ..Default::default()
    };
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![
            enum_value("SIZE_BIG", 0),
            deprecated_value(enum_value("SIZE_LARGE", 0)),
        ],
        ..Default::default()
    });
    let content = generate_squashed(file, &config);
    assert!(
        content.contains(
            "#[deprecated]#[allow(non_upper_case_globals)]pubconstLarge:Self=Self::SIZE_BIG"
        ),
        "the idiomatic const of the deprecated alias carries the marker: {content}"
    );
    assert!(
        !content.contains(
            "#[deprecated]#[allow(non_upper_case_globals)]pubconstBig:Self=Self::SIZE_BIG"
        ),
        "the idiomatic const of the live variant stays unmarked: {content}"
    );
}

#[test]
fn enum_default_naming_a_deprecated_alias_of_a_live_variant_guards_codec() {
    let mut file = enum_default_file();
    file.enum_type[0].value = vec![
        enum_value("BIG", 1),
        deprecated_value(enum_value("LARGE", 1)),
        enum_value("NEW", 2),
    ];
    file.message_type[0].field[0].default_value = Some("LARGE".to_string());
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content.contains("#[allow(deprecated)]impl::buffa::MessageforHolder"),
        "the default names the deprecated alias const: {content}"
    );
}

#[test]
fn enum_default_naming_a_live_alias_beside_a_deprecated_one_is_unguarded() {
    // `C` inherits from the variant `A`, which is live; the deprecated alias
    // `B` between them does not pass its marker on.
    let mut file = enum_default_file();
    file.enum_type[0].value = vec![
        enum_value("A", 1),
        deprecated_value(enum_value("B", 1)),
        enum_value("C", 1),
    ];
    file.message_type[0].field[0].default_value = Some("C".to_string());
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content.contains("Size::C"),
        "fixture sanity: the default must reach the generated code: {content}"
    );
    assert!(
        !content.contains("#[allow(deprecated)]impl::buffa::MessageforHolder"),
        "`C` is live, so the default needs no guard: {content}"
    );
}

#[test]
fn enum_default_naming_live_variant_with_deprecated_alias_is_unguarded() {
    // The marker flows from a variant to its aliases, not back: `BIG` stays
    // live when only its alias `LARGE` is deprecated.
    let mut file = enum_default_file();
    file.enum_type[0].value = vec![
        enum_value("BIG", 1),
        deprecated_value(enum_value("LARGE", 1)),
        enum_value("NEW", 2),
    ];
    file.message_type[0].field[0].default_value = Some("BIG".to_string());
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content.contains("Size::BIG"),
        "fixture sanity: the default must reach the generated code: {content}"
    );
    assert!(
        !content.contains("#[allow(deprecated)]impl::buffa::MessageforHolder"),
        "a default that names a live variant needs no guard: {content}"
    );
}

#[test]
fn arbitrary_for_an_enum_with_a_deprecated_value_is_an_impl_not_a_derive() {
    let config = CodeGenConfig {
        generate_arbitrary: true,
        ..Default::default()
    };
    let mut file = enum_default_file();
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Live".to_string()),
        value: vec![enum_value("LIVE_A", 0), enum_value("LIVE_B", 1)],
        ..Default::default()
    });
    let content = generate_squashed(file, &config);
    // The derive would name `Size::OLD` outside any `#[allow(deprecated)]`.
    assert!(
        content.contains("#[cfg(feature=\"arbitrary\")]impl<'a>::arbitrary::Arbitrary<'a>forSize{"),
        "an enum with a deprecated value implements Arbitrary by hand: {content}"
    );
    assert!(
        content.contains(
            "letvalues=<Selfas::buffa::Enumeration>::values();\
             letdraw=<u32as::arbitrary::Arbitrary>::arbitrary(u)?;\
             letindex=(u64::from(draw)*values.len()asu64)>>32;\
             ::core::result::Result::Ok(values[indexasusize])"
        ),
        "the impl maps a `u32` onto the declared values as the derive does: {content}"
    );
    assert!(
        content.contains("<u32as::arbitrary::Arbitrary>::size_hint(depth)"),
        "the impl reports the derive's size hint: {content}"
    );
    assert!(
        !content.contains("impl<'a>::arbitrary::Arbitrary<'a>forLive"),
        "an enum without one keeps the derive: {content}"
    );
    assert_eq!(
        content
            .matches("#[cfg_attr(feature=\"arbitrary\",derive(::arbitrary::Arbitrary))]")
            .count(),
        2,
        "`Holder` and `Live` derive, `Size` does not: {content}"
    );
}

#[test]
fn lazy_view_to_owned_allows_deprecated() {
    let config = CodeGenConfig {
        lazy_views: true,
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    assert!(
        content.contains("#[allow(deprecated)]fnto_owned_message"),
        "the lazy view's to_owned writes the owned field: {content}"
    );
}

#[test]
fn table_static_allows_deprecated() {
    let config = CodeGenConfig {
        codec_strategy: crate::CodecStrategy::Table,
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    assert!(
        content.contains("#[allow(deprecated)]pub(crate)static__BUFFA_TABLE_Widget"),
        "the table entries take offsets of deprecated fields: {content}"
    );
}

#[test]
fn oneof_only_deprecation_is_unmarked_and_unguarded() {
    // A oneof member lives in the oneof enum (owned and view), which is not
    // marked, so the message's impls name no deprecated field.
    let content = generate_squashed(oneof_only_file(), &CodeGenConfig::default());
    assert!(
        !content.contains("#[deprecated]"),
        "a deprecated oneof member is not marked: {content}"
    );
    for impl_head in [
        "impl::buffa::MessageforWidget",
        "impl<'a>::buffa::MessageView<'a>forWidgetView<'a>",
    ] {
        assert!(
            !content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "a oneof-only deprecation must not guard `{impl_head}`: {content}"
        );
    }
}

#[test]
fn caller_deprecated_oneof_struct_field_guards_the_impls_that_visit_it() {
    // `Widget.choice` is the only deprecated member, and only through the
    // caller's `oneof_struct_field_attribute`. The `[deprecated = true]` on
    // the oneof's member plays no part.
    let rule = |path: &str| CodeGenConfig {
        oneof_struct_field_attributes: vec![(
            path.to_string(),
            "#[deprecated(note = \"hand\")]".to_string(),
        )],
        ..Default::default()
    };
    let impl_heads = [
        "impl::buffa::MessageforWidget",
        "impl::core::fmt::DebugforWidget",
        "impl<'a>::buffa::MessageView<'a>forWidgetView<'a>",
    ];

    let content = generate_squashed(oneof_only_file(), &rule(".deprecate.test.Widget.choice"));
    assert!(
        content.contains(r#"#[deprecated(note="hand")]pubchoice:"#),
        "the owned struct's oneof field takes the attribute: {content}"
    );
    assert_eq!(content.matches("#[deprecated").count(), 1, "{content}");
    for impl_head in impl_heads {
        assert!(
            content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "`{impl_head}` visits the deprecated oneof field: {content}"
        );
    }

    // The rule is matched against oneof paths, so one that names the plain
    // field `label` deprecates nothing and guards nothing.
    let content = generate_squashed(oneof_only_file(), &rule(".deprecate.test.Widget.label"));
    assert!(!content.contains("#[deprecated"), "{content}");
    assert!(!content.contains("#[allow(deprecated)]"), "{content}");

    // Nor does one that reaches only the synthetic oneof of an `optional`
    // field, which has no struct field of its own.
    let mut note = make_field("note", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING);
    note.oneof_index = Some(0);
    note.proto3_optional = Some(true);
    let mut file = proto3_file("synthetic.proto");
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![note],
        oneof_decl: vec![OneofDescriptorProto {
            name: Some("_note".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    });
    for path in [".", ".deprecate.test.Widget._note"] {
        let content = generate_squashed(file.clone(), &rule(path));
        assert!(!content.contains("#[deprecated"), "{path}: {content}");
        assert!(
            !content.contains("#[allow(deprecated)]"),
            "{path}: {content}"
        );
    }
}

// ── views ───────────────────────────────────────────────────────────

#[test]
fn view_field_and_owned_view_accessor_carry_marker() {
    let content = generate_squashed(deprecated_file(), &CodeGenConfig::default());
    assert!(
        content.contains("#[deprecated]publegacy_name:&'astr"),
        "the view struct's field carries the marker"
    );
    assert!(
        content.contains(
            "#[deprecated]#[allow(deprecated)]#[must_use]pubfnlegacy_name(&self)->&'_str"
        ),
        "the `WidgetOwnedView` accessor carries the marker and guards its own read"
    );
    assert!(
        !content.contains("#[deprecated]publabel:&'astr")
            && content.contains("///Field2:`label`#[must_use]pubfnlabel(&self)"),
        "a live field's view field and accessor stay unmarked"
    );
}

#[test]
fn view_impls_that_touch_fields_allow_deprecated() {
    let file = deprecated_file_with_redacted_label();
    let config = CodeGenConfig {
        generate_json: true,
        generate_reflection: true,
        generate_reflection_vtable: true,
        ..Default::default()
    };
    let content = generate_squashed(file, &config);
    for impl_head in [
        "impl<'a>::buffa::MessageView<'a>forWidgetView<'a>",
        "impl<'a>::buffa::ViewEncode<'a>forWidgetView<'a>",
        "impl<'a>::core::fmt::DebugforWidgetView<'a>",
        "impl<'__a>::serde::SerializeforWidgetView<'__a>",
        "impl<'a>::buffa_descriptor::reflect::ReflectMessageforWidgetView<'a>",
    ] {
        assert!(
            content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "`{impl_head}` reads or writes the deprecated view field, so it must be guarded"
        );
    }
}

#[test]
fn lazy_view_field_carries_marker_and_its_impls_allow_deprecated() {
    let file = deprecated_file_with_redacted_label();
    let config = CodeGenConfig {
        lazy_views: true,
        generate_json: true,
        ..Default::default()
    };
    let content = generate_squashed(file, &config);
    let lazy = &content[content
        .find("pubstructWidgetLazyView<'a>")
        .expect("the lazy view struct")..];
    assert!(
        lazy.contains("#[deprecated]publegacy_name:&'astr"),
        "the lazy view struct's field carries the marker"
    );
    for impl_head in [
        "impl<'a>::core::fmt::DebugforWidgetLazyView<'a>",
        "impl<'__a>::serde::SerializeforWidgetLazyView<'__a>",
    ] {
        assert!(
            content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "`{impl_head}` reads or writes the deprecated lazy-view field, so it must be guarded"
        );
    }
    assert_eq!(
        content
            .matches("#[allow(deprecated)]impl<'a>WidgetLazyView<'a>{")
            .count(),
        2,
        "the decode and the encode inherent impls are both guarded"
    );
    assert!(
        !content.contains("#[allow(deprecated)]impl<'a>::buffa::LazyMessageView<'a>"),
        "the `LazyMessageView` impl delegates; only its `to_owned_message` is guarded"
    );
}

#[test]
fn caller_deprecated_attribute_marks_the_view_without_its_note() {
    // A `#[deprecated]` from `field_attribute` marks every generated way to
    // reach the field. The attribute's own text stays on the owned field.
    let config = CodeGenConfig {
        field_attributes: vec![(
            ".deprecate.test.Widget.legacy_name".to_string(),
            "#[deprecated(note = \"hand\")]".to_string(),
        )],
        ..Default::default()
    };
    let content = generate_squashed(clean_file(), &config);
    assert_eq!(
        content.matches(r#"note="hand""#).count(),
        1,
        "the caller's attribute lands on the owned field only: {content}"
    );
    assert!(
        content.contains("#[deprecated]publegacy_name:&'astr"),
        "the view field carries a bare marker"
    );
    assert!(
        content.contains("#[deprecated]#[allow(deprecated)]#[must_use]pubfnlegacy_name(&self)"),
        "the `WidgetOwnedView` accessor carries a bare marker"
    );
    assert!(
        content.contains("#[allow(deprecated)]impl<'a>::buffa::MessageView<'a>forWidgetView<'a>"),
        "so the view's impls are guarded"
    );
}

#[test]
fn caller_deprecated_fields_are_marked_and_guarded_on_every_view_surface() {
    // The option-deprecated tests never consult the `field_attribute` path,
    // so this one repeats their assertions for fields that only the caller
    // deprecates: a required message field and a required scalar, beside a
    // redacted field that gives the views a `Debug` impl.
    let mut limits = make_field("limits", 1, Label::LABEL_REQUIRED, Type::TYPE_MESSAGE);
    limits.type_name = Some(".deprecate.test.Limits".to_string());
    let mut label = make_field("label", 3, Label::LABEL_OPTIONAL, Type::TYPE_STRING);
    label.options = FieldOptions {
        debug_redact: Some(true),
        ..Default::default()
    }
    .into();
    let mut file = proto3_file("required.proto");
    file.syntax = Some("proto2".to_string());
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Limits".to_string()),
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![
            limits,
            make_field("code", 2, Label::LABEL_REQUIRED, Type::TYPE_INT32),
            label,
        ],
        ..Default::default()
    });
    let note = "#[deprecated(note = \"hand\")]".to_string();
    let config = CodeGenConfig {
        field_attributes: vec![
            (".deprecate.test.Widget.limits".to_string(), note.clone()),
            (".deprecate.test.Widget.code".to_string(), note),
        ],
        lazy_views: true,
        generate_json: true,
        generate_reflection: true,
        generate_reflection_vtable: true,
        ..Default::default()
    };
    let content = generate_squashed(file, &config);

    assert_eq!(
        content.matches(r#"note="hand""#).count(),
        2,
        "the caller's attribute stays on the two owned fields: {content}"
    );
    for field in ["limits", "code"] {
        assert_eq!(
            content
                .matches(&format!("#[deprecated]pub{field}:"))
                .count(),
            2,
            "`{field}` carries a bare marker on the view and the lazy view: {content}"
        );
        assert_eq!(
            content
                .matches(&format!(
                    "#[deprecated]#[allow(deprecated)]#[must_use]#[inline]pubconstfnhas_{field}(&self)"
                ))
                .count(),
            2,
            "`has_{field}` is marked on the view and the lazy view: {content}"
        );
        assert!(
            content.contains(&format!(
                "#[deprecated]#[allow(deprecated)]#[must_use]pubfn{field}("
            )),
            "the `WidgetOwnedView` accessor for `{field}` is marked: {content}"
        );
    }
    for impl_head in [
        "impl<'a>::buffa::MessageView<'a>forWidgetView<'a>",
        "impl<'a>::buffa::ViewEncode<'a>forWidgetView<'a>",
        "impl<'a>::core::fmt::DebugforWidgetView<'a>",
        "impl<'__a>::serde::SerializeforWidgetView<'__a>",
        "impl<'a>::buffa_descriptor::reflect::ReflectMessageforWidgetView<'a>",
        "impl<'a>::core::fmt::DebugforWidgetLazyView<'a>",
        "impl<'__a>::serde::SerializeforWidgetLazyView<'__a>",
    ] {
        assert!(
            content.contains(&format!("#[allow(deprecated)]{impl_head}")),
            "`{impl_head}` names a caller-deprecated view field, so it must be guarded"
        );
    }
    assert_eq!(
        content
            .matches("#[allow(deprecated)]impl<'a>WidgetLazyView<'a>{")
            .count(),
        2,
        "the lazy view's decode and encode inherent impls are both guarded"
    );
}

#[test]
fn deprecated_map_field_carries_marker_on_each_struct() {
    let mut key = make_field("key", 1, Label::LABEL_OPTIONAL, Type::TYPE_STRING);
    key.json_name = Some("key".to_string());
    let mut value = make_field("value", 2, Label::LABEL_OPTIONAL, Type::TYPE_STRING);
    value.json_name = Some("value".to_string());
    let entry = DescriptorProto {
        name: Some("AttrsEntry".to_string()),
        field: vec![key, value],
        options: MessageOptions {
            map_entry: Some(true),
            ..Default::default()
        }
        .into(),
        ..Default::default()
    };
    let mut attrs = make_field("attrs", 1, Label::LABEL_REPEATED, Type::TYPE_MESSAGE);
    attrs.type_name = Some(".deprecate.test.Widget.AttrsEntry".to_string());
    let mut file = proto3_file("map.proto");
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![deprecated(attrs)],
        nested_type: vec![entry],
        ..Default::default()
    });
    let config = CodeGenConfig {
        lazy_views: true,
        ..Default::default()
    };
    let content = generate_squashed(file, &config);
    assert_eq!(
        content.matches("#[deprecated]pubattrs:").count(),
        3,
        "the owned struct, the view and the lazy view each mark the map field: {content}"
    );
}

#[test]
fn has_method_of_a_deprecated_required_field_is_deprecated() {
    // `has_limits` reads the view field by name and `has_code` reads the seen
    // bit. Both are reads of a deprecated field, on the view and the lazy view.
    let mut limits = make_field("limits", 1, Label::LABEL_REQUIRED, Type::TYPE_MESSAGE);
    limits.type_name = Some(".deprecate.test.Limits".to_string());
    let mut file = proto3_file("required.proto");
    file.syntax = Some("proto2".to_string());
    file.package = Some("deprecate.test".to_string());
    file.message_type.push(DescriptorProto {
        name: Some("Limits".to_string()),
        ..Default::default()
    });
    file.message_type.push(DescriptorProto {
        name: Some("Quota".to_string()),
        field: vec![
            deprecated(limits),
            deprecated(make_field(
                "code",
                2,
                Label::LABEL_REQUIRED,
                Type::TYPE_INT32,
            )),
            make_field("live", 3, Label::LABEL_REQUIRED, Type::TYPE_INT32),
        ],
        ..Default::default()
    });
    let config = CodeGenConfig {
        lazy_views: true,
        ..Default::default()
    };
    let content = generate_squashed(file, &config);
    let marked = "#[deprecated]#[allow(deprecated)]#[must_use]#[inline]pubconstfn";
    for method in ["has_limits", "has_code"] {
        assert_eq!(
            content
                .matches(&format!("{marked}{method}(&self)->bool"))
                .count(),
            2,
            "`{method}` is marked and guarded on the view and the lazy view: {content}"
        );
    }
    assert_eq!(
        content
            .matches("#[must_use]#[inline]pubconstfnhas_live(&self)->bool")
            .count(),
        2,
        "the live field keeps its accessor on both views"
    );
    assert!(
        !content.contains(&format!("{marked}has_live")),
        "a live required field's `has_*` stays unmarked"
    );
}

// ── untouched output ────────────────────────────────────────────────

#[test]
fn file_without_deprecation_emits_no_attributes() {
    let content = generate_squashed(clean_file(), &CodeGenConfig::default());
    assert!(!content.contains("#[deprecated]"), "no option, no marker");
    assert!(
        !content.contains("#[allow(deprecated)]"),
        "guards must not leak into messages that do not need them: {content}"
    );
}

// ── caller-supplied marker wins ─────────────────────────────────────

#[test]
fn caller_deprecated_attribute_is_not_duplicated() {
    // rustc rejects two `deprecated` attributes on one item, so a build that
    // restored the marker by hand must keep exactly the caller's version.
    let config = CodeGenConfig {
        field_attributes: vec![(
            ".deprecate.test.Widget.legacy_name".to_string(),
            r#"#[deprecated(note = "use label")]"#.to_string(),
        )],
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    let field_pos = content.find("publegacy_name:").expect("legacy_name field");
    let start = content[..field_pos]
        .rfind("#[deprecated")
        .expect("a deprecated attribute above the field");
    let between = &content[start..field_pos];
    // Whitespace-insensitive like the rest of this module, so the note reads
    // `note="uselabel"` here.
    assert!(
        between.contains(r#"note="uselabel""#),
        "the caller's note survives: {between}"
    );
    assert_eq!(
        between.matches("#[deprecated").count(),
        1,
        "exactly one #[deprecated] on the field, got: {between}"
    );
    assert_eq!(
        content.matches(r#"note="uselabel""#).count(),
        1,
        "the note must not be duplicated onto other fields"
    );
}

#[test]
fn caller_deprecated_attribute_on_other_field_still_gets_marker() {
    // The hand-restored path only suppresses the option-derived marker for the
    // field its path matches: `label` gets the caller's note, `legacy_name`
    // still gets the option's marker.
    let config = CodeGenConfig {
        field_attributes: vec![(
            ".deprecate.test.Widget.label".to_string(),
            "#[deprecated(note = \"hand\")]".to_string(),
        )],
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    assert!(
        content.contains("#[deprecated]publegacy_name:"),
        "unmatched field keeps the option-derived marker: {content}"
    );
    assert!(
        content.contains(r#"note="hand""#),
        "the caller's attribute still lands on its own field: {content}"
    );
}

#[test]
fn caller_deprecated_attribute_in_a_multi_attribute_string_is_detected() {
    // `matching_attributes` accepts a stream of attributes, so the marker can
    // arrive anywhere in the string — not just first.
    let config = CodeGenConfig {
        field_attributes: vec![(
            ".deprecate.test.Widget.legacy_name".to_string(),
            "#[allow(non_snake_case)] #[deprecated(note = \"use label\")]".to_string(),
        )],
        ..Default::default()
    };
    let content = generate_squashed(deprecated_file(), &config);
    let field_pos = content.find("publegacy_name:").expect("legacy_name field");
    let start = content[..field_pos]
        .rfind("#[deprecated")
        .expect("a deprecated attribute above the field");
    assert_eq!(
        content[start..field_pos].matches("#[deprecated").count(),
        1,
        "the option marker must yield to a marker in a multi-attribute string, \
         two would be a hard error: {}",
        &content[start..field_pos]
    );
}

#[test]
fn deprecated_field_setter_is_also_deprecated() {
    // Otherwise `msg.with_legacy_name(v)` is a silent way to write a
    // deprecated field while `msg.legacy_name = v` warns.
    let mut file = deprecated_file();
    file.message_type[0].field[0].proto3_optional = Some(true);
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        content.contains("#[deprecated]pubfnwith_legacy_name"),
        "the setter for a deprecated field must be deprecated: {content}"
    );
    assert!(
        !content.contains("#[deprecated]pubfnwith_label"),
        "the setter for a live field stays unmarked"
    );
}

#[test]
fn alias_deprecated_while_primary_is_live_marks_only_the_alias() {
    // Direction check: the marker flows from the value's own option, so an
    // alias can be deprecated while its primary is live (and the idiomatic
    // alias of the primary then stays unmarked).
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    file.enum_type.push(EnumDescriptorProto {
        name: Some("Size".to_string()),
        value: vec![
            enum_value("BIG", 1),
            deprecated_value(enum_value("LARGE", 1)),
        ],
        ..Default::default()
    });
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        !content.contains("#[deprecated]BIG=1"),
        "the primary is live: {content}"
    );
    assert!(
        content
            .contains("#[deprecated]#[allow(non_upper_case_globals)]pubconstLARGE:Self=Self::BIG"),
        "the deprecated alias carries the marker: {content}"
    );
    assert!(
        !content
            .contains("#[deprecated]#[allow(non_upper_case_globals)]pubconstBig:Self=Self::BIG"),
        "the primary's idiomatic alias must not inherit from the alias: {content}"
    );
}

#[test]
fn attribute_shape_detection() {
    // The caller-marker probe decides whether codegen adds its own
    // `#[deprecated]`, and two of them on one item is a hard error — so the
    // accepted and rejected shapes matter.
    let cases: &[(&str, bool)] = &[
        ("#[deprecated]", true),
        ("#[deprecated(note = \"use x\")]", true),
        ("#[deprecated(note = \"a\")]\n#[allow(dead_code)]", true),
        ("#[allow(non_snake_case)] #[deprecated]", true),
        // cfg_attr expands to the same attribute in one of its arms.
        ("#[cfg_attr(feature = \"json\", deprecated)]", true),
        (
            "#[cfg_attr(feature = \"json\", deprecated, serde(skip))]",
            true,
        ),
        // Not the built-in attribute.
        ("#[deprecated_alias]", false),
        ("#[some_tool::deprecated]", false),
        ("#[cfg_attr(feature = \"json\", allow(deprecated))]", false),
        ("#[cfg_attr(a, cfg_attr(b, deprecated))]", true),
        // `deprecated` as a cfg predicate, or as another tool's argument.
        ("#[cfg_attr(deprecated, serde(skip))]", false),
        ("#[schema(deprecated)]", false),
        ("#[serde(skip)]", false),
        ("#[doc = \"marked deprecated in the proto\"]", false),
        ("not an attribute", false),
        // An inner attribute in the stream must not abort the scan.
        ("#![allow(deprecated)] #[deprecated]", true),
    ];
    for (attr, expected) in cases {
        assert_eq!(
            crate::message::is_deprecated_attr_str(attr),
            *expected,
            "shape {attr:?} should be {expected}"
        );
    }
}

#[test]
fn message_level_deprecated_option_is_not_emitted() {
    // Parity with prost-build, which marks fields, oneof variants and enum
    // values only. Pinned so widening the scope later is a deliberate change.
    let mut msg = DescriptorProto {
        name: Some("Widget".to_string()),
        field: vec![make_field(
            "label",
            1,
            Label::LABEL_OPTIONAL,
            Type::TYPE_STRING,
        )],
        options: MessageOptions {
            deprecated: Some(true),
            ..Default::default()
        }
        .into(),
        ..Default::default()
    };
    let mut file = proto3_file("deprecated.proto");
    file.package = Some("deprecate.test".to_string());
    msg.options = MessageOptions {
        deprecated: Some(true),
        ..Default::default()
    }
    .into();
    file.message_type.push(msg);
    let content = generate_squashed(file, &CodeGenConfig::default());
    assert!(
        !content.contains("#[deprecated]pubstructWidget"),
        "message-level `deprecated` is not emitted: {content}"
    );
}