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
use camo_core as camo;
use std::{convert::TryFrom, fmt};

/// A top-level type definition.
#[derive(Clone, Debug, PartialEq)]
pub enum Definition {
    /// An interface definition.
    Interface(Interface),
    /// A type definition.
    Alias(TypeAlias),
}

impl Definition {
    /// The name of the type definition.
    pub fn name(&self) -> &str {
        match self {
            Definition::Interface(i) => &i.name,
            Definition::Alias(a) => &a.name,
        }
    }

    /// `true` if the type definition is exported.
    pub fn export(&self) -> bool {
        match self {
            Definition::Interface(i) => i.export,
            Definition::Alias(a) => a.export,
        }
    }
}

impl From<Interface> for Definition {
    fn from(value: Interface) -> Self {
        Definition::Interface(value)
    }
}

impl From<TypeAlias> for Definition {
    fn from(value: TypeAlias) -> Self {
        Definition::Alias(value)
    }
}

#[derive(Clone, Copy)]
struct Renamer(Option<camo::RenameRule>);

impl Renamer {
    fn rename_field(&self, name: &str) -> String {
        let Self(rule) = self;
        match rule {
            Some(camo::RenameRule::LowerCase) => name.to_lowercase(),
            Some(camo::RenameRule::UpperCase) => name.to_uppercase(),
            Some(camo::RenameRule::PascalCase) => snake_to_non_snake_case(true, name),
            Some(camo::RenameRule::CamelCase) => snake_to_non_snake_case(false, name),
            Some(camo::RenameRule::SnakeCase) => name.to_string(),
            Some(camo::RenameRule::ScreamingSnakeCase) => name.to_uppercase(),
            Some(camo::RenameRule::KebabCase) => name.replace('_', "-"),
            Some(camo::RenameRule::ScreamingKebabCase) => name.to_uppercase().replace('_', "-"),
            None => name.to_string(),
        }
    }

    fn rename_type(&self, name: &str) -> String {
        let Self(rule) = self;
        match rule {
            Some(camo::RenameRule::LowerCase) => name.to_lowercase(),
            Some(camo::RenameRule::UpperCase) => name.to_uppercase(),
            Some(camo::RenameRule::PascalCase) => name.to_string(),
            Some(camo::RenameRule::CamelCase) => name[..1].to_ascii_lowercase() + &name[1..],
            Some(camo::RenameRule::SnakeCase) => pascal_to_separated_case('_', name),
            Some(camo::RenameRule::ScreamingSnakeCase) => {
                pascal_to_separated_case('_', name).to_uppercase()
            }
            Some(camo::RenameRule::KebabCase) => pascal_to_separated_case('-', name),
            Some(camo::RenameRule::ScreamingKebabCase) => {
                pascal_to_separated_case('-', name).to_uppercase()
            }
            None => name.to_string(),
        }
    }
}

fn snake_to_non_snake_case(capitalize_first: bool, field: &str) -> String {
    let mut result = String::new();
    let mut capitalize = capitalize_first;
    for ch in field.chars() {
        if ch == '_' {
            capitalize = true;
        } else if capitalize {
            result.push(ch.to_ascii_uppercase());
            capitalize = false;
        } else {
            result.push(ch);
        }
    }
    result
}

fn pascal_to_separated_case(separator: char, name: &str) -> String {
    let mut result = String::new();
    for (i, ch) in name.char_indices() {
        if i > 0 && ch.is_uppercase() {
            result.push(separator);
        }
        result.push(ch.to_ascii_lowercase());
    }
    result
}

