typespec_rs 0.4.2

A Rust implementation of the TypeSpec type system — parser, checker, and emitter
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
//! @typespec/protobuf - Protocol Buffers Types and Decorators
//!
//! Ported from TypeSpec packages/protobuf
//!
//! Provides types and decorators for Protocol Buffers (Protobuf) modeling:
//! - `@message` - Declare a model as a Protobuf message
//! - `@field(index)` - Define field index for a message property
//! - `@reserve(...)` - Reserve field indices, ranges, or names
//! - `@service` - Declare an interface as a Protobuf service
//! - `@package(details?)` - Declare a namespace as a Protobuf package
//! - `@stream(mode)` - Set streaming mode for an operation
//!
//! Custom scalar types:
//! - `sint32`, `sint64` - Signed integer encodings
//! - `sfixed32`, `sfixed64` - Signed fixed-width encodings
//! - `fixed32`, `fixed64` - Unsigned fixed-width encodings
//!
//! Types:
//! - `Extern<Path, Name>` - External Protobuf reference
//! - `Map<Key, Value>` - Protobuf map type
//! - `StreamMode` enum - Streaming mode for operations
//! - `PackageDetails` model - Package configuration
//!
//! Well-known types:
//! - `Empty` - google.protobuf.Empty
//! - `Timestamp` - google.protobuf.Timestamp
//! - `Any` - google.protobuf.Any
//! - `LatLng` - google.type.LatLng
//!
//! ## Helper Functions
//! - `is_map(state, target)` - Check if a model is a Protobuf map
//! - `is_message(state, target)` - Check if a type is a Protobuf message

use crate::checker::types::TypeId;
use crate::diagnostics::{DiagnosticDefinition, DiagnosticMap};
use crate::state_accessors::StateAccessors;
use std::collections::HashMap;

// ============================================================================
// Diagnostic codes
// ============================================================================

pub const DIAG_FIELD_INDEX_MISSING: &str = "field-index/missing";
pub const DIAG_FIELD_INDEX_INVALID: &str = "field-index/invalid";
pub const DIAG_FIELD_INDEX_OUT_OF_BOUNDS: &str = "field-index/out-of-bounds";
pub const DIAG_FIELD_INDEX_RESERVED: &str = "field-index/reserved";
pub const DIAG_FIELD_INDEX_USER_RESERVED: &str = "field-index/user-reserved";
pub const DIAG_FIELD_INDEX_USER_RESERVED_RANGE: &str = "field-index/user-reserved-range";
pub const DIAG_FIELD_NAME_USER_RESERVED: &str = "field-name/user-reserved";
pub const DIAG_ROOT_OPERATION: &str = "root-operation";
pub const DIAG_UNSUPPORTED_INTRINSIC: &str = "unsupported-intrinsic";
pub const DIAG_UNSUPPORTED_RETURN_TYPE: &str = "unsupported-return-type";
pub const DIAG_UNSUPPORTED_INPUT_TYPE: &str = "unsupported-input-type";
pub const DIAG_UNSUPPORTED_FIELD_TYPE: &str = "unsupported-field-type";
pub const DIAG_NAMESPACE_COLLISION: &str = "namespace-collision";
pub const DIAG_UNCONVERTIBLE_ENUM: &str = "unconvertible-enum";
pub const DIAG_NESTED_ARRAY: &str = "nested-array";
pub const DIAG_INVALID_PACKAGE_NAME: &str = "invalid-package-name";
pub const DIAG_ILLEGAL_RESERVATION: &str = "illegal-reservation";
pub const DIAG_MODEL_NOT_IN_PACKAGE: &str = "model-not-in-package";
pub const DIAG_ANONYMOUS_MODEL: &str = "anonymous-model";
pub const DIAG_UNSPEAKABLE_TEMPLATE_ARGUMENT: &str = "unspeakable-template-argument";
pub const DIAG_OPTIONAL_ARRAY_FIELD: &str = "optional-array-field";
pub const DIAG_OPTIONAL_MAP_FIELD: &str = "optional-map-field";
pub const DIAG_PACKAGE: &str = "package";

// ============================================================================
// Protobuf syntax versions
// ============================================================================

/// Protobuf syntax version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ProtoSyntax {
    /// proto2 syntax
    Proto2,
    /// proto3 syntax
    #[default]
    Proto3,
}

// ============================================================================
// State keys (fully qualified with namespace)
// ============================================================================

/// State key for @field decorator
pub const STATE_FIELD_INDEX: &str = "TypeSpec.Protobuf.fieldIndex";
/// State key for @package decorator
pub const STATE_PACKAGE: &str = "TypeSpec.Protobuf.package";
/// State key for @service decorator
pub const STATE_SERVICE: &str = "TypeSpec.Protobuf.service";
/// State key for extern reference
pub const STATE_EXTERN_REF: &str = "TypeSpec.Protobuf.externRef";
/// State key for @stream decorator
pub const STATE_STREAM: &str = "TypeSpec.Protobuf.stream";
/// State key for @reserve decorator
pub const STATE_RESERVE: &str = "TypeSpec.Protobuf.reserve";
/// State key for @message decorator
pub const STATE_MESSAGE: &str = "TypeSpec.Protobuf.message";
/// State key for Map marker
pub const STATE_MAP: &str = "TypeSpec.Protobuf._map";

