oxiproto-codegen 0.1.2

Pure Rust protobuf code generator from FileDescriptorSet to Rust structs/enums
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
#![forbid(unsafe_code)]

use prost_types::{
    DescriptorProto, EnumDescriptorProto, FieldDescriptorProto, FileDescriptorProto,
    FileDescriptorSet, SourceCodeInfo,
};

pub use crate::options::{CodegenError, CodegenOptions};
use crate::type_registry::TypeRegistry;

/// Emit Rust source code from a `FileDescriptorSet`.
pub fn emit_file_descriptor_set(fds: &FileDescriptorSet) -> Result<String, CodegenError> {
    emit_file_descriptor_set_with_options(fds, &CodegenOptions::default())
}

/// Emit Rust source code from a `FileDescriptorSet` with custom options.
pub fn emit_file_descriptor_set_with_options(
    fds: &FileDescriptorSet,
    options: &CodegenOptions,
) -> Result<String, CodegenError> {
    // Build a type registry for cross-package path resolution.
    let registry = TypeRegistry::build(fds, options.package_namespacing);

    let mut out = String::new();

    out.push_str("// Generated by oxiproto-codegen. Do not edit.\n\n");

    // Emit JSON prelude once at file root only for flat (non-namespaced) layout.
    // Under package_namespacing, the prelude is emitted per-module instead.
    if options.emit_json && !options.package_namespacing {
        out.push_str(&crate::json_impl::emit_json_file_prelude());
    }

    // Add imports for map types if any map fields exist
    let has_maps = fds.file.iter().any(file_has_map_fields);
    if has_maps {
        if options.use_btree_map_effective() {
            out.push_str("use std::collections::BTreeMap;\n\n");
        } else {
            out.push_str("use std::collections::HashMap;\n\n");
        }
    }

    // Collect per-package output when package_namespacing is enabled
    if options.package_namespacing {
        // Build a sorted map: package -> Vec of file outputs
        let mut pkg_map: std::collections::BTreeMap<String, String> =
            std::collections::BTreeMap::new();
        for file in &fds.file {
            let package = file.package.as_deref().unwrap_or("").to_string();
            let mut file_out = String::new();
            emit_file_content(&mut file_out, file, options, &package, &registry)?;
            if !file_out.trim().is_empty() {
                pkg_map.entry(package).or_default().push_str(&file_out);
            }
        }
        for (package, content) in &pkg_map {
            if package.is_empty() {
                // Root package under namespacing: emit prelude then content
                if options.emit_json {
                    out.push_str(&crate::json_impl::emit_json_file_prelude());
                }
                out.push_str(content);
            } else {
                emit_package_modules(&mut out, package, content, options);
            }
        }
    } else {
        for file in &fds.file {
            let package = file.package.as_deref().unwrap_or("").to_string();
            emit_file_content(&mut out, file, options, &package, &registry)?;
        }
    }

    Ok(out)
}

/// Wrap `content` in nested `pub mod` blocks for a dotted package name.
/// When `options.emit_json` is true, the JSON prelude (`JsonError`, `_json_type`,
/// etc.) is emitted inside the innermost module so that it is in scope for all
/// generated `to_json`/`from_json` implementations within that module.
fn emit_package_modules(out: &mut String, package: &str, content: &str, options: &CodegenOptions) {
    let parts: Vec<&str> = package.split('.').collect();
    // Open all mod blocks
    for (depth, part) in parts.iter().enumerate() {
        let indent = "    ".repeat(depth);
        out.push_str(&format!("{indent}pub mod {part} {{\n"));
    }
    // Emit JSON prelude inside the innermost module
    let indent = "    ".repeat(parts.len());
    if options.emit_json {
        for line in crate::json_impl::emit_json_file_prelude().lines() {
            if line.trim().is_empty() {
                out.push('\n');
            } else {
                out.push_str(&format!("{indent}{line}\n"));
            }
        }
    }
    // Emit content indented by parts.len() * 4 spaces
    for line in content.lines() {
        if line.trim().is_empty() {
            out.push('\n');
        } else {
            out.push_str(&format!("{indent}{line}\n"));
        }
    }
    // Close all mod blocks
    for depth in (0..parts.len()).rev() {
        let indent = "    ".repeat(depth);
        out.push_str(&format!("{indent}}}\n"));
    }
    out.push('\n');
}

