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
use std::collections::{HashMap, HashSet};

use crate::{
    value::{EnumType, EnumVariantType, FunctionType, PairType, StructType, Type},
    Comparison, Database, TypeId,
};

#[derive(Debug)]
struct ComparisonContext<'a> {
    visited: HashSet<(TypeId, TypeId)>,
    generic_type_stack: &'a mut Vec<HashMap<TypeId, TypeId>>,
    infer_generics: bool,
}

impl<'a> ComparisonContext<'a> {
    fn new(generic_type_stack: &'a mut Vec<HashMap<TypeId, TypeId>>, infer_generics: bool) -> Self {
        Self {
            visited: HashSet::new(),
            generic_type_stack,
            infer_generics,
        }
    }
}

impl Database {
    pub fn substitute_type(
        &mut self,
        type_id: TypeId,
        substitutions: &HashMap<TypeId, TypeId>,
    ) -> TypeId {
        self.substitute_type_visitor(type_id, substitutions, &mut HashSet::new())
    }

    pub fn compare_type(&self, lhs: TypeId, rhs: TypeId) -> Comparison {
        self.compare_type_visitor(
            lhs,
            rhs,
            &mut ComparisonContext::new(&mut Vec::new(), false),
        )
    }

    pub fn compare_type_with_generics(
        &self,
        lhs: TypeId,
        rhs: TypeId,
        generic_type_stack: &mut Vec<HashMap<TypeId, TypeId>>,
    ) -> Comparison {
        self.compare_type_visitor(
            lhs,
            rhs,
            &mut ComparisonContext::new(generic_type_stack, true),
        )
    }

    pub fn is_cyclic(&self, type_id: TypeId) -> bool {
        self.is_cyclic_visitor(type_id, &mut HashSet::new())
    }

    pub fn first_type(&self, type_id: TypeId) -> Option<TypeId> {
        let Type::Pair(pair) = self.ty(type_id) else {
            return None;
        };
        Some(pair.first)
    }

    pub fn rest_type(&self, type_id: TypeId) -> Option<TypeId> {
        let Type::Pair(pair) = self.ty(type_id) else {
            return None;
        };
        Some(pair.rest)
    }

    pub fn non_nullable(&mut self, ty: TypeId) -> TypeId {
        match self.ty(ty) {
            Type::Nullable(inner) => self.non_nullable(*inner),
            _ => ty,
        }
    }

    pub fn non_undefined(&mut self, ty: TypeId) -> TypeId {
        match self.ty(ty) {
            Type::Optional(inner) => self.non_undefined(*inner),
            _ => ty,
        }
    }

    pub fn unwrap_list(&mut self, ty: TypeId) -> Option<TypeId> {
        match self.ty(ty) {
            Type::List(inner) => Some(*inner),
            _ => None,
        }
    }