/// Namespace for Protobuf types
pub const PROTOBUF_NAMESPACE: &str = "TypeSpec.Protobuf";

// ============================================================================
// StreamMode enum
// ============================================================================

string_enum! {
    /// Streaming mode for an operation.
    /// Ported from TS StreamMode enum.
    pub enum StreamMode {
        /// Both input and output are streaming
        Duplex => "Duplex",
        /// Input is streaming (client streaming)
        In => "In",
        /// Output is streaming (server streaming)
        Out => "Out",
        /// Neither input nor output are streaming
        None => "None",
    }
}

// ============================================================================
// Protobuf scalar types (beyond standard TypeSpec scalars)
// ============================================================================

string_enum! {
    /// Custom Protobuf scalar types.
    /// These extend standard TypeSpec integer types with Protobuf-specific encodings.
    pub enum ProtobufScalarKind {
        /// signed int32 (sint32 encoding)
        Sint32 => "sint32",
        /// signed int64 (sint64 encoding)
        Sint64 => "sint64",
        /// signed fixed 32 (sfixed32 encoding)
        Sfixed32 => "sfixed32",
        /// signed fixed 64 (sfixed64 encoding)
        Sfixed64 => "sfixed64",
        /// unsigned fixed 32 (fixed32 encoding)
        Fixed32 => "fixed32",
        /// unsigned fixed 64 (fixed64 encoding)
        Fixed64 => "fixed64",
    }
}

impl ProtobufScalarKind {
    /// Get the parent TypeSpec scalar
    pub fn extends_scalar(&self) -> &'static str {
        match self {
            ProtobufScalarKind::Sint32 | ProtobufScalarKind::Sfixed32 => "int32",
            ProtobufScalarKind::Sint64 | ProtobufScalarKind::Sfixed64 => "int64",
            ProtobufScalarKind::Fixed32 => "uint32",
            ProtobufScalarKind::Fixed64 => "uint64",
        }
    }

    /// Get all custom protobuf scalar kinds
    pub fn all() -> &'static [ProtobufScalarKind] {
        &[
            ProtobufScalarKind::Sint32,
            ProtobufScalarKind::Sint64,
            ProtobufScalarKind::Sfixed32,
            ProtobufScalarKind::Sfixed64,
            ProtobufScalarKind::Fixed32,
            ProtobufScalarKind::Fixed64,
        ]
    }
}

// ============================================================================
// Field reservation types
// ============================================================================

/// A field reservation entry.
/// Ported from TS @reserve decorator arguments.
#[derive(Debug, Clone, PartialEq)]
pub enum FieldReservation {
    /// Reserved field name
    Name(String),
    /// Reserved field index
    Index(u32),
    /// Reserved field index range (inclusive)
    Range(u32, u32),
}

impl FieldReservation {
    /// Check if a field index falls within this reservation
    pub fn contains_index(&self, index: u32) -> bool {
        match self {
            FieldReservation::Name(_) => false,
            FieldReservation::Index(i) => *i == index,
            FieldReservation::Range(start, end) => index >= *start && index <= *end,
        }
    }

    /// Check if a field name matches this reservation
    pub fn contains_name(&self, name: &str) -> bool {
        match self {
            FieldReservation::Name(n) => n == name,
            _ => false,
        }
    }
}

/// Protobuf field index constraints
pub const FIELD_INDEX_MIN: u32 = 1;
pub const FIELD_INDEX_MAX: u32 = 536870911; // 2^29 - 1
/// Implementation-reserved range
pub const FIELD_INDEX_RESERVED_MIN: u32 = 19000;
pub const FIELD_INDEX_RESERVED_MAX: u32 = 19999;

/// Check if a field index is valid (not in reserved range)
pub fn is_valid_field_index(index: u32) -> bool {
    (FIELD_INDEX_MIN..=FIELD_INDEX_MAX).contains(&index)
        && !(FIELD_INDEX_RESERVED_MIN..=FIELD_INDEX_RESERVED_MAX).contains(&index)
}

/// Check if a field index is reserved by the user
pub fn is_user_reserved(index: u32, reservations: &[FieldReservation]) -> bool {
    reservations.iter().any(|r| r.contains_index(index))
}

/// Check if a field name is reserved by the user
pub fn is_name_reserved(name: &str, reservations: &[FieldReservation]) -> bool {
    reservations.iter().any(|r| r.contains_name(name))
}

// ============================================================================
// Protobuf identifier validation
// ============================================================================