impl From<camo::Container> for Definition {
    fn from(container: camo::Container) -> Self {
        let rename = Renamer(container.attributes.rename);
        let rename_all = Renamer(container.attributes.rename_all);
        let tag_rule = container.attributes.tag;
        let content_rule = container.attributes.content;

        match container.item {
            camo::Item::Struct(s) => match s.content {
                camo::StructContent::NamedFields(fields) => Definition::Interface(Interface {
                    export: s.visibility.is_pub(),
                    name: rename.rename_type(s.name),
                    parameters: s
                        .parameters
                        .into_iter()
                        .filter_map(|parameter| match parameter {
                            // Lifetimes are ignored
                            camo::GenericParameter::Lifetime(_) => None,
                            camo::GenericParameter::Type(ty) => Some(ty),
                        })
                        .collect(),
                    fields: fields
                        .into_iter()
                        .map(|field| Field {
                            name: rename_all.rename_field(field.name),
                            ty: Type::from(field.ty),
                        })
                        .collect(),
                }),
                camo::StructContent::UnnamedField(field) => {
                    Definition::Alias(TypeAlias {
                        export: s.visibility.is_pub(),
                        name: rename.rename_type(s.name),
                        parameters: s
                            .parameters
                            .into_iter()
                            .filter_map(|parameter| match parameter {
                                // Lifetimes are ignored
                                camo::GenericParameter::Lifetime(_) => None,
                                camo::GenericParameter::Type(ty) => Some(ty),
                            })
                            .collect(),
                        ty: Type::from(field.ty),
                    })
                }
            },
            camo::Item::Enum(ty) => Definition::Alias(if let Some(tag) = tag_rule {
                if let Some(content) = content_rule {
                    TypeAlias::adjacently_tagged(rename, rename_all, tag, content, ty)
                } else {
                    TypeAlias::internally_tagged(rename, rename_all, tag, ty)
                }
            } else {
                TypeAlias::externally_tagged(rename, rename_all, ty)
            }),
        }
    }
}

impl fmt::Display for Definition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Definition::Interface(ty) => write!(f, "{}", ty),
            Definition::Alias(ty) => write!(f, "{}", ty),
        }
    }
}

/// A top-level `interface` definition.
///
/// Example:
///
/// ```ts
/// interface Foo {
///     value: number;
/// }
/// ```
///
/// See: <https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#interfaces>
#[derive(Clone, Debug, PartialEq)]
pub struct Interface {
    /// Whether the interface is marked with `export`.
    pub export: bool,
    /// The name of the interface.
    pub name: String,
    /// The generic parameters of the interface.
    pub parameters: Vec<&'static str>,
    /// The fields of the interface.
    pub fields: Vec<Field>,
}

impl fmt::Display for Interface {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.export {
            write!(f, "export ")?;
        }
        write!(f, "interface {}", self.name)?;
        if !self.parameters.is_empty() {
            write!(f, "<")?;
            for parameter in &self.parameters {
                write!(f, "{}", parameter)?;
            }
            write!(f, ">")?;
        }
        writeln!(f, " {{")?;
        for field in &self.fields {
            writeln!(f, "\t{}", field)?;
        }
        writeln!(f, "}}")
    }
}

/// A field in e.g. an interface or an object type.
#[derive(Clone, Debug, PartialEq)]
pub struct Field {
    /// The name of the field.
    pub name: String,
    /// The type of the field.
    pub ty: Type,
}

impl fmt::Display for Field {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if is_valid_identifier(self.name.as_str()) {
            write!(f, "{name}: {ty};", name = self.name, ty = self.ty)
        } else {
            write!(f, r#"'{name}': {ty};"#, name = self.name, ty = self.ty)
        }
    }
}

fn is_valid_identifier(string: &str) -> bool {
    let mut chars = string.chars();
    if let Some(c) = chars.next() {
        if !c.is_alphabetic() && c != '_' {
            return false;
        }
    }
    chars.all(|c| c.is_alphanumeric() || c == '_')
}

/// A top-level `type` definition.
/// Example:
///
/// ```ts
/// type Foo = { value: number };
/// ```
///
/// See: <https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-aliases>
#[derive(Clone, Debug, PartialEq)]
pub struct TypeAlias {
    /// Whether the type is marked with `export`.
    pub export: bool,
    /// The name of the type definition.
    pub name: String,
    /// The generic parameters of the type definition.
    pub parameters: Vec<&'static str>,
    /// The content of the type definition.
    pub ty: Type,
}