fn file_has_map_fields(file: &FileDescriptorProto) -> bool {
    file.message_type.iter().any(message_has_map_fields)
}

fn message_has_map_fields(msg: &DescriptorProto) -> bool {
    msg.nested_type
        .iter()
        .any(|n| n.options.as_ref().is_some_and(|o| o.map_entry()))
        || msg.nested_type.iter().any(message_has_map_fields)
}

fn emit_file_content(
    out: &mut String,
    file: &FileDescriptorProto,
    options: &CodegenOptions,
    file_package: &str,
    registry: &TypeRegistry,
) -> Result<(), CodegenError> {
    let source_info = file.source_code_info.as_ref();

    for (idx, msg) in file.message_type.iter().enumerate() {
        let path = vec![4, idx as i32];
        emit_message(
            out,
            msg,
            &[],
            options,
            source_info,
            &path,
            file_package,
            registry,
        )?;
    }
    for (idx, en) in file.enum_type.iter().enumerate() {
        let path = vec![5, idx as i32];
        emit_enum(out, en, options, source_info, &path)?;
    }
    if options.emit_services {
        for (idx, svc) in file.service.iter().enumerate() {
            let path = vec![6, idx as i32];
            emit_service(out, svc, options, source_info, &path)?;
        }
    }
    Ok(())
}

fn emit_file(
    out: &mut String,
    file: &FileDescriptorProto,
    options: &CodegenOptions,
    registry: &TypeRegistry,
) -> Result<(), CodegenError> {
    let file_package = file.package.as_deref().unwrap_or("");
    emit_file_content(out, file, options, file_package, registry)
}

#[allow(dead_code)]
pub(crate) fn emit_file_compat(
    out: &mut String,
    file: &FileDescriptorProto,
    options: &CodegenOptions,
) -> Result<(), CodegenError> {
    // Build a minimal single-file registry for the compat path.
    let fds = prost_types::FileDescriptorSet {
        file: vec![file.clone()],
    };
    let registry = TypeRegistry::build(&fds, options.package_namespacing);
    emit_file(out, file, options, &registry)
}

/// Compute the fully-qualified proto type name for a message.
fn fully_qualified_type_name(name: &str, file_package: &str) -> String {
    if file_package.is_empty() {
        name.to_string()
    } else {
        format!("{file_package}.{name}")
    }
}

/// Collect reserved field numbers from a message descriptor.
fn reserved_numbers(msg: &DescriptorProto) -> std::collections::HashSet<i32> {
    let mut set = std::collections::HashSet::new();
    for range in &msg.reserved_range {
        let start = range.start.unwrap_or(0);
        let end = range.end.unwrap_or(0);
        for n in start..end {
            set.insert(n);
        }
    }
    set
}

/// Collect reserved field names from a message descriptor.
fn reserved_names(msg: &DescriptorProto) -> std::collections::HashSet<&str> {
    msg.reserved_name.iter().map(|s| s.as_str()).collect()
}