    pub fn substitute_type_visitor(
        &mut self,
        type_id: TypeId,
        substitutions: &HashMap<TypeId, TypeId>,
        visited: &mut HashSet<TypeId>,
    ) -> TypeId {
        if let Some(type_id) = substitutions.get(&type_id).copied() {
            return type_id;
        }

        if !visited.insert(type_id) {
            return type_id;
        }

        match self.ty(type_id).clone() {
            Type::Alias(..) => unreachable!(),
            Type::Pair(pair) => {
                let new_pair = PairType {
                    first: self.substitute_type_visitor(pair.first, substitutions, visited),
                    rest: self.substitute_type_visitor(pair.rest, substitutions, visited),
                };

                if new_pair == pair {
                    type_id
                } else {
                    self.alloc_type(Type::Pair(new_pair))
                }
            }
            Type::Enum(enum_type) => {
                let new_enum = EnumType {
                    has_fields: enum_type.has_fields,
                    variants: enum_type
                        .variants
                        .iter()
                        .map(|(k, v)| {
                            (
                                k.clone(),
                                self.substitute_type_visitor(*v, substitutions, visited),
                            )
                        })
                        .collect(),
                };

                if new_enum == enum_type {
                    type_id
                } else {
                    self.alloc_type(Type::Enum(new_enum))
                }
            }
            Type::EnumVariant(enum_variant) => {
                let new_variant = EnumVariantType {
                    enum_type: enum_variant.enum_type,
                    original_type_id: enum_variant.original_type_id,
                    fields: enum_variant.fields.as_ref().map(|fields| {
                        fields
                            .iter()
                            .map(|(k, v)| {
                                (
                                    k.clone(),
                                    self.substitute_type_visitor(*v, substitutions, visited),
                                )
                            })
                            .collect()
                    }),
                    rest: enum_variant.rest,
                    discriminant: enum_variant.discriminant,
                };

                if new_variant == enum_variant {
                    type_id
                } else {
                    self.alloc_type(Type::EnumVariant(new_variant))
                }
            }
            Type::List(inner) => {
                let new_inner = self.substitute_type_visitor(inner, substitutions, visited);

                if new_inner == inner {
                    type_id
                } else {
                    self.alloc_type(Type::List(new_inner))
                }
            }
            Type::Struct(struct_type) => {
                let new_struct = StructType {
                    original_type_id: struct_type.original_type_id,
                    fields: struct_type
                        .fields
                        .iter()
                        .map(|(k, v)| {
                            (
                                k.clone(),
                                self.substitute_type_visitor(*v, substitutions, visited),
                            )
                        })
                        .collect(),
                    rest: struct_type.rest,
                };

                if new_struct == struct_type {
                    type_id
                } else {
                    self.alloc_type(Type::Struct(new_struct))
                }
            }
            Type::Function(function) => {
                let new_function = FunctionType {
                    param_types: function
                        .param_types
                        .iter()
                        .map(|ty| self.substitute_type_visitor(*ty, substitutions, visited))
                        .collect(),
                    rest: function.rest,
                    return_type: self.substitute_type_visitor(
                        function.return_type,
                        substitutions,
                        visited,
                    ),
                    generic_types: function
                        .generic_types
                        .iter()
                        .map(|ty| self.substitute_type_visitor(*ty, substitutions, visited))
                        .collect(),
                };

                if new_function == function {
                    type_id
                } else {
                    self.alloc_type(Type::Function(new_function))
                }
            }
            Type::Nullable(inner) => {
                let new_inner = self.substitute_type_visitor(inner, substitutions, visited);

                if new_inner == inner {
                    type_id
                } else {
                    self.alloc_type(Type::Nullable(inner))
                }
            }
            Type::Optional(inner) => {
                let new_inner = self.substitute_type_visitor(inner, substitutions, visited);

                if new_inner == inner {
                    type_id
                } else {
                    self.alloc_type(Type::Optional(inner))
                }
            }
            Type::Unknown
            | Type::Generic
            | Type::Any
            | Type::Bool
            | Type::Bytes
            | Type::Bytes32
            | Type::Int
            | Type::Nil
            | Type::PublicKey => type_id,
        }
    }