impl TypeAlias {
    /// Create a new type alias for the type `T`.
    pub fn alias<T: Into<Type>>(name: &str, ty: T) -> Self {
        Self {
            export: false,
            name: String::from(name),
            parameters: Vec::new(),
            ty: ty.into(),
        }
    }

    /// Mark the type with `export`.
    pub fn exported(self) -> Self {
        Self {
            export: true,
            ..self
        }
    }

    fn externally_tagged(rename: Renamer, rename_all: Renamer, ty: camo::Enum) -> Self {
        Self {
            export: ty.visibility.is_pub(),
            name: rename.rename_type(ty.name),
            parameters: ty
                .parameters
                .into_iter()
                .filter_map(|parameter| match parameter {
                    // Lifetimes are ignored
                    camo::GenericParameter::Lifetime(_) => None,
                    camo::GenericParameter::Type(ty) => Some(ty),
                })
                .collect(),
            ty: Type::Union(UnionType::externally_tagged(rename_all, ty.variants)),
        }
    }

    fn adjacently_tagged(
        rename: Renamer,
        rename_all: Renamer,
        tag: &'static str,
        content: &'static str,
        ty: camo::Enum,
    ) -> Self {
        Self {
            export: ty.visibility.is_pub(),
            name: rename.rename_type(ty.name),
            parameters: ty
                .parameters
                .into_iter()
                .filter_map(|parameter| match parameter {
                    // Lifetimes are ignored
                    camo::GenericParameter::Lifetime(_) => None,
                    camo::GenericParameter::Type(ty) => Some(ty),
                })
                .collect(),
            ty: Type::Union(UnionType::adjacently_tagged(
                rename_all,
                tag,
                content,
                ty.variants,
            )),
        }
    }

    fn internally_tagged(
        rename: Renamer,
        rename_all: Renamer,
        tag: &'static str,
        ty: camo::Enum,
    ) -> Self {
        Self {
            export: ty.visibility.is_pub(),
            name: rename.rename_field(ty.name),
            parameters: ty
                .parameters
                .into_iter()
                .filter_map(|parameter| match parameter {
                    // Lifetimes are ignored
                    camo::GenericParameter::Lifetime(_) => None,
                    camo::GenericParameter::Type(ty) => Some(ty),
                })
                .collect(),
            ty: Type::Union(UnionType::internally_tagged(rename_all, tag, ty.variants)),
        }
    }
}

impl fmt::Display for TypeAlias {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.export {
            write!(f, "export ")?;
        }
        write!(f, "type {}", self.name)?;
        if !self.parameters.is_empty() {
            write!(f, "<")?;
            for parameter in &self.parameters {
                write!(f, "{}", parameter)?;
            }
            write!(f, ">")?;
        }
        if self.ty.is_union() {
            writeln!(f, " ={};", self.ty)
        } else {
            writeln!(f, " = {};", self.ty)
        }
    }
}

/// A type with multiple cases.
///
/// Example:
/// ```ts
/// type Primitive =
///     | number
///     | boolean
///     | symbol;
/// ```
///
/// See: <https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types>
#[derive(Clone, Debug, PartialEq)]
pub struct UnionType {
    /// The variants of the union type.
    pub variants: Vec<Variant>,
}

impl UnionType {
    fn externally_tagged(rename_all: Renamer, variants: Vec<camo::Variant>) -> Self {
        Self {
            variants: variants
                .into_iter()
                .map(|variant| Variant::externally_tagged(rename_all, variant))
                .collect(),
        }
    }

    fn adjacently_tagged(
        rename_all: Renamer,
        tag: &'static str,
        content: &'static str,
        variants: Vec<camo::Variant>,
    ) -> Self {
        Self {
            variants: variants
                .into_iter()
                .map(|variant| Variant::adjacently_tagged(rename_all, tag, content, variant))
                .collect(),
        }
    }