#[allow(clippy::too_many_arguments)]
fn emit_message(
    out: &mut String,
    msg: &DescriptorProto,
    name_prefix: &[&str],
    options: &CodegenOptions,
    source_info: Option<&SourceCodeInfo>,
    path: &[i32],
    file_package: &str,
    registry: &TypeRegistry,
) -> Result<(), CodegenError> {
    let name = msg
        .name
        .as_deref()
        .ok_or_else(|| CodegenError::InvalidDescriptor("message missing name".into()))?;

    // Skip map entry types — they are emitted inline as HashMap/BTreeMap
    if msg.options.as_ref().is_some_and(|o| o.map_entry()) {
        return Ok(());
    }

    let full_name = if name_prefix.is_empty() {
        name.to_string()
    } else {
        format!("{}_{}", name_prefix.join("_"), name)
    };

    // Fully-qualified proto name for attribute lookup
    let fq_name = fully_qualified_type_name(&full_name, file_package);

    // Collect reserved info
    let res_nums = reserved_numbers(msg);
    let res_names = reserved_names(msg);

    // Collect oneof groups for this message
    let oneofs = collect_oneofs(msg)?;

    // Determine which fields belong to a oneof
    let oneof_field_indices: Vec<Option<usize>> = msg
        .field
        .iter()
        .map(|f| f.oneof_index.map(|i| i as usize))
        .collect();

    // Build map field info: map<K,V> fields reference a nested map entry type
    let map_entries = collect_map_entries(msg, file_package, registry);
    let map_field_names: std::collections::HashSet<String> = map_entries.keys().cloned().collect();

    // Custom type attributes
    if let Some(attrs) = options.type_attributes.get(&fq_name) {
        for attr in attrs {
            out.push_str(attr);
            out.push('\n');
        }
    }

    // Emit doc comments (top-level item: no indent)
    if options.generate_docs {
        emit_leading_comments(out, source_info, path, 0);
    }

    // Deprecated attribute
    let is_deprecated =
        options.generate_deprecated && msg.options.as_ref().is_some_and(|o| o.deprecated());
    if is_deprecated {
        out.push_str("#[deprecated]\n");
    }

    out.push_str("#[derive(Debug, Clone, PartialEq, Default)]\n");
    out.push_str(&format!("pub struct {full_name} {{\n"));

    // Track which oneofs have been emitted
    let mut emitted_oneofs = vec![false; oneofs.len()];

    for (field_idx, field) in msg.field.iter().enumerate() {
        let fname = field
            .name
            .as_deref()
            .ok_or_else(|| CodegenError::InvalidDescriptor("field missing name".into()))?;
        let field_number = field.number.unwrap_or(0);

        // Skip reserved fields
        if res_nums.contains(&field_number) || res_names.contains(fname) {
            let comment_target = if res_names.contains(fname) {
                fname.to_string()
            } else {
                format!("{field_number}")
            };
            out.push_str(&format!("    // reserved field {comment_target}\n"));
            continue;
        }

        // Per-field attributes
        let fq_field_key = format!("{fq_name}.{fname}");
        if let Some(fattrs) = options.field_attributes.get(&fq_field_key) {
            for attr in fattrs {
                out.push_str("    ");
                out.push_str(attr);
                out.push('\n');
            }
        }

        // Emit doc comment for field (struct member: 4-space indent)
        if options.generate_docs {
            let mut field_path = path.to_vec();
            field_path.push(2); // 2 = field in DescriptorProto
            field_path.push(field_idx as i32);
            emit_leading_comments(out, source_info, &field_path, 4);
        }

        // Deprecated field
        if options.generate_deprecated && field.options.as_ref().is_some_and(|o| o.deprecated()) {
            out.push_str("    #[deprecated]\n");
        }

        // Check if this field belongs to a oneof
        if let Some(oneof_idx) = oneof_field_indices[field_idx] {
            if !emitted_oneofs[oneof_idx] {
                emitted_oneofs[oneof_idx] = true;
                let oneof = &oneofs[oneof_idx];
                let oneof_type = format!("{full_name}_{}", to_pascal_case(&oneof.name));
                out.push_str(&format!("    pub {}: Option<{oneof_type}>,\n", oneof.name));
            }
            continue;
        }

        // Check if this is a map field
        if let Some(map_info) = map_entries.get(fname) {
            let map_type = if options.use_btree_map_effective() {
                "BTreeMap"
            } else {
                "HashMap"
            };
            out.push_str(&format!(
                "    pub {fname}: {map_type}<{}, {}>,\n",
                map_info.key_type, map_info.value_type
            ));
            continue;
        }

        let ftype = field_type_str_with_wkt(field, &full_name, file_package, registry)?;
        out.push_str(&format!("    pub {fname}: {ftype},\n"));
    }

    // Add _unknown field for OxiMessage support
    if options.emit_oxi_message_impl {
        out.push_str("    #[doc(hidden)]\n");
        out.push_str("    pub _unknown: ::oxiproto_core::wire::UnknownFields,\n");
    }

    out.push_str("}\n\n");

    // Emit oneof enums
    for (oneof_idx, oneof) in oneofs.iter().enumerate() {
        let oneof_type = format!("{full_name}_{}", to_pascal_case(&oneof.name));
        emit_oneof_enum(
            out,
            &oneof_type,
            &msg.field,
            oneof_idx,
            &full_name,
            options,
            file_package,
            registry,
        )?;
    }

    // Emit OxiMessage and OxiName impls if requested
    if options.emit_oxi_message_impl {
        let impl_code = crate::message_impl::emit_oxi_message_impl(
            msg,
            &full_name,
            file_package,
            &map_field_names,
        )?;
        out.push_str(&impl_code);
        let name_code = crate::message_impl::emit_oxi_name_impl(msg, &full_name, file_package);
        out.push_str(&name_code);
    }

    // Emit JSON to_json/from_json impls if requested
    if options.emit_json {
        let json_code = crate::json_impl::emit_json_impls(
            msg,
            &full_name,
            file_package,
            &map_field_names,
            registry,
        )?;
        out.push_str(&json_code);
    }

    // Emit builder if requested
    if options.emit_builder {
        let builder_code = crate::builder_impl::emit_builder_for_message(
            msg,
            &full_name,
            options,
            file_package,
            registry,
        )?;
        out.push_str(&builder_code);
    }

    // Emit text format method if requested
    if options.emit_text_format {
        let text_code = crate::text_impl::emit_text_format_impl(
            msg,
            &full_name,
            options,
            file_package,
            registry,
        )?;
        out.push_str(&text_code);
    }

    // Recurse into nested messages, prefixing with current name
    let prefix: Vec<&str> = name_prefix
        .iter()
        .copied()
        .chain(std::iter::once(name))
        .collect();
    for (idx, nested) in msg.nested_type.iter().enumerate() {
        let mut nested_path = path.to_vec();
        nested_path.push(3); // 3 = nested_type in DescriptorProto
        nested_path.push(idx as i32);
        emit_message(
            out,
            nested,
            &prefix,
            options,
            source_info,
            &nested_path,
            file_package,
            registry,
        )?;
    }
    for (idx, en) in msg.enum_type.iter().enumerate() {
        let mut enum_path = path.to_vec();
        enum_path.push(4); // 4 = enum_type in DescriptorProto
        enum_path.push(idx as i32);
        emit_enum(out, en, options, source_info, &enum_path)?;
    }
    Ok(())
}