    #[allow(clippy::match_same_arms, clippy::too_many_lines)]
    fn compare_type_visitor(
        &self,
        lhs: TypeId,
        rhs: TypeId,
        ctx: &mut ComparisonContext<'_>,
    ) -> Comparison {
        let key = (lhs, rhs);
        if lhs == rhs || !ctx.visited.insert(key) {
            return Comparison::Equal;
        }

        let comparison = match (self.ty(lhs), self.ty(rhs)) {
            // Aliases are already resolved at this point.
            (Type::Alias(..), _) | (_, Type::Alias(..)) => unreachable!(),

            // We need to infer `Generic` types, and return `Unrelated` if incompatible.
            (_, Type::Generic) => {
                let mut found = None;

                for generics in ctx.generic_type_stack.iter().rev() {
                    if let Some(&generic) = generics.get(&rhs) {
                        found = Some(generic);
                    }
                }

                if let Some(found) = found {
                    self.compare_type_visitor(lhs, found, ctx)
                } else if ctx.infer_generics {
                    ctx.generic_type_stack.last_mut().unwrap().insert(rhs, lhs);
                    Comparison::Assignable
                } else {
                    Comparison::Unrelated
                }
            }

            // We should have already given a diagnostic for `Unknown`.
            // So we will go ahead and pretend they are equal to everything.
            (Type::Unknown, _) | (_, Type::Unknown) => Comparison::Equal,

            // Possibly undefined is a special type.
            (Type::Optional(..), _) | (_, Type::Optional(..)) => Comparison::Unrelated,

            // These are of course equal atomic types.
            (Type::Any, Type::Any) => Comparison::Equal,
            (Type::Int, Type::Int) => Comparison::Equal,
            (Type::Bool, Type::Bool) => Comparison::Equal,
            (Type::Bytes, Type::Bytes) => Comparison::Equal,
            (Type::Bytes32, Type::Bytes32) => Comparison::Equal,
            (Type::PublicKey, Type::PublicKey) => Comparison::Equal,
            (Type::Nil, Type::Nil) => Comparison::Equal,

            // We should treat `Bytes32` as a subtype of `Bytes` and therefore equal.
            // `PublicKey` however, can have different meaning, so is not equal.
            // `Bytes` is also not equal to `Bytes32` since it's unsized.
            (Type::Bytes32, Type::Bytes) => Comparison::Equal,

            // You can cast `Any` to anything, but it's not implicit.
            // So many languages make `Any` implicit and it makes it hard to debug.
            (Type::Any, _) => Comparison::Castable,

            // However, anything can be assigned to `Any` implicitly.
            (_, Type::Any) => Comparison::Assignable,

            // `Generic` types are unrelated to everything else except their specific instance.
            // The only exception is the `Any` type above.
            (Type::Generic, _) => Comparison::Unrelated,

            // You have to explicitly convert between other atom types.
            // This is because the compiled output can change depending on the type.
            (Type::Int, Type::Bytes) => Comparison::Castable,
            (Type::Bool, Type::Bytes) => Comparison::Castable,
            (Type::Bool, Type::Int) => Comparison::Castable,
            (Type::Nil, Type::Int) => Comparison::Castable,
            (Type::Nil, Type::Bool) => Comparison::Castable,
            (Type::PublicKey, Type::Bytes) => Comparison::Castable,
            (Type::PublicKey, Type::Int) => Comparison::Castable,
            (Type::Bytes, Type::Int) => Comparison::Castable,
            (Type::Bytes32, Type::Int) => Comparison::Castable,

            // Let's allow assigning `Nil` to `Bytes` for ease of use.
            // The only alternative without needing a cast is empty strings.
            (Type::Nil, Type::Bytes) => Comparison::Assignable,

            // Size changing conversions are not possible without a type guard.
            (Type::Bytes, Type::Bytes32) => Comparison::Superset,
            (Type::Bytes, Type::PublicKey) => Comparison::Superset,
            (Type::Bytes, Type::Nil) => Comparison::Superset,
            (Type::Bytes, Type::Bool) => Comparison::Superset,
            (Type::Int, Type::Bytes32) => Comparison::Superset,
            (Type::Int, Type::PublicKey) => Comparison::Superset,
            (Type::Int, Type::Nil) => Comparison::Superset,
            (Type::Int, Type::Bool) => Comparison::Superset,
            (Type::Bool, Type::PublicKey) => Comparison::Unrelated,
            (Type::Bool, Type::Bytes32) => Comparison::Unrelated,
            (Type::Bool, Type::Nil) => Comparison::Unrelated,
            (Type::Nil, Type::Bytes32) => Comparison::Unrelated,
            (Type::Nil, Type::PublicKey) => Comparison::Unrelated,
            (Type::PublicKey, Type::Bytes32) => Comparison::Unrelated,
            (Type::PublicKey, Type::Bool) => Comparison::Unrelated,
            (Type::PublicKey, Type::Nil) => Comparison::Unrelated,
            (Type::Bytes32, Type::PublicKey) => Comparison::Unrelated,
            (Type::Bytes32, Type::Bool) => Comparison::Unrelated,
            (Type::Bytes32, Type::Nil) => Comparison::Unrelated,

            // These are the variants of the `Nullable` type.
            (Type::Nil, Type::Nullable(..)) => Comparison::Assignable,
            (Type::Nullable(lhs), Type::Nullable(rhs)) => {
                self.compare_type_visitor(*lhs, *rhs, ctx)
            }
            (_, Type::Nullable(inner)) => self.compare_type_visitor(lhs, *inner, ctx),
            (Type::Nullable(inner), Type::Bytes) => {
                Comparison::Castable & self.compare_type_visitor(*inner, rhs, ctx)
            }

            // TODO: Unions would make this more generalized and useful.
            // I should add unions back.
            (Type::Nullable(_inner), _) => Comparison::Unrelated,

            // Compare both sides of a `Pair`.
            (Type::Pair(lhs), Type::Pair(rhs)) => {
                let first = self.compare_type_visitor(lhs.first, rhs.first, ctx);
                let rest = self.compare_type_visitor(lhs.rest, rhs.rest, ctx);
                first & rest
            }

            // A `Pair` is a valid `List` if its first type is the same as the list's inner type
            // and the rest is also a valid `List` of the same type.
            // However, it's not considered equal but rather assignable.
            (Type::Pair(pair), Type::List(inner)) => {
                let inner = self.compare_type_visitor(pair.first, *inner, ctx);
                let rest = self.compare_type_visitor(pair.rest, rhs, ctx);
                Comparison::Assignable & inner & rest
            }

            // A `List` is not a valid pair since `Nil` is also a valid list.
            // It's a `Superset` only if the opposite comparison is not `Unrelated`.
            (Type::List(..), Type::Pair(..)) => {
                Comparison::Superset & self.compare_type_visitor(rhs, lhs, ctx)
            }

            // Nothing else can be assigned to or from a `Pair`.
            (Type::Pair(..), _) | (_, Type::Pair(..)) => Comparison::Unrelated,

            // A `List` just compares with the inner type of another `List`.
            (Type::List(lhs), Type::List(rhs)) => self.compare_type_visitor(*lhs, *rhs, ctx),

            // `Nil` is a valid list.
            (Type::Nil, Type::List(..)) => Comparison::Assignable,
            (Type::List(..), Type::Nil) => Comparison::Superset,

            // `List` is not compatible with atoms.
            (Type::Bytes, Type::List(..)) => Comparison::Unrelated,
            (Type::Bytes32, Type::List(..)) => Comparison::Unrelated,
            (Type::PublicKey, Type::List(..)) => Comparison::Unrelated,
            (Type::Int, Type::List(..)) => Comparison::Unrelated,
            (Type::Bool, Type::List(..)) => Comparison::Unrelated,
            (Type::List(..), Type::Bytes) => Comparison::Unrelated,
            (Type::List(..), Type::Bytes32) => Comparison::Unrelated,
            (Type::List(..), Type::PublicKey) => Comparison::Unrelated,
            (Type::List(..), Type::Int) => Comparison::Unrelated,
            (Type::List(..), Type::Bool) => Comparison::Unrelated,

            // A `Struct` is castable to others only if the fields are identical.
            (Type::Struct(lhs), Type::Struct(rhs)) => {
                if lhs.fields.len() == rhs.fields.len() {
                    let mut result = Comparison::Castable;
                    for i in 0..lhs.fields.len() {
                        result &= self.compare_type_visitor(lhs.fields[i], rhs.fields[i], ctx);
                    }
                    result
                } else {
                    Comparison::Unrelated
                }
            }
            (Type::Struct(..), _) | (_, Type::Struct(..)) => Comparison::Unrelated,

            // Enum variants are assignable only to their respective enum.
            (Type::EnumVariant(variant_type), Type::Enum(..)) => {
                if variant_type.enum_type == rhs {
                    Comparison::Assignable
                } else {
                    Comparison::Unrelated
                }
            }

            // But not the other way around.
            (Type::Enum(..), Type::EnumVariant(variant_type)) => {
                if variant_type.enum_type == lhs {
                    Comparison::Superset
                } else {
                    Comparison::Unrelated
                }
            }

            // You can cast numeric enums to `Int`.
            (Type::EnumVariant(variant_type), Type::Bytes | Type::Int) => {
                self.compare_type_visitor(variant_type.enum_type, rhs, ctx)
            }

            (Type::Enum(enum_type), Type::Bytes | Type::Int) => {
                if enum_type.has_fields {
                    Comparison::Unrelated
                } else {
                    Comparison::Castable
                }
            }

            // Enums and their variants are not assignable to anything else.
            (Type::Enum(..), _) | (_, Type::Enum(..)) => Comparison::Unrelated,
            (Type::EnumVariant(..), _) | (_, Type::EnumVariant(..)) => Comparison::Unrelated,

            // The parameters and return types of functions are checked.
            // This can be made more flexible later.
            (Type::Function(lhs), Type::Function(rhs)) => {
                if lhs.param_types.len() != rhs.param_types.len() || lhs.rest != rhs.rest {
                    Comparison::Unrelated
                } else {
                    let mut result =
                        self.compare_type_visitor(lhs.return_type, rhs.return_type, ctx);

                    for i in 0..lhs.param_types.len() {
                        result &=
                            self.compare_type_visitor(lhs.param_types[i], rhs.param_types[i], ctx);
                    }

                    result
                }
            }

            // There is likely nothing that should relate to a function.
            (Type::Function(..), _) | (_, Type::Function(..)) => Comparison::Unrelated,
        };

        ctx.visited.remove(&key);
        comparison
    }