/// Protobuf full identifier regex.
/// Defined in the [ProtoBuf Language Spec](https://developers.google.com/protocol-buffers/docs/reference/proto3-spec#identifiers).
/// ident = letter { letter | decimalDigit | "_" }
/// fullIdent = ident { "." ident }
pub const PROTO_FULL_IDENT: &str = r"([a-zA-Z][a-zA-Z0-9_]*)+";

/// Check if a string is a valid Protobuf package name.
/// Must consist of letters and numbers separated by ".".
pub fn is_valid_proto_package_name(name: &str) -> bool {
    if name.is_empty() {
        return false;
    }
    for segment in name.split('.') {
        if segment.is_empty() {
            return false;
        }
        let chars: Vec<char> = segment.chars().collect();
        if !chars[0].is_ascii_alphabetic() {
            return false;
        }
        if !chars.iter().all(|c| c.is_ascii_alphanumeric() || *c == '_') {
            return false;
        }
    }
    true
}

// ============================================================================
// Decorator implementations
// ============================================================================

flag_decorator!(apply_message, is_message, STATE_MESSAGE);
flag_decorator!(apply_service, is_service, STATE_SERVICE);

/// Implementation of the `@package` decorator.
/// Associates a namespace with a Protobuf package.
/// Ported from TS $package.
pub fn apply_package(state: &mut StateAccessors, target: TypeId, details: Option<&PackageDetails>) {
    let value = details
        .as_ref()
        .map(|d| d.name.as_deref().unwrap_or(""))
        .unwrap_or("");
    state.set_state(STATE_PACKAGE, target, value.to_string());
}

/// Get the package details for a namespace.
pub fn get_package(state: &StateAccessors, target: TypeId) -> Option<String> {
    state
        .get_state(STATE_PACKAGE, target)
        .map(|s| s.to_string())
}

/// Implementation of the `@field` decorator.
/// Sets the field index for a model property.
/// Ported from TS $field.
/// Returns Ok(()) if valid, or Err(diag_code) if invalid.
pub fn apply_field(
    state: &mut StateAccessors,
    target: TypeId,
    field_index: u32,
) -> Result<(), &'static str> {
    if !is_valid_field_index(field_index) {
        if field_index == 0 || !((FIELD_INDEX_MIN..=FIELD_INDEX_MAX).contains(&field_index)) {
            if field_index == 0 {
                return Err(DIAG_FIELD_INDEX_INVALID);
            }
            return Err(DIAG_FIELD_INDEX_OUT_OF_BOUNDS);
        }
        if (FIELD_INDEX_RESERVED_MIN..=FIELD_INDEX_RESERVED_MAX).contains(&field_index) {
            return Err(DIAG_FIELD_INDEX_RESERVED);
        }
    }
    state.set_state(STATE_FIELD_INDEX, target, field_index.to_string());
    Ok(())
}

/// Get the field index for a model property.
pub fn get_field_index(state: &StateAccessors, target: TypeId) -> Option<u32> {
    state
        .get_state(STATE_FIELD_INDEX, target)
        .and_then(|s| s.parse::<u32>().ok())
}

/// Implementation of the `@stream` decorator.
/// Sets the streaming mode for an operation.
/// Ported from TS $stream.
pub fn apply_stream(state: &mut StateAccessors, target: TypeId, mode: StreamMode) {
    state.set_state(STATE_STREAM, target, mode.as_str().to_string());
}

/// Get the streaming mode for an operation.
pub fn get_stream_mode(state: &StateAccessors, target: TypeId) -> Option<StreamMode> {
    state
        .get_state(STATE_STREAM, target)
        .and_then(StreamMode::parse_str)
}

/// Implementation of the `@reserve` decorator.
/// Stores field reservations for a type.
/// Ported from TS $reserve.
pub fn apply_reserve(
    state: &mut StateAccessors,
    target: TypeId,
    reservations: &[FieldReservation],
) {
    // Serialize reservations as semicolon-separated entries
    let serialized: String = reservations
        .iter()
        .map(|r| match r {
            FieldReservation::Name(n) => format!("n:{}", n),
            FieldReservation::Index(i) => format!("i:{}", i),
            FieldReservation::Range(s, e) => format!("r:{}-{}", s, e),
        })
        .collect::<Vec<_>>()
        .join(";");
    state.set_state(STATE_RESERVE, target, serialized);
}

/// Get field reservations for a type.
pub fn get_reservations(state: &StateAccessors, target: TypeId) -> Vec<FieldReservation> {
    state
        .get_state(STATE_RESERVE, target)
        .map(|s| {
            if s.is_empty() {
                return Vec::new();
            }
            s.split(';')
                .filter_map(|entry| {
                    let parts: Vec<&str> = entry.splitn(2, ':').collect();
                    if parts.len() != 2 {
                        return None;
                    }
                    match parts[0] {
                        "n" => Some(FieldReservation::Name(parts[1].to_string())),
                        "i" => parts[1].parse::<u32>().ok().map(FieldReservation::Index),
                        "r" => {
                            let range_parts: Vec<&str> = parts[1].splitn(2, '-').collect();
                            if range_parts.len() == 2 {
                                let start = range_parts[0].parse::<u32>().ok()?;
                                let end = range_parts[1].parse::<u32>().ok()?;
                                Some(FieldReservation::Range(start, end))
                            } else {
                                None
                            }
                        }
                        _ => None,
                    }
                })
                .collect()
        })
        .unwrap_or_default()
}