/// Information about a map field's key and value types.
pub(crate) struct MapFieldInfo {
    pub(crate) key_type: String,
    pub(crate) value_type: String,
}

/// Collect map entry types from nested messages.
pub(crate) fn collect_map_entries(
    msg: &DescriptorProto,
    file_package: &str,
    registry: &TypeRegistry,
) -> std::collections::BTreeMap<String, MapFieldInfo> {
    let mut result = std::collections::BTreeMap::new();

    for nested in &msg.nested_type {
        let is_map_entry = nested.options.as_ref().is_some_and(|o| o.map_entry());
        if !is_map_entry {
            continue;
        }

        let entry_name = nested.name.as_deref().unwrap_or("");

        // Find which field in the parent references this map entry
        for field in &msg.field {
            let type_name = field.type_name.as_deref().unwrap_or("");
            let type_last = type_name.split('.').next_back().unwrap_or("");
            if type_last != entry_name {
                continue;
            }
            let field_name = field.name.as_deref().unwrap_or("");
            if field_name.is_empty() {
                continue;
            }

            let key_type = nested
                .field
                .iter()
                .find(|f| f.name.as_deref() == Some("key"))
                .map(|f| scalar_type_string(f, file_package, registry))
                .unwrap_or_else(|| "String".to_string());
            let value_type = nested
                .field
                .iter()
                .find(|f| f.name.as_deref() == Some("value"))
                .map(|f| scalar_type_string(f, file_package, registry))
                .unwrap_or_else(|| "String".to_string());

            result.insert(
                field_name.to_string(),
                MapFieldInfo {
                    key_type,
                    value_type,
                },
            );
        }
    }

    result
}