    fn internally_tagged(
        rename_all: Renamer,
        tag: &'static str,
        variants: Vec<camo::Variant>,
    ) -> Self {
        Self {
            variants: variants
                .into_iter()
                .map(|variant| Variant::internally_tagged(rename_all, tag, variant))
                .collect(),
        }
    }
}

impl fmt::Display for UnionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for variant in &self.variants {
            write!(f, "\n\t| {}", variant)?;
        }
        Ok(())
    }
}

/// A variant of a union type.
#[derive(Clone, Debug, PartialEq)]
pub struct Variant(pub Type);

impl Variant {
    fn externally_tagged(rename_all: Renamer, variant: camo::Variant) -> Self {
        let variant_renamer = match variant.attributes.rename {
            Some(rename) => Renamer(Some(rename)),
            None => rename_all,
        };
        let field_renamer = Renamer(variant.attributes.rename_all);
        match variant.content {
            camo::VariantContent::Unit => Self(Type::Literal(LiteralType::String(
                variant_renamer.rename_type(variant.name),
            ))),
            camo::VariantContent::Unnamed(ty) => Self(Type::Object(ObjectType {
                fields: Vec::from([Field {
                    name: variant_renamer.rename_type(variant.name),
                    ty: Type::from(ty),
                }]),
            })),
            camo::VariantContent::Named(fields) => Self(Type::Object(ObjectType {
                fields: Vec::from([Field {
                    name: variant_renamer.rename_type(variant.name),
                    ty: Type::Object(ObjectType {
                        fields: fields
                            .into_iter()
                            .map(|field| Field {
                                name: field_renamer.rename_field(field.name),
                                ty: Type::from(field.ty),
                            })
                            .collect(),
                    }),
                }]),
            })),
        }
    }

    fn adjacently_tagged(
        rename_all: Renamer,
        tag: &'static str,
        content: &'static str,
        variant: camo::Variant,
    ) -> Self {
        let variant_renamer = match variant.attributes.rename {
            Some(rename) => Renamer(Some(rename)),
            None => rename_all,
        };
        let field_renamer = Renamer(variant.attributes.rename_all);
        match variant.content {
            camo::VariantContent::Unit => Self(Type::Object(ObjectType {
                fields: Vec::from([Field {
                    name: String::from(tag),
                    ty: Type::Literal(LiteralType::String(
                        variant_renamer.rename_type(variant.name),
                    )),
                }]),
            })),
            camo::VariantContent::Unnamed(ty) => Self(Type::Object(ObjectType {
                fields: Vec::from([
                    Field {
                        name: String::from(tag),
                        ty: Type::Literal(LiteralType::String(
                            variant_renamer.rename_type(variant.name),
                        )),
                    },
                    Field {
                        name: String::from(content),
                        ty: Type::from(ty),
                    },
                ]),
            })),
            camo::VariantContent::Named(fields) => Self(Type::Object(ObjectType {
                fields: Vec::from([
                    Field {
                        name: String::from(tag),
                        ty: Type::Literal(LiteralType::String(
                            variant_renamer.rename_type(variant.name),
                        )),
                    },
                    Field {
                        name: String::from(content),
                        ty: Type::Object(ObjectType {
                            fields: fields
                                .into_iter()
                                .map(|field| Field {
                                    name: field_renamer.rename_field(field.name),
                                    ty: Type::from(field.ty),
                                })
                                .collect(),
                        }),
                    },
                ]),
            })),
        }
    }