flag_decorator!(apply_map, is_map, STATE_MAP);

/// Implementation of the internal `@externRef` decorator.
/// Stores an external Protobuf reference.
/// Ported from TS $externRef.
pub fn apply_extern_ref(state: &mut StateAccessors, target: TypeId, path: &str, name: &str) {
    state.set_state(STATE_EXTERN_REF, target, format!("{}|{}", path, name));
}

/// Get the external Protobuf reference for a model.
/// Returns (path, name) if found.
pub fn get_extern_ref(state: &StateAccessors, target: TypeId) -> Option<(String, String)> {
    state.get_state(STATE_EXTERN_REF, target).and_then(|s| {
        let parts: Vec<&str> = s.splitn(2, '|').collect();
        if parts.len() == 2 {
            Some((parts[0].to_string(), parts[1].to_string()))
        } else {
            None
        }
    })
}

// ============================================================================
// PackageDetails type
// ============================================================================

/// Details for a Protobuf package definition.
/// Ported from TS PackageDetails model.
#[derive(Debug, Clone)]
pub struct PackageDetails {
    /// The package name
    pub name: Option<String>,
    /// Package options
    pub options: Vec<(String, PackageOptionValue)>,
}

/// Value types for package options
#[derive(Debug, Clone, PartialEq)]
pub enum PackageOptionValue {
    /// String option value
    String(String),
    /// Boolean option value
    Boolean(bool),
    /// Numeric option value
    Numeric(f64),
}

// ============================================================================
// Emitter options
// ============================================================================

/// Protobuf emitter options.
/// Ported from TS ProtobufEmitterOptions interface.
#[derive(Debug, Clone, Default)]
pub struct ProtobufEmitterOptions {
    /// Don't emit anything
    pub no_emit: bool,
    /// Omit unreachable types
    pub omit_unreachable_types: bool,
}

// ============================================================================
// Protobuf type mapping
// ============================================================================

/// Mapping from TypeSpec scalar to Protobuf scalar type name.
/// Ported from TS proto.ts conversions.
pub fn typespec_scalar_to_proto(scalar_name: &str) -> Option<&'static str> {
    match scalar_name {
        "boolean" => Some("bool"),
        "string" => Some("string"),
        "bytes" => Some("bytes"),
        "int8" | "int16" | "int32" => Some("int32"),
        "int64" => Some("int64"),
        "uint8" | "uint16" | "uint32" => Some("uint32"),
        "uint64" => Some("uint64"),
        "safeint" => Some("int64"),
        "float32" => Some("float"),
        "float64" => Some("double"),
        "sint32" => Some("sint32"),
        "sint64" => Some("sint64"),
        "sfixed32" => Some("sfixed32"),
        "sfixed64" => Some("sfixed64"),
        "fixed32" => Some("fixed32"),
        "fixed64" => Some("fixed64"),
        _ => None,
    }
}

// ============================================================================
// Proto3 optional label logic
// ============================================================================

/// Result of checking whether an optional label should be emitted for a field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OptionalLabelDecision {
    /// Emit `optional` keyword
    Emit,
    /// Do NOT emit `optional` keyword (array/Map types in proto3)
    Skip,
    /// Do NOT emit `optional` and emit a warning (optional + array)
    WarnArray,
    /// Do NOT emit `optional` and emit a warning (optional + map)
    WarnMap,
}

/// Determine whether a proto3 field should emit the `optional` keyword.
///
/// Rules (ported from upstream TypeSpec protobuf emitter):
/// - In proto2, `optional` is always emitted for optional fields
/// - In proto3:
///   - Array fields (model with indexer) should NOT emit `optional`
///   - Map fields should NOT emit `optional`
///   - Other optional fields SHOULD emit `optional`
///   - `optional` + array is discouraged → warning
///   - `optional` + map is discouraged → warning
///
/// Parameters:
/// - `is_optional`: whether the TypeSpec property is optional
/// - `field_type_id`: the TypeId of the field's type
/// - `syntax`: the protobuf syntax version
/// - `checker`: the type checker for resolving types
pub fn should_emit_optional_label(
    is_optional: bool,
    field_type_id: TypeId,
    syntax: ProtoSyntax,
    checker: &crate::checker::Checker,
) -> OptionalLabelDecision {
    if !is_optional {
        return OptionalLabelDecision::Skip;
    }

    if syntax == ProtoSyntax::Proto2 {
        return OptionalLabelDecision::Emit;
    }

    // proto3: check if the field type is array or map
    let resolved = checker.resolve_alias_chain(field_type_id);

    if is_array_type(checker, resolved) {
        return OptionalLabelDecision::WarnArray;
    }

    if is_map_type(checker, resolved) {
        return OptionalLabelDecision::WarnMap;
    }

    OptionalLabelDecision::Emit
}