/// Get the Rust type string for a scalar/enum/message field (used by map entries and general fields).
///
/// For message and enum types, uses the registry to compute the correct relative path.
fn scalar_type_string(
    field: &FieldDescriptorProto,
    file_package: &str,
    registry: &TypeRegistry,
) -> String {
    use prost_types::field_descriptor_proto::Type;
    let ftype = field.r#type.unwrap_or(Type::String as i32);

    if ftype == Type::Message as i32 || ftype == Type::Enum as i32 {
        let raw_type_name = field.type_name.as_deref().unwrap_or("");
        return registry.resolve(file_package, raw_type_name);
    }

    match ftype {
        t if t == Type::Int32 as i32 || t == Type::Sint32 as i32 || t == Type::Sfixed32 as i32 => {
            "i32".to_string()
        }
        t if t == Type::Int64 as i32 || t == Type::Sint64 as i32 || t == Type::Sfixed64 as i32 => {
            "i64".to_string()
        }
        t if t == Type::Uint32 as i32 || t == Type::Fixed32 as i32 => "u32".to_string(),
        t if t == Type::Uint64 as i32 || t == Type::Fixed64 as i32 => "u64".to_string(),
        t if t == Type::Float as i32 => "f32".to_string(),
        t if t == Type::Double as i32 => "f64".to_string(),
        t if t == Type::Bool as i32 => "bool".to_string(),
        t if t == Type::String as i32 => "String".to_string(),
        t if t == Type::Bytes as i32 => "Vec<u8>".to_string(),
        _ => "String".to_string(),
    }
}

/// Collected information about a oneof group.
struct OneofInfo {
    name: String,
}

/// Collect oneof groups from a message descriptor.
fn collect_oneofs(msg: &DescriptorProto) -> Result<Vec<OneofInfo>, CodegenError> {
    let mut oneofs = Vec::new();
    for oneof in &msg.oneof_decl {
        let name = oneof
            .name
            .as_deref()
            .ok_or_else(|| CodegenError::InvalidDescriptor("oneof missing name".into()))?;
        oneofs.push(OneofInfo {
            name: name.to_string(),
        });
    }
    Ok(oneofs)
}

/// Emit a Rust enum for a oneof group.
#[allow(clippy::too_many_arguments)]
fn emit_oneof_enum(
    out: &mut String,
    enum_name: &str,
    fields: &[FieldDescriptorProto],
    oneof_index: usize,
    parent_struct: &str,
    _options: &CodegenOptions,
    file_package: &str,
    registry: &TypeRegistry,
) -> Result<(), CodegenError> {
    let oneof_fields: Vec<&FieldDescriptorProto> = fields
        .iter()
        .filter(|f| f.oneof_index == Some(oneof_index as i32))
        .collect();

    if oneof_fields.is_empty() {
        return Ok(());
    }

    // Oneof enum names follow the flat convention `{Parent}_{OneofName}` which
    // intentionally contains underscores — suppress the style lint for generated code.
    out.push_str("#[allow(clippy::all, non_camel_case_types, clippy::enum_variant_names)]\n");
    out.push_str("#[derive(Debug, Clone, PartialEq)]\n");
    out.push_str(&format!("pub enum {enum_name} {{\n"));

    for field in &oneof_fields {
        let fname = field
            .name
            .as_deref()
            .ok_or_else(|| CodegenError::InvalidDescriptor("oneof field missing name".into()))?;
        let variant_name = to_pascal_case(fname);
        let ftype = oneof_field_type_str(field, parent_struct, file_package, registry)?;
        out.push_str(&format!("    {variant_name}({ftype}),\n"));
    }

    out.push_str("}\n\n");
    Ok(())
}

/// Get the Rust type for a oneof field variant.
fn oneof_field_type_str(
    field: &FieldDescriptorProto,
    _parent_struct: &str,
    file_package: &str,
    registry: &TypeRegistry,
) -> Result<String, CodegenError> {
    use prost_types::field_descriptor_proto::Type;

    let ftype = field.r#type.unwrap_or(Type::String as i32);
    let raw_type_name = field.type_name.as_deref().unwrap_or("");

    if ftype == Type::Message as i32 {
        let n = registry.resolve(file_package, raw_type_name);
        return Ok(format!("Box<{n}>"));
    }

    Ok(scalar_type_string(field, file_package, registry))
}