    fn is_cyclic_visitor(&self, ty: TypeId, visited_aliases: &mut HashSet<TypeId>) -> bool {
        match self.ty_raw(ty).clone() {
            Type::Pair(pair) => {
                self.is_cyclic_visitor(pair.first, visited_aliases)
                    || self.is_cyclic_visitor(pair.rest, visited_aliases)
            }
            Type::Alias(alias) => {
                if !visited_aliases.insert(alias) {
                    return true;
                }
                self.is_cyclic_visitor(alias, visited_aliases)
            }
            Type::List(..)
            | Type::Struct(..)
            | Type::Enum(..)
            | Type::EnumVariant(..)
            | Type::Function(..)
            | Type::Unknown
            | Type::Generic
            | Type::Nil
            | Type::Any
            | Type::Int
            | Type::Bool
            | Type::Bytes
            | Type::Bytes32
            | Type::PublicKey => false,
            Type::Nullable(ty) | Type::Optional(ty) => self.is_cyclic_visitor(ty, visited_aliases),
        }
    }
}

#[cfg(test)]
mod tests {
    use indexmap::IndexMap;

    use crate::{
        compiler::{builtins, Builtins},
        value::{EnumType, EnumVariantType, FunctionType, PairType, Rest, StructType},
    };

    use super::*;