/// Check if a type is an array type (model with indexer).
fn is_array_type(checker: &crate::checker::Checker, type_id: TypeId) -> bool {
    match checker.get_type(type_id) {
        Some(crate::checker::types::Type::Model(m)) => m.indexer.is_some() && !is_map_type(checker, type_id),
        _ => false,
    }
}

/// Check if a type is a Protobuf Map type.
fn is_map_type(checker: &crate::checker::Checker, type_id: TypeId) -> bool {
    match checker.get_type(type_id) {
        Some(crate::checker::types::Type::Model(m)) => {
            is_map(&checker.state_accessors, m.id)
        }
        _ => false,
    }
}

// ============================================================================
// Library creation
// ============================================================================

/// Create the @typespec/protobuf library diagnostic map.
/// Ported from TS TypeSpecProtobufLibrary definition in lib.ts.
pub fn create_protobuf_library() -> DiagnosticMap {
    HashMap::from([
        (
            "field-index".to_string(),
            DiagnosticDefinition::error_with_messages(vec![
                (
                    "missing",
                    "field {name} does not have a field index, but one is required (try using the '@field' decorator)",
                ),
                (
                    "invalid",
                    "field index {index} is invalid (must be an integer greater than zero)",
                ),
                (
                    "out-of-bounds",
                    "field index {index} is out of bounds (must be less than {max})",
                ),
                (
                    "reserved",
                    "field index {index} falls within the implementation-reserved range of 19000-19999 inclusive",
                ),
                (
                    "user-reserved",
                    "field index {index} was reserved by a call to @reserve on this model",
                ),
                (
                    "user-reserved-range",
                    "field index {index} falls within a range reserved by a call to @reserve on this model",
                ),
            ]),
        ),
        (
            "field-name".to_string(),
            DiagnosticDefinition::error_with_messages(vec![(
                "user-reserved",
                "field name '{name}' was reserved by a call to @reserve on this model",
            )]),
        ),
        (
            DIAG_ROOT_OPERATION.to_string(),
            DiagnosticDefinition::error(
                "operations in the root namespace are not supported (no associated Protobuf service)",
            ),
        ),
        (
            DIAG_UNSUPPORTED_INTRINSIC.to_string(),
            DiagnosticDefinition::error("intrinsic type {name} is not supported in Protobuf"),
        ),
        (
            DIAG_UNSUPPORTED_RETURN_TYPE.to_string(),
            DiagnosticDefinition::error("Protobuf methods must return a named Model"),
        ),
        (
            DIAG_UNSUPPORTED_INPUT_TYPE.to_string(),
            DiagnosticDefinition::error_with_messages(vec![
                (
                    "wrong-number",
                    "Protobuf methods must accept exactly one Model input (an empty model will do)",
                ),
                (
                    "wrong-type",
                    "Protobuf methods may only accept a named Model as an input",
                ),
                (
                    "unconvertible",
                    "input parameters cannot be converted to a Protobuf message",
                ),
            ]),
        ),
        (
            DIAG_UNSUPPORTED_FIELD_TYPE.to_string(),
            DiagnosticDefinition::error_with_messages(vec![
                (
                    "unconvertible",
                    "cannot convert a {type} to a protobuf type (only intrinsic types and models are supported)",
                ),
                (
                    "unknown-intrinsic",
                    "no known protobuf scalar for intrinsic type {name}",
                ),
                (
                    "unknown-scalar",
                    "no known protobuf scalar for TypeSpec scalar type {name}",
                ),
                (
                    "recursive-map",
                    "a protobuf map's 'value' type may not refer to another map",
                ),
                ("union", "a message field's type may not be a union"),
            ]),
        ),
        (
            DIAG_NAMESPACE_COLLISION.to_string(),
            DiagnosticDefinition::error("the package name {name} has already been used"),
        ),
        (
            DIAG_UNCONVERTIBLE_ENUM.to_string(),
            DiagnosticDefinition::error_with_messages(vec![
                (
                    "default",
                    "enums must explicitly assign exactly one integer to each member to be used in a Protobuf message",
                ),
                (
                    "no-zero-first",
                    "the first variant of an enum must be set to zero to be used in a Protobuf message",
                ),
            ]),
        ),
        (
            DIAG_NESTED_ARRAY.to_string(),
            DiagnosticDefinition::error("nested arrays are not supported by the Protobuf emitter"),
        ),
        (
            DIAG_INVALID_PACKAGE_NAME.to_string(),
            DiagnosticDefinition::error(
                "{name} is not a valid package name (must consist of letters and numbers separated by \".\")",
            ),
        ),
        (
            DIAG_ILLEGAL_RESERVATION.to_string(),
            DiagnosticDefinition::error(
                "reservation value must be a string literal, uint32 literal, or a tuple of two uint32 literals denoting a range",
            ),
        ),
        (
            DIAG_MODEL_NOT_IN_PACKAGE.to_string(),
            DiagnosticDefinition::error(
                "model {name} is not in a namespace that uses the '@Protobuf.package' decorator",
            ),
        ),
        (
            DIAG_ANONYMOUS_MODEL.to_string(),
            DiagnosticDefinition::error("anonymous models cannot be used in Protobuf messages"),
        ),
        (
            DIAG_UNSPEAKABLE_TEMPLATE_ARGUMENT.to_string(),
            DiagnosticDefinition::error(
                "template {name} cannot be converted to a Protobuf message because it has an unspeakable argument (try using the '@friendlyName' decorator on the template)",
            ),
        ),
        (
            DIAG_PACKAGE.to_string(),
            DiagnosticDefinition::error_with_messages(vec![(
                "disallowed-option-type",
                "option '{name}' with type '{type}' is not allowed in a package declaration (only string, boolean, and numeric types are allowed)",
            )]),
        ),
        (
            DIAG_OPTIONAL_ARRAY_FIELD.to_string(),
            DiagnosticDefinition::warning(
                "optional on an array field has no effect in proto3 and is not recommended",
            ),
        ),
        (
            DIAG_OPTIONAL_MAP_FIELD.to_string(),
            DiagnosticDefinition::warning(
                "optional on a map field has no effect in proto3 and is not recommended",
            ),
        ),
    ])
}