fn emit_enum(
    out: &mut String,
    en: &EnumDescriptorProto,
    options: &CodegenOptions,
    source_info: Option<&SourceCodeInfo>,
    path: &[i32],
) -> Result<(), CodegenError> {
    let name = en
        .name
        .as_deref()
        .ok_or_else(|| CodegenError::InvalidDescriptor("enum missing name".into()))?;

    // Doc comments (top-level item: no indent)
    if options.generate_docs {
        emit_leading_comments(out, source_info, path, 0);
    }

    // Deprecated
    let is_deprecated =
        options.generate_deprecated && en.options.as_ref().is_some_and(|o| o.deprecated());
    if is_deprecated {
        out.push_str("#[deprecated]\n");
    }

    // Generated proto enums commonly have variants that share a prefix with the
    // enum type name (e.g. `Color::ColorUnspecified`) — suppress the lint.
    out.push_str("#[allow(clippy::enum_variant_names)]\n");
    out.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n");
    out.push_str("#[repr(i32)]\n");
    out.push_str(&format!("pub enum {name} {{\n"));
    for (val_idx, val) in en.value.iter().enumerate() {
        let vname = val
            .name
            .as_deref()
            .ok_or_else(|| CodegenError::InvalidDescriptor("enum value missing name".into()))?;
        let num = val.number.unwrap_or(0);
        let variant = to_pascal_case_enum(vname, name);

        if options.generate_docs {
            let mut val_path = path.to_vec();
            val_path.push(2);
            val_path.push(val_idx as i32);
            emit_leading_comments(out, source_info, &val_path, 4);
        }

        out.push_str(&format!("    {variant} = {num},\n"));
    }
    out.push_str("}\n\n");

    // Emit Default impl for the enum (first value is the default per proto3)
    if let Some(first_val) = en.value.first() {
        let first_name = first_val.name.as_deref().unwrap_or("UNKNOWN");
        let first_variant = to_pascal_case_enum(first_name, name);
        out.push_str("#[allow(clippy::derivable_impls)]\n");
        out.push_str(&format!("impl Default for {name} {{\n"));
        out.push_str("    fn default() -> Self {\n");
        out.push_str(&format!("        {name}::{first_variant}\n"));
        out.push_str("    }\n");
        out.push_str("}\n\n");
    }

    // Emit From<i32> conversion
    out.push_str(&format!("impl {name} {{\n"));
    out.push_str("    /// Convert from an i32 value, returning `None` for unknown values.\n");
    out.push_str("    pub fn from_i32(value: i32) -> Option<Self> {\n");
    out.push_str("        match value {\n");
    for val in &en.value {
        let vname = val.name.as_deref().unwrap_or("UNKNOWN");
        let num = val.number.unwrap_or(0);
        let variant = to_pascal_case_enum(vname, name);
        out.push_str(&format!("            {num} => Some({name}::{variant}),\n"));
    }
    out.push_str("            _ => None,\n");
    out.push_str("        }\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");

    // Emit JSON methods if requested
    if options.emit_json {
        out.push_str(&crate::json_impl::emit_enum_json_impl(en, name)?);
    }

    Ok(())
}

/// Emit a service trait definition.
fn emit_service(
    out: &mut String,
    svc: &prost_types::ServiceDescriptorProto,
    options: &CodegenOptions,
    source_info: Option<&SourceCodeInfo>,
    path: &[i32],
) -> Result<(), CodegenError> {
    let name = svc
        .name
        .as_deref()
        .ok_or_else(|| CodegenError::InvalidDescriptor("service missing name".into()))?;

    if options.generate_docs {
        emit_leading_comments(out, source_info, path, 0);
    }

    let is_deprecated =
        options.generate_deprecated && svc.options.as_ref().is_some_and(|o| o.deprecated());
    if is_deprecated {
        out.push_str("#[deprecated]\n");
    }

    out.push_str(&format!("pub trait {name} {{\n"));

    for (method_idx, method) in svc.method.iter().enumerate() {
        let method_name = method
            .name
            .as_deref()
            .ok_or_else(|| CodegenError::InvalidDescriptor("method missing name".into()))?;
        let rust_method_name = to_snake_case(method_name);

        if options.generate_docs {
            let mut method_path = path.to_vec();
            method_path.push(2);
            method_path.push(method_idx as i32);
            emit_leading_comments(out, source_info, &method_path, 4);
        }

        let input_type = method
            .input_type
            .as_deref()
            .map(|t| last_component(t.trim_start_matches('.')))
            .unwrap_or_else(|| "()".to_string());
        let output_type = method
            .output_type
            .as_deref()
            .map(|t| last_component(t.trim_start_matches('.')))
            .unwrap_or_else(|| "()".to_string());

        let client_streaming = method.client_streaming.unwrap_or(false);
        let server_streaming = method.server_streaming.unwrap_or(false);

        let (req_type, resp_type) = match (client_streaming, server_streaming) {
            (false, false) => (input_type.clone(), output_type.clone()),
            (false, true) => (input_type.clone(), format!("Vec<{output_type}>")),
            (true, false) => (format!("Vec<{input_type}>"), output_type.clone()),
            (true, true) => (format!("Vec<{input_type}>"), format!("Vec<{output_type}>")),
        };

        out.push_str(&format!(
            "    fn {rust_method_name}(&self, request: {req_type}) -> Result<{resp_type}, Box<dyn std::error::Error>>;\n"
        ));
    }

    out.push_str("}\n\n");
    Ok(())
}