    fn internally_tagged(rename_all: Renamer, tag: &'static str, variant: camo::Variant) -> Self {
        let variant_renamer = match variant.attributes.rename {
            Some(rename) => Renamer(Some(rename)),
            None => rename_all,
        };
        let field_renamer = Renamer(variant.attributes.rename_all);
        match variant.content {
            camo::VariantContent::Unit => Self(Type::Object(ObjectType {
                fields: Vec::from([Field {
                    name: String::from(tag),
                    ty: Type::Literal(LiteralType::String(
                        variant_renamer.rename_type(variant.name),
                    )),
                }]),
            })),
            camo::VariantContent::Unnamed(ty) => Self(Type::Intersection(IntersectionType {
                left: Box::new(Type::Object(ObjectType {
                    fields: Vec::from([Field {
                        name: String::from(tag),
                        ty: Type::Literal(LiteralType::String(
                            variant_renamer.rename_type(variant.name),
                        )),
                    }]),
                })),
                right: Box::new(Type::from(ty)),
            })),
            camo::VariantContent::Named(fields) => Self(Type::Intersection(IntersectionType {
                left: Box::new(Type::Object(ObjectType {
                    fields: Vec::from([Field {
                        name: String::from(tag),
                        ty: Type::Literal(LiteralType::String(
                            variant_renamer.rename_type(variant.name),
                        )),
                    }]),
                })),
                right: Box::new(Type::Object(ObjectType {
                    fields: fields
                        .into_iter()
                        .map(|field| Field {
                            name: field_renamer.rename_field(field.name),
                            ty: Type::from(field.ty),
                        })
                        .collect(),
                })),
            })),
        }
    }
}

impl fmt::Display for Variant {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Represents a type use, e. g. in an interface definition,
/// function type definition, or type alias.
#[derive(Clone, Debug, PartialEq)]
pub enum Type {
    /// A built-in type like `number` or `string`.
    Builtin(BuiltinType),
    /// A path to some type.
    /// Includes simple names like `MyType`.
    Path(TypePath),
    /// An object type.
    Object(ObjectType),
    /// A literal type.
    Literal(LiteralType),
    /// An array type.
    Array(ArrayType),
    /// A union type, combining multiple cases.
    Union(UnionType),
    /// An intersection type, combining two types.
    Intersection(IntersectionType),
}

impl Type {
    fn is_union(&self) -> bool {
        matches!(self, Self::Union(..))
    }
}

impl From<&str> for Type {
    fn from(value: &str) -> Self {
        Self::Path(TypePath::from(value))
    }
}

impl From<String> for Type {
    fn from(value: String) -> Self {
        Self::Path(TypePath::from(value))
    }
}

impl From<BuiltinType> for Type {
    fn from(value: BuiltinType) -> Self {
        Self::Builtin(value)
    }
}

impl From<TypePath> for Type {
    fn from(value: TypePath) -> Self {
        Self::Path(value)
    }
}

impl From<ObjectType> for Type {
    fn from(value: ObjectType) -> Self {
        Self::Object(value)
    }
}

impl From<LiteralType> for Type {
    fn from(value: LiteralType) -> Self {
        Self::Literal(value)
    }
}

impl From<ArrayType> for Type {
    fn from(value: ArrayType) -> Self {
        Self::Array(value)
    }
}

impl From<IntersectionType> for Type {
    fn from(value: IntersectionType) -> Self {
        Self::Intersection(value)
    }
}

impl From<camo::Type> for Type {
    fn from(ty: camo::Type) -> Self {
        match ty {
            camo::Type::Path(ty) => match camo::BuiltinType::try_from(ty) {
                Ok(ty) => Type::Builtin(BuiltinType::from(ty)),
                Err(ty) => {
                    if let Some(segment) = ty.segments.first() {
                        match segment.name {
                            "String" => {
                                return Type::Builtin(BuiltinType::String);
                            }
                            "Vec" => {
                                let component_ty = match segment.arguments.first().unwrap().clone()
                                {
                                    camo::GenericArgument::Type(ty) => ty,
                                    camo::GenericArgument::Lifetime(_) => {
                                        panic!("unexpected lifetime argument provided to Vec")
                                    }
                                };
                                return Type::Array(ArrayType::from(Type::from(component_ty)));
                            }
                            "Option" => {
                                let component_ty = match segment.arguments.first().unwrap().clone()
                                {
                                    camo::GenericArgument::Type(ty) => ty,
                                    camo::GenericArgument::Lifetime(_) => {
                                        panic!("unexpected lifetime argument provided to Option")
                                    }
                                };
                                return Type::Union(UnionType {
                                    variants: Vec::from([
                                        Variant(Type::from(component_ty)),
                                        Variant(Type::Builtin(BuiltinType::Null)),
                                    ]),
                                });
                            }
                            _ => return Type::Path(TypePath::from(ty)),
                        }
                    }
                    Type::Path(TypePath::from(ty))
                }
            },
            camo::Type::Reference(ty) => {
                if let camo::Type::Path(path) = &*ty.ty {
                    if let Some(segment) = path.segments.first() {
                        if segment.name == "str" {
                            return Type::Builtin(BuiltinType::String);
                        }
                    }
                }
                Type::from(*ty.ty)
            }
            camo::Type::Slice(ty) => Type::Array(ArrayType::from(ty)),
            camo::Type::Array(ty) => Type::Array(ArrayType::from(ty)),
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Type::Builtin(ty) => write!(f, "{}", ty),
            Type::Path(ty) => write!(f, "{}", ty),
            Type::Object(ty) => write!(f, "{}", ty),
            Type::Literal(ty) => write!(f, "{}", ty),
            Type::Array(ty) => write!(f, "{}", ty),
            Type::Union(ty) => write!(f, "{}", ty),
            Type::Intersection(ty) => write!(f, "{}", ty),
        }
    }
}

/// The built-in types.
#[derive(Clone, Debug, PartialEq)]
pub enum BuiltinType {
    /// The `number` type.
    Number,
    /// The `boolean` type.
    Boolean,
    /// The `string` type.
    String,
    /// The `object` type.
    Object,
    /// The `null` type.
    Null,
    /// The `undefined` type.
    Undefined,
    /// The `never` type.
    Never,
    /// The `any` type.
    Any,
    /// The `unknown` type.
    Unknown,
    /// The `bigint` type.
    BigInt,
    /// The `symbol` type.
    Symbol,
}

impl BuiltinType {
    /// The name of the built-in type.
    pub fn as_str(&self) -> &'static str {
        match self {
            BuiltinType::Number => "number",
            BuiltinType::Boolean => "boolean",
            BuiltinType::String => "string",
            BuiltinType::Object => "object",
            BuiltinType::Null => "null",
            BuiltinType::Undefined => "undefined",
            BuiltinType::Never => "never",
            BuiltinType::Any => "any",
            BuiltinType::Unknown => "unknown",
            BuiltinType::BigInt => "bigint",
            BuiltinType::Symbol => "symbol",
        }
    }
}