// ============================================================================
// TSP Sources
// ============================================================================

/// The TypeSpec source for the Protobuf library (proto.tsp)
pub const PROTOBUF_TSP: &str = r#"
import "../dist/src/tsp-index.js";

namespace TypeSpec.Protobuf;

/**
 * A model that represents an external Protobuf reference.
 * @template Path the relative path to a .proto file to import
 * @template Name the fully-qualified reference to the type
 */
@Private.externRef(Path, Name)
model Extern<Path extends string, Name extends string> {
  _extern: never;
}

/**
 * Contains some common well-known Protobuf types defined by the google.protobuf library.
 */
namespace WellKnown {
  model Empty is Extern<"google/protobuf/empty.proto", "google.protobuf.Empty">;
  model Timestamp is Extern<"google/protobuf/timestamp.proto", "google.protobuf.Timestamp">;
  model Any is Extern<"google/protobuf/any.proto", "google.protobuf.Any">;
  model LatLng is Extern<"google/type/latlng.proto", "google.type.LatLng">;
}

scalar sint32 extends int32;
scalar sint64 extends int64;
scalar sfixed32 extends int32;
scalar sfixed64 extends int64;
scalar fixed32 extends uint32;
scalar fixed64 extends uint64;

alias integral = int32 | int64 | uint32 | uint64 | boolean;

@Private._map
model Map<Key extends integral | string, Value> {}

extern dec message(target: {});
extern dec field(target: TypeSpec.Reflection.ModelProperty, index: valueof uint32);
extern dec reserve(target: {}, ...reservations: valueof (string | [uint32, uint32] | uint32)[]);
extern dec service(target: TypeSpec.Reflection.Interface);

model PackageDetails {
  name?: string;
  options?: Record<string | boolean | numeric>;
}

extern dec `package`(target: TypeSpec.Reflection.Namespace, details?: PackageDetails);

enum StreamMode {
  Duplex,
  In,
  Out,
  None,
}

extern dec stream(target: TypeSpec.Reflection.Operation, mode: StreamMode);