/// Emit leading comments from source code info as Rust doc comments.
fn emit_leading_comments(
    out: &mut String,
    source_info: Option<&SourceCodeInfo>,
    path: &[i32],
    indent: usize,
) {
    let Some(sci) = source_info else {
        return;
    };

    let pad = " ".repeat(indent);
    for loc in &sci.location {
        if loc.path == path {
            if let Some(leading) = &loc.leading_comments {
                for line in leading.lines() {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        out.push_str(&format!("{pad}///\n"));
                    } else {
                        out.push_str(&format!("{pad}/// {trimmed}\n"));
                    }
                }
            }
        }
    }
}

/// Determine the Rust field type, checking WKT first.
pub(crate) fn field_type_str_with_wkt(
    field: &FieldDescriptorProto,
    struct_name: &str,
    file_package: &str,
    registry: &TypeRegistry,
) -> Result<String, CodegenError> {
    use prost_types::field_descriptor_proto::{Label, Type};

    let label = field.label.unwrap_or(Label::Optional as i32);
    let ftype = field.r#type.unwrap_or(Type::String as i32);
    let repeated = label == Label::Repeated as i32;
    let raw_type_name = field.type_name.as_deref().unwrap_or("");

    // Check WKT first
    if ftype == Type::Message as i32 && !raw_type_name.is_empty() {
        // Normalize: strip leading dot, then check both forms
        let normalized = raw_type_name.trim_start_matches('.');
        let lookup_with_dot = format!(".{normalized}");
        if let Some(wkt) = crate::wkt_map::wkt_rust_type(&lookup_with_dot) {
            return if repeated {
                Ok(format!("Vec<{wkt}>"))
            } else {
                Ok(wkt.to_string())
            };
        }
    }

    field_type_str(field, struct_name, file_package, registry)
}

fn field_type_str(
    field: &FieldDescriptorProto,
    _struct_name: &str,
    file_package: &str,
    registry: &TypeRegistry,
) -> Result<String, CodegenError> {
    use prost_types::field_descriptor_proto::{Label, Type};

    let label = field.label.unwrap_or(Label::Optional as i32);
    let ftype = field.r#type.unwrap_or(Type::String as i32);
    let repeated = label == Label::Repeated as i32;
    let raw_type_name = field.type_name.as_deref().unwrap_or("");

    if ftype == Type::Message as i32 {
        let n = registry.resolve(file_package, raw_type_name);
        return if repeated {
            Ok(format!("Vec<{n}>"))
        } else {
            Ok(format!("Option<Box<{n}>>"))
        };
    }

    let base: String = scalar_type_string(field, file_package, registry);

    if repeated {
        Ok(format!("Vec<{base}>"))
    } else {
        Ok(base)
    }
}

fn last_component(s: &str) -> String {
    s.split('.').next_back().unwrap_or(s).to_string()
}

/// Convert SCREAMING_SNAKE_CASE or snake_case to PascalCase (CamelCase).
pub(crate) fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
            }
        })
        .collect()
}

/// Public re-export of to_pascal_case for use in message_impl.
pub(crate) fn to_pascal_case_pub(s: &str) -> String {
    to_pascal_case(s)
}

/// Convert PascalCase/camelCase to snake_case.
fn to_snake_case(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 4);
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        result.push(c.to_ascii_lowercase());
    }
    result
}