    fn setup() -> (Database, Builtins) {
        let mut db = Database::new();
        let ty = builtins(&mut db);
        (db, ty)
    }

    fn fields(items: &[TypeId]) -> IndexMap<String, TypeId> {
        let mut fields = IndexMap::new();
        for (i, item) in items.iter().enumerate() {
            fields.insert(format!("field_{i}"), *item);
        }
        fields
    }

    #[test]
    fn test_substitution() {
        let (mut db, ty) = setup();

        let a = db.alloc_type(Type::Generic);
        let b = db.alloc_type(Type::Generic);

        let a_list = db.alloc_type(Type::List(a));

        let function = db.alloc_type(Type::Function(FunctionType {
            param_types: vec![a_list],
            rest: Rest::Nil,
            return_type: b,
            generic_types: vec![a, b],
        }));

        let int_list = db.alloc_type(Type::List(ty.int));

        let substitutions = [(a, ty.int), (b, ty.bool)].into_iter().collect();
        let substituted = db.substitute_type(function, &substitutions);

        let expected = db.alloc_type(Type::Function(FunctionType {
            param_types: vec![int_list],
            rest: Rest::Nil,
            return_type: ty.bool,
            generic_types: vec![a, b],
        }));

        assert_eq!(db.compare_type(substituted, expected), Comparison::Equal);
    }

    #[test]
    fn test_alias_resolution() {
        let (mut db, ty) = setup();

        let int_alias = db.alloc_type(Type::Alias(ty.int));
        assert_eq!(db.compare_type(int_alias, ty.int), Comparison::Equal);
        assert_eq!(db.compare_type(ty.int, int_alias), Comparison::Equal);
        assert_eq!(db.compare_type(int_alias, int_alias), Comparison::Equal);

        let double_alias = db.alloc_type(Type::Alias(int_alias));
        assert_eq!(db.compare_type(double_alias, ty.int), Comparison::Equal);
        assert_eq!(db.compare_type(ty.int, double_alias), Comparison::Equal);
        assert_eq!(
            db.compare_type(double_alias, double_alias),
            Comparison::Equal
        );
        assert_eq!(db.compare_type(double_alias, int_alias), Comparison::Equal);
        assert_eq!(db.compare_type(int_alias, double_alias), Comparison::Equal);
    }