impl From<camo::BuiltinType> for BuiltinType {
    fn from(builtin: camo::BuiltinType) -> Self {
        match builtin {
            camo::BuiltinType::Bool => BuiltinType::Boolean,
            camo::BuiltinType::U8
            | camo::BuiltinType::U16
            | camo::BuiltinType::U32
            | camo::BuiltinType::U64
            | camo::BuiltinType::U128
            | camo::BuiltinType::Usize
            | camo::BuiltinType::I8
            | camo::BuiltinType::I16
            | camo::BuiltinType::I32
            | camo::BuiltinType::I64
            | camo::BuiltinType::I128
            | camo::BuiltinType::Isize
            | camo::BuiltinType::F32
            | camo::BuiltinType::F64 => BuiltinType::Number,
            camo::BuiltinType::Char => BuiltinType::String,
        }
    }
}

impl fmt::Display for BuiltinType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// The name of a type.
///
/// Example:
///
/// ```ts
/// const x: types.X = { /* ... */}
/// //       ^^^^^^^
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct TypePath {
    /// The segments of the type name.
    pub segments: Vec<PathSegment>,
}

impl From<camo::TypePath> for TypePath {
    fn from(value: camo::TypePath) -> Self {
        Self {
            segments: value.segments.into_iter().map(Into::into).collect(),
        }
    }
}