/// Convert enum value name to PascalCase, stripping the enum type prefix
/// if the value name starts with it (common in protobuf style).
fn to_pascal_case_enum(value_name: &str, _enum_name: &str) -> String {
    to_pascal_case(value_name)
}

/// Structured representation of generated Rust code grouped into a module hierarchy.
///
/// Each node corresponds to one package segment. The root node represents
/// the top-level scope (empty `name`). `items` holds rendered Rust code
/// (struct definitions, impls, etc.) belonging to this module. `children`
/// hold sub-packages.
#[derive(Debug, Clone, Default)]
pub struct ModuleTree {
    /// Module name (one package segment, e.g. `"foo"` for `package foo.bar`).
    /// Empty string for the root node.
    pub name: String,
    /// Rendered Rust items (one string per file's content at this package level).
    pub items: Vec<String>,
    /// Sub-package modules (one per unique next segment).
    pub children: Vec<ModuleTree>,
}

impl ModuleTree {
    /// Find or create a direct child module with the given name.
    fn get_or_insert_child(&mut self, name: &str) -> &mut ModuleTree {
        let pos = match self.children.iter().position(|c| c.name == name) {
            Some(p) => p,
            None => {
                self.children.push(ModuleTree {
                    name: name.to_string(),
                    ..Default::default()
                });
                self.children.len() - 1
            }
        };
        &mut self.children[pos]
    }

    /// Navigate to the node at `path` from this root, creating intermediate nodes.
    fn navigate_to(&mut self, path: &[&str]) -> &mut ModuleTree {
        let mut node = self;
        for &seg in path {
            node = node.get_or_insert_child(seg);
        }
        node
    }

    /// Render the tree to a flat Rust source string.
    ///
    /// Each child module is wrapped in `pub mod {name} { ... }`.
    /// Items at each node are concatenated before child modules.
    pub fn render(&self) -> String {
        let mut out = String::new();
        // Items first
        for item in &self.items {
            out.push_str(item);
            out.push('\n');
        }
        // Then children wrapped in `pub mod`
        for child in &self.children {
            out.push_str(&format!("pub mod {} {{\n", child.name));
            let inner = child.render();
            // Indent inner content by 4 spaces
            for line in inner.lines() {
                if line.is_empty() {
                    out.push('\n');
                } else {
                    out.push_str("    ");
                    out.push_str(line);
                    out.push('\n');
                }
            }
            out.push_str("}\n");
        }
        out
    }

    /// All module paths in the tree (depth-first). Each path is a Vec of
    /// module-name segments from root to leaf.
    pub fn all_paths(&self) -> Vec<Vec<String>> {
        let mut result = Vec::new();
        self.collect_paths(&[], &mut result);
        result
    }

    fn collect_paths(&self, prefix: &[String], out: &mut Vec<Vec<String>>) {
        let path: Vec<String> = if self.name.is_empty() {
            prefix.to_vec()
        } else {
            let mut p = prefix.to_vec();
            p.push(self.name.clone());
            p
        };
        out.push(path.clone());
        for child in &self.children {
            child.collect_paths(&path, out);
        }
    }
}

/// Generate a `ModuleTree` from a `FileDescriptorSet`.
///
/// Each package becomes a node in the tree. Items from multiple files in
/// the same package are kept as separate entries in `items` (one per file).
pub fn generate_module_tree(
    fds: &FileDescriptorSet,
    options: &CodegenOptions,
) -> Result<ModuleTree, CodegenError> {
    use std::collections::BTreeMap;

    let registry = TypeRegistry::build(fds, true); // tree is always namespace-aware

    // One Vec entry per FILE — do NOT concatenate same-package files.
    let mut pkg_map: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for file in &fds.file {
        let pkg = file.package.as_deref().unwrap_or("").to_string();
        let mut file_out = String::new();
        emit_file_content(&mut file_out, file, options, &pkg, &registry)?;
        pkg_map.entry(pkg).or_default().push(file_out);
    }

    let mut root = ModuleTree::default();

    for (pkg, contents) in pkg_map {
        if pkg.is_empty() {
            for c in contents {
                root.items.push(c);
            }
        } else {
            let segs: Vec<&str> = pkg.split('.').collect();
            let node = root.navigate_to(&segs);
            for c in contents {
                node.items.push(c);
            }
        }
    }

    Ok(root)
}