    #[test]
    fn test_generic_type() {
        let (mut db, ty) = setup();
        let a = db.alloc_type(Type::Generic);
        let b = db.alloc_type(Type::Generic);
        assert_eq!(db.compare_type(a, b), Comparison::Unrelated);
        assert_eq!(db.compare_type(a, ty.int), Comparison::Unrelated);
        assert_eq!(db.compare_type(ty.int, a), Comparison::Unrelated);
        assert_eq!(db.compare_type(a, a), Comparison::Equal);
    }

    #[test]
    fn test_any_type() {
        let (db, ty) = setup();
        assert_eq!(db.compare_type(ty.any, ty.int), Comparison::Castable);
        assert_eq!(db.compare_type(ty.any, ty.any), Comparison::Equal);
        assert_eq!(db.compare_type(ty.int, ty.any), Comparison::Assignable);
    }

    #[test]
    fn test_unknown_type() {
        let (db, ty) = setup();
        assert_eq!(db.compare_type(ty.any, ty.unknown), Comparison::Equal);
        assert_eq!(db.compare_type(ty.int, ty.unknown), Comparison::Equal);
        assert_eq!(db.compare_type(ty.unknown, ty.int), Comparison::Equal);
        assert_eq!(db.compare_type(ty.unknown, ty.any), Comparison::Equal);
    }

    #[test]
    fn test_atom_types() {
        let (db, ty) = setup();
        assert_eq!(db.compare_type(ty.bytes, ty.bytes32), Comparison::Superset);
        assert_eq!(db.compare_type(ty.bytes32, ty.bytes), Comparison::Equal);
        assert_eq!(
            db.compare_type(ty.bytes, ty.public_key),
            Comparison::Superset
        );
        assert_eq!(
            db.compare_type(ty.public_key, ty.bytes),
            Comparison::Castable
        );
        assert_eq!(db.compare_type(ty.bytes, ty.int), Comparison::Castable);
        assert_eq!(db.compare_type(ty.int, ty.bytes), Comparison::Castable);
        assert_eq!(db.compare_type(ty.int, ty.int), Comparison::Equal);
    }

    #[test]
    fn test_nil_type() {
        let (mut db, ty) = setup();

        let list = db.alloc_type(Type::List(ty.int));
        assert_eq!(db.compare_type(ty.nil, ty.int), Comparison::Castable);
        assert_eq!(db.compare_type(ty.nil, ty.bool), Comparison::Castable);
        assert_eq!(db.compare_type(ty.nil, ty.bytes), Comparison::Assignable);
        assert_eq!(db.compare_type(ty.nil, ty.bytes32), Comparison::Unrelated);
        assert_eq!(
            db.compare_type(ty.nil, ty.public_key),
            Comparison::Unrelated
        );
        assert_eq!(db.compare_type(ty.nil, list), Comparison::Assignable);
    }

    #[test]
    fn test_pair_type() {
        let (mut db, ty) = setup();

        let int_pair = db.alloc_type(Type::Pair(PairType {
            first: ty.int,
            rest: ty.int,
        }));
        assert_eq!(db.compare_type(int_pair, int_pair), Comparison::Equal);

        let bytes_pair = db.alloc_type(Type::Pair(PairType {
            first: ty.bytes,
            rest: ty.bytes,
        }));
        assert_eq!(db.compare_type(int_pair, bytes_pair), Comparison::Castable);
        assert_eq!(db.compare_type(bytes_pair, int_pair), Comparison::Castable);

        let bytes32_pair = db.alloc_type(Type::Pair(PairType {
            first: ty.bytes32,
            rest: ty.bytes32,
        }));
        assert_eq!(
            db.compare_type(bytes_pair, bytes32_pair),
            Comparison::Superset
        );
        assert_eq!(db.compare_type(bytes32_pair, bytes_pair), Comparison::Equal);

        let bytes32_bytes = db.alloc_type(Type::Pair(PairType {
            first: ty.bytes32,
            rest: ty.bytes,
        }));
        assert_eq!(
            db.compare_type(bytes_pair, bytes32_bytes),
            Comparison::Superset
        );
        assert_eq!(
            db.compare_type(bytes32_bytes, bytes_pair),
            Comparison::Equal
        );
    }