namespace Private {
  extern dec externRef(target: Reflection.Model, path: string, name: string);
  extern dec _map(target: Reflection.Model);
}
"#;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_protobuf_namespace() {
        assert_eq!(PROTOBUF_NAMESPACE, "TypeSpec.Protobuf");
    }

    #[test]
    fn test_create_protobuf_library() {
        let diags = create_protobuf_library();
        assert!(diags.len() >= 15);
        let codes: Vec<&str> = diags.keys().map(|code| code.as_str()).collect();
        assert!(codes.contains(&"field-index"));
        assert!(codes.contains(&DIAG_UNSUPPORTED_FIELD_TYPE));
        assert!(codes.contains(&DIAG_NESTED_ARRAY));
    }

    #[test]
    fn test_stream_mode() {
        assert_eq!(StreamMode::Duplex.as_str(), "Duplex");
        assert_eq!(StreamMode::parse_str("Duplex"), Some(StreamMode::Duplex));
        assert_eq!(StreamMode::parse_str("In"), Some(StreamMode::In));
        assert_eq!(StreamMode::parse_str("Out"), Some(StreamMode::Out));
        assert_eq!(StreamMode::parse_str("None"), Some(StreamMode::None));
        assert_eq!(StreamMode::parse_str("unknown"), None);
    }

    #[test]
    fn test_protobuf_scalar_kinds() {
        for kind in ProtobufScalarKind::all() {
            assert!(!kind.as_str().is_empty());
            assert!(!kind.extends_scalar().is_empty());
        }
    }

    #[test]
    fn test_field_reservation() {
        let reservations = vec![
            FieldReservation::Name("test".to_string()),
            FieldReservation::Index(100),
            FieldReservation::Range(8, 15),
        ];

        assert!(is_name_reserved("test", &reservations));
        assert!(!is_name_reserved("other", &reservations));
        assert!(is_user_reserved(100, &reservations));
        assert!(is_user_reserved(10, &reservations)); // in range 8-15
        assert!(!is_user_reserved(7, &reservations));
        assert!(!is_user_reserved(16, &reservations));
    }

    #[test]
    fn test_valid_field_indices() {
        assert!(is_valid_field_index(1));
        assert!(is_valid_field_index(15));
        assert!(is_valid_field_index(18999));
        assert!(is_valid_field_index(20000));
        assert!(!is_valid_field_index(0));
        assert!(!is_valid_field_index(19000)); // reserved
        assert!(!is_valid_field_index(19999)); // reserved
        assert!(!is_valid_field_index(536870912)); // too large
    }

    #[test]
    fn test_typespec_to_proto_mapping() {
        assert_eq!(typespec_scalar_to_proto("boolean"), Some("bool"));
        assert_eq!(typespec_scalar_to_proto("string"), Some("string"));
        assert_eq!(typespec_scalar_to_proto("int32"), Some("int32"));
        assert_eq!(typespec_scalar_to_proto("int64"), Some("int64"));
        assert_eq!(typespec_scalar_to_proto("float32"), Some("float"));
        assert_eq!(typespec_scalar_to_proto("float64"), Some("double"));
        assert_eq!(typespec_scalar_to_proto("sint32"), Some("sint32"));
        assert_eq!(typespec_scalar_to_proto("fixed32"), Some("fixed32"));
        assert_eq!(typespec_scalar_to_proto("unknown"), None);
    }

    #[test]
    fn test_protobuf_tsp_not_empty() {
        assert!(!PROTOBUF_TSP.is_empty());
        assert!(PROTOBUF_TSP.contains("Extern"));
        assert!(PROTOBUF_TSP.contains("sint32"));
        assert!(PROTOBUF_TSP.contains("Map"));
        assert!(PROTOBUF_TSP.contains("StreamMode"));
        assert!(PROTOBUF_TSP.contains("message"));
        assert!(PROTOBUF_TSP.contains("field"));
        assert!(PROTOBUF_TSP.contains("reserve"));
        assert!(PROTOBUF_TSP.contains("service"));
    }

    #[test]
    fn test_package_details() {
        let details = PackageDetails {
            name: Some("test.package".to_string()),
            options: vec![
                (
                    "java_package".to_string(),
                    PackageOptionValue::String("com.test".to_string()),
                ),
                ("optimize_for".to_string(), PackageOptionValue::Numeric(1.0)),
            ],
        };
        assert_eq!(details.name, Some("test.package".to_string()));
        assert_eq!(details.options.len(), 2);
    }

    #[test]
    fn test_is_valid_proto_package_name() {
        assert!(is_valid_proto_package_name("com.example"));
        assert!(is_valid_proto_package_name("google.protobuf"));
        assert!(is_valid_proto_package_name("a"));
        assert!(!is_valid_proto_package_name(""));
        assert!(!is_valid_proto_package_name(".example"));
        assert!(!is_valid_proto_package_name("example."));
        assert!(!is_valid_proto_package_name("123.example"));
        assert!(!is_valid_proto_package_name("com.123"));
    }

    #[test]
    fn test_apply_and_is_message() {
        let mut state = StateAccessors::new();
        assert!(!is_message(&state, 1));
        apply_message(&mut state, 1);
        assert!(is_message(&state, 1));
        assert!(!is_message(&state, 2));
    }

    #[test]
    fn test_apply_and_is_service() {
        let mut state = StateAccessors::new();
        assert!(!is_service(&state, 1));
        apply_service(&mut state, 1);
        assert!(is_service(&state, 1));
    }

    #[test]
    fn test_apply_field_valid() {
        let mut state = StateAccessors::new();
        let result = apply_field(&mut state, 1, 1);
        assert!(result.is_ok());
        assert_eq!(get_field_index(&state, 1), Some(1));
    }

    #[test]
    fn test_apply_field_zero() {
        let mut state = StateAccessors::new();
        let result = apply_field(&mut state, 1, 0);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), DIAG_FIELD_INDEX_INVALID);
    }

    #[test]
    fn test_apply_field_reserved() {
        let mut state = StateAccessors::new();
        let result = apply_field(&mut state, 1, 19000);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), DIAG_FIELD_INDEX_RESERVED);
    }

    #[test]
    fn test_apply_stream() {
        let mut state = StateAccessors::new();
        apply_stream(&mut state, 1, StreamMode::Duplex);
        assert_eq!(get_stream_mode(&state, 1), Some(StreamMode::Duplex));

        apply_stream(&mut state, 2, StreamMode::Out);
        assert_eq!(get_stream_mode(&state, 2), Some(StreamMode::Out));
    }

    #[test]
    fn test_apply_and_get_reservations() {
        let mut state = StateAccessors::new();
        let reservations = vec![
            FieldReservation::Name("test".to_string()),
            FieldReservation::Index(100),
            FieldReservation::Range(8, 15),
        ];
        apply_reserve(&mut state, 1, &reservations);

        let retrieved = get_reservations(&state, 1);
        assert_eq!(retrieved.len(), 3);
        assert!(
            retrieved
                .iter()
                .any(|r| matches!(r, FieldReservation::Name(n) if n == "test"))
        );
        assert!(
            retrieved
                .iter()
                .any(|r| matches!(r, FieldReservation::Index(100)))
        );
        assert!(
            retrieved
                .iter()
                .any(|r| matches!(r, FieldReservation::Range(8, 15)))
        );
    }

    #[test]
    fn test_apply_and_is_map() {
        let mut state = StateAccessors::new();
        assert!(!is_map(&state, 1));
        apply_map(&mut state, 1);
        assert!(is_map(&state, 1));
    }

    #[test]
    fn test_apply_and_get_extern_ref() {
        let mut state = StateAccessors::new();
        apply_extern_ref(
            &mut state,
            1,
            "google/protobuf/empty.proto",
            "google.protobuf.Empty",
        );

        let result = get_extern_ref(&state, 1);
        assert!(result.is_some());
        let (path, name) = result.unwrap();
        assert_eq!(path, "google/protobuf/empty.proto");
        assert_eq!(name, "google.protobuf.Empty");
    }

    #[test]
    fn test_apply_package() {
        let mut state = StateAccessors::new();
        let details = PackageDetails {
            name: Some("test.package".to_string()),
            options: vec![],
        };
        apply_package(&mut state, 1, Some(&details));
        assert_eq!(get_package(&state, 1), Some("test.package".to_string()));

        apply_package(&mut state, 2, None);
        assert_eq!(get_package(&state, 2), Some("".to_string()));
    }

    #[test]
    fn test_optional_label_non_optional_field() {
        let checker = crate::checker::Checker::new();
        let result = should_emit_optional_label(false, 0, ProtoSyntax::Proto3, &checker);
        assert_eq!(result, OptionalLabelDecision::Skip);
    }

    #[test]
    fn test_optional_label_proto2() {
        let checker = crate::checker::Checker::new();
        let result = should_emit_optional_label(true, 0, ProtoSyntax::Proto2, &checker);
        assert_eq!(result, OptionalLabelDecision::Emit);
    }

    #[test]
    fn test_optional_label_proto3_simple_type() {
        let mut checker = crate::checker::Checker::new();
        let string_type = crate::checker::types::Type::String(crate::checker::types::StringType {
            id: checker.next_type_id(),
            value: String::new(),
            node: None,
            is_finished: true,
        });
        let string_id = checker.create_type(string_type);
        let result = should_emit_optional_label(true, string_id, ProtoSyntax::Proto3, &checker);
        assert_eq!(result, OptionalLabelDecision::Emit);
    }

    #[test]
    fn test_optional_label_proto3_array_type() {
        let mut checker = crate::checker::Checker::new();
        let array_model = crate::checker::types::Type::Model(crate::checker::types::ModelType::new(
            checker.next_type_id(),
            "string[]".to_string(),
            None,
            None,
        ));
        let array_id = checker.create_type(array_model);
        if let Some(crate::checker::types::Type::Model(m)) = checker.get_type_mut(array_id) {
            m.indexer = Some((0, 0));
        }
        let result = should_emit_optional_label(true, array_id, ProtoSyntax::Proto3, &checker);
        assert_eq!(result, OptionalLabelDecision::WarnArray);
    }

    #[test]
    fn test_optional_label_proto3_map_type() {
        let mut checker = crate::checker::Checker::new();
        let map_model = crate::checker::types::Type::Model(crate::checker::types::ModelType::new(
            checker.next_type_id(),
            "Map".to_string(),
            None,
            None,
        ));
        let map_id = checker.create_type(map_model);
        if let Some(crate::checker::types::Type::Model(m)) = checker.get_type_mut(map_id) {
            m.indexer = Some((0, 0));
        }
        // Mark as protobuf map
        apply_map(&mut checker.state_accessors, map_id);
        let result = should_emit_optional_label(true, map_id, ProtoSyntax::Proto3, &checker);
        assert_eq!(result, OptionalLabelDecision::WarnMap);
    }

    #[test]
    fn test_proto_syntax_default() {
        assert_eq!(ProtoSyntax::default(), ProtoSyntax::Proto3);
    }
}