impl<const N: usize> From<[&str; N]> for TypePath {
    fn from(value: [&str; N]) -> Self {
        Self {
            segments: value
                .map(|name| PathSegment {
                    name: name.to_string(),
                    arguments: Vec::new(),
                })
                .to_vec(),
        }
    }
}

impl From<&str> for TypePath {
    fn from(value: &str) -> Self {
        Self {
            segments: Vec::from([PathSegment {
                name: value.to_string(),
                arguments: Vec::new(),
            }]),
        }
    }
}

impl From<String> for TypePath {
    fn from(value: String) -> Self {
        Self {
            segments: Vec::from([PathSegment {
                name: value,
                arguments: Vec::new(),
            }]),
        }
    }
}

impl fmt::Display for TypePath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut iter = self.segments.iter();
        if let Some(segment) = iter.next() {
            write!(f, "{}", segment)?;
        }
        for segment in iter {
            write!(f, ".{}", segment)?;
        }
        Ok(())
    }
}

/// A segment of a type path.
#[derive(Clone, Debug, PartialEq)]
pub struct PathSegment {
    /// The name of the segment.
    pub name: String,
    /// The arguments provided to the segment.
    pub arguments: Vec<Type>,
}

impl From<camo::PathSegment> for PathSegment {
    fn from(value: camo::PathSegment) -> Self {
        Self {
            name: value.name.to_string(),
            arguments: value
                .arguments
                .into_iter()
                .filter_map(|argument| match argument {
                    camo::GenericArgument::Type(ty) => Some(Type::from(ty)),
                    camo::GenericArgument::Lifetime(_) => None,
                })
                .collect(),
        }
    }
}

impl fmt::Display for PathSegment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name)?;
        if !self.arguments.is_empty() {
            write!(f, "<")?;
            let mut iter = self.arguments.iter();
            if let Some(argument) = iter.next() {
                write!(f, "{}", argument)?;
            }
            for argument in iter {
                write!(f, ", {}", argument)?;
            }
            write!(f, ">")?;
        }
        Ok(())
    }
}

/// An object type.
///
/// See: <https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#object-types>
#[derive(Clone, Debug, PartialEq)]
pub struct ObjectType {
    /// The fields of the object type.
    pub fields: Vec<Field>,
}

impl fmt::Display for ObjectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{{")?;
        for field in &self.fields {
            write!(f, " {}", field)?;
        }
        write!(f, " }}")
    }
}

/// A literal type.
///
/// Example:
/// ```ts
/// type Tag = "Tag";
/// ```
///
/// See: <https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types>
#[derive(Clone, Debug, PartialEq)]
pub enum LiteralType {
    /// A string literal type.
    String(String),
}

impl fmt::Display for LiteralType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LiteralType::String(s) => write!(f, "\"{}\"", s),
        }
    }
}

/// An array type expression.
///
/// Example:
/// ```ts
/// type Numbers = number[];
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct ArrayType(pub Box<Type>);

impl From<Type> for ArrayType {
    fn from(value: Type) -> Self {
        Self(Box::new(value))
    }
}

impl From<camo::SliceType> for ArrayType {
    fn from(value: camo::SliceType) -> Self {
        Self(Box::new(Type::from(*value.0)))
    }
}

impl From<camo::ArrayType> for ArrayType {
    fn from(value: camo::ArrayType) -> Self {
        Self(Box::new(Type::from(*value.0)))
    }
}

impl fmt::Display for ArrayType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}[]", self.0)
    }
}

/// An intersection type.
///
/// Example:
/// ```ts
/// type T = { name: string } & { value: number };
/// //        -------------   ^  ----------------
/// ```
///
/// See: <https://www.typescriptlang.org/docs/handbook/2/objects.html#intersection-types>
#[derive(Clone, Debug, PartialEq)]
pub struct IntersectionType {
    /// The left-hand side of the intersection.
    pub left: Box<Type>,
    /// The right-hand side of the intersection.
    pub right: Box<Type>,
}

impl fmt::Display for IntersectionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} & {}", self.left, self.right)
    }
}