    #[test]
    fn test_list_types() {
        let (mut db, ty) = setup();

        let int_list = db.alloc_type(Type::List(ty.int));
        assert_eq!(db.compare_type(int_list, int_list), Comparison::Equal);

        let pair_list = db.alloc_type(Type::Pair(PairType {
            first: ty.int,
            rest: int_list,
        }));
        assert_eq!(db.compare_type(pair_list, int_list), Comparison::Assignable);
        assert_eq!(db.compare_type(int_list, pair_list), Comparison::Superset);

        let pair_nil = db.alloc_type(Type::Pair(PairType {
            first: ty.int,
            rest: ty.nil,
        }));
        assert_eq!(db.compare_type(pair_nil, int_list), Comparison::Assignable);

        let pair_unrelated_first = db.alloc_type(Type::Pair(PairType {
            first: pair_list,
            rest: ty.nil,
        }));
        assert_eq!(
            db.compare_type(pair_unrelated_first, int_list),
            Comparison::Unrelated
        );

        let pair_unrelated_rest = db.alloc_type(Type::Pair(PairType {
            first: ty.int,
            rest: ty.int,
        }));
        assert_eq!(
            db.compare_type(pair_unrelated_rest, int_list),
            Comparison::Unrelated
        );
    }

    #[test]
    fn test_struct_types() {
        let (mut db, ty) = setup();

        let two_ints = db.alloc_type(Type::Unknown);
        *db.ty_mut(two_ints) = Type::Struct(StructType {
            original_type_id: two_ints,
            fields: fields(&[ty.int, ty.int]),
            rest: Rest::Nil,
        });
        assert_eq!(db.compare_type(two_ints, two_ints), Comparison::Equal);

        let one_int = db.alloc_type(Type::Unknown);
        *db.ty_mut(one_int) = Type::Struct(StructType {
            original_type_id: one_int,
            fields: fields(&[ty.int]),
            rest: Rest::Nil,
        });
        assert_eq!(db.compare_type(one_int, two_ints), Comparison::Unrelated);

        let empty_struct = db.alloc_type(Type::Unknown);
        *db.ty_mut(empty_struct) = Type::Struct(StructType {
            original_type_id: empty_struct,
            fields: fields(&[]),
            rest: Rest::Nil,
        });
        assert_eq!(
            db.compare_type(empty_struct, empty_struct),
            Comparison::Equal
        );
    }

    #[test]
    fn test_enum_types() {
        let (mut db, ty) = setup();

        let enum_type = db.alloc_type(Type::Unknown);

        let variant = db.alloc_type(Type::Unknown);
        *db.ty_mut(variant) = Type::EnumVariant(EnumVariantType {
            enum_type,
            original_type_id: variant,
            fields: Some(fields(&[ty.int])),
            discriminant: ty.unknown_hir,
            rest: Rest::Nil,
        });

        *db.ty_mut(enum_type) = Type::Enum(EnumType {
            has_fields: true,
            variants: fields(&[variant]),
        });

        assert_eq!(db.compare_type(enum_type, variant), Comparison::Superset);
        assert_eq!(db.compare_type(variant, enum_type), Comparison::Assignable);
    }

    #[test]
    fn test_function_types() {
        let (mut db, ty) = setup();

        let int_to_bool = db.alloc_type(Type::Function(FunctionType {
            param_types: vec![ty.int],
            rest: Rest::Nil,
            return_type: ty.bool,
            generic_types: Vec::new(),
        }));
        assert_eq!(db.compare_type(int_to_bool, int_to_bool), Comparison::Equal);

        let int_to_int = db.alloc_type(Type::Function(FunctionType {
            param_types: vec![ty.int],
            rest: Rest::Nil,
            return_type: ty.int,
            generic_types: Vec::new(),
        }));
        assert_eq!(
            db.compare_type(int_to_bool, int_to_int),
            Comparison::Castable
        );
        assert_eq!(
            db.compare_type(int_to_int, int_to_bool),
            Comparison::Superset
        );

        let int_list = db.alloc_type(Type::List(ty.int));
        let int_list_to_bool = db.alloc_type(Type::Function(FunctionType {
            param_types: vec![int_list],
            rest: Rest::Nil,
            return_type: ty.bool,
            generic_types: Vec::new(),
        }));
        assert_eq!(
            db.compare_type(int_to_bool, int_list_to_bool),
            Comparison::Unrelated
        );
        assert_eq!(
            db.compare_type(int_list_to_bool, int_to_bool),
            Comparison::Unrelated
        );
    }
}