-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathtypechecker.rs
2261 lines (1965 loc) · 94.1 KB
/
typechecker.rs
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
//! typechecker.rs - Defines the type inference pass used by the compiler.
//! This pass comes after name resolution and is followed by the lifetime inference.
//!
//! This pass traverses over the ast, filling out the (typ: Option<Type>) field of each node.
//! When this pass is finished, all such fields are guarenteed to be filled out. The formatting
//! of this file begins with helper functions for type inference at the type, and ends with
//! the actual AST pass defined in the `Inferable` trait. Note that this AST pass starts
//! in the first module, and whenever it finds a variable using a definition that hasn't yet
//! been typechecked, it delves into that definition to typecheck it. This means any variables
//! that are unused are not typechecked by default.
//!
//! This uses algorithm j extended with let polymorphism and multi-parameter
//! typeclasses (traits) with a very limited form of functional dependencies.
//! For generalization this uses let binding levels to determine if types escape
//! the current binding and should thus not be generalized.
//!
//! Most of this file is translated from: https://github.com/jfecher/algorithm-j
//! That repository may be a good starting place for those new to type inference.
//! For those already familiar with type inference or more interested in ante's
//! internals, the recommended starting place while reading this file is the
//! `Inferable` trait and its impls for each node. From there, you can see what
//! type inference does for each node type and inspect any helpers that are used.
//!
//! Note that as a result of type inference, the following Optional fields in the
//! Ast will be filled out:
//! - `typ: Option<Type>` for all nodes,
//! - `trait_binding: Option<TraitBindingId>` for `ast::Variable`s,
//! - `decision_tree: Option<DecisionTree>` for `ast::Match`s
use crate::cache::{DefinitionInfoId, DefinitionKind, EffectInfoId, ModuleCache, TraitInfoId};
use crate::cache::{ImplScopeId, VariableId};
use crate::error::location::{Locatable, Location};
use crate::error::{Diagnostic, DiagnosticKind as D, TypeErrorKind, TypeErrorKind as TE};
use crate::parser::ast::{self, ClosureEnvironment, Mutability};
use crate::types::traits::{RequiredTrait, TraitConstraint, TraitConstraints};
use crate::types::typed::Typed;
use crate::types::EffectSet;
use crate::types::{
pattern, traitchecker, FunctionType, LetBindingLevel, PrimitiveType, Type, Type::*, TypeBinding, TypeBinding::*,
TypeInfo, TypeVariableId, INITIAL_LEVEL, PAIR_TYPE, STRING_TYPE,
};
use crate::util::*;
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::effects::Effect;
use super::mutual_recursion::{definition_is_mutually_recursive, try_generalize_definition};
use super::traits::{Callsite, ConstraintSignature, TraitConstraintId};
use super::{GeneralizedType, TypeInfoBody, TypeTag};
/// The current LetBindingLevel we are at.
/// This increases by 1 whenever we enter the rhs of a `ast::Definition` and decreases
/// by 1 whenever we exit this rhs. This helps keep track of which scope type variables
/// arose from and whether they should be generalized or not. See
/// http://okmij.org/ftp/ML/generalization.html for more information on let binding levels.
pub static CURRENT_LEVEL: AtomicUsize = AtomicUsize::new(INITIAL_LEVEL);
/// A sparse set of type bindings, used by try_unify
pub type TypeBindings = HashMap<TypeVariableId, Type>;
/// The result of `try_unify`: either a set of type bindings to perform,
/// or an error message of which types failed to unify.
pub type UnificationResult<'c> = Result<UnificationBindings, Diagnostic<'c>>;
type LevelBindings = Vec<(TypeVariableId, LetBindingLevel)>;
/// Arbitrary limit of maximum recursive calls to functions like find_binding.
/// Expected not to happen but leads to better errors than a stack overflow when it does.
const RECURSION_LIMIT: u32 = 100;
#[derive(Debug, Clone)]
pub struct UnificationBindings {
pub bindings: TypeBindings,
level_bindings: LevelBindings,
}
impl UnificationBindings {
pub fn empty() -> UnificationBindings {
UnificationBindings { bindings: HashMap::new(), level_bindings: vec![] }
}
pub fn perform(self, cache: &mut ModuleCache) {
perform_type_bindings(self.bindings, cache);
for (id, level) in self.level_bindings {
match &cache.type_bindings[id.0] {
Bound(_) => (), // The binding changed from under us. Is this an issue?
Unbound(original_level, kind) => {
let min_level = std::cmp::min(level, *original_level);
cache.type_bindings[id.0] = Unbound(min_level, kind.clone());
},
}
}
}
pub fn extend(&mut self, mut other: UnificationBindings) {
self.bindings.extend(other.bindings);
self.level_bindings.append(&mut other.level_bindings);
}
}
pub struct TypeResult {
typ: Type,
traits: TraitConstraints,
effects: EffectSet,
}
impl TypeResult {
fn new(typ: Type, traits: TraitConstraints, cache: &mut ModuleCache) -> TypeResult {
Self { typ, traits, effects: EffectSet::any(cache) }
}
fn of(typ: Type, cache: &mut ModuleCache) -> TypeResult {
Self { typ, traits: vec![], effects: EffectSet::any(cache) }
}
fn with_type(mut self, typ: Type) -> TypeResult {
self.typ = typ;
self
}
fn combine(&mut self, other: &mut Self, cache: &mut ModuleCache) {
self.traits.append(&mut other.traits);
self.effects = self.effects.combine(&other.effects, cache);
}
fn handle_effects_from(
&mut self, mut traits: TraitConstraints, effects: EffectSet, handled_effects: &mut Vec<Effect>,
cache: &mut ModuleCache,
) {
self.traits.append(&mut traits);
self.effects.handle_effects_from(effects, handled_effects, cache);
}
}
/// Convert a TypeApplication(UserDefinedType(id), args) into the set of TypeBindings
/// so that each mapping in the bindings is in the form `var -> arg` where each variable
/// was one of the variables given in the definition of the user-defined-type:
/// `type Foo var1 var2 ... varN = ...` and each `arg` corresponds to the generic argument
/// of the type somewhere in the program, e.g: `foo : Foo arg1 arg2 ... argN`
pub fn type_application_bindings(info: &TypeInfo<'_>, typeargs: &[Type], cache: &ModuleCache) -> TypeBindings {
info.args
.iter()
.copied()
.zip(typeargs.iter().cloned())
.filter_map(|(a, b)| {
let b = follow_bindings_in_cache(&b, cache);
if TypeVariable(a) != b {
Some((a, b))
} else {
None
}
})
.collect()
}
/// Given `a` returns `ref a`
fn ref_of(mutability: Mutability, typ: Type, cache: &mut ModuleCache) -> Type {
let sharedness = Box::new(next_type_variable(cache));
let mutability = match mutability {
Mutability::Polymorphic => Box::new(next_type_variable(cache)),
Mutability::Immutable => Box::new(Type::Tag(TypeTag::Immutable)),
Mutability::Mutable => Box::new(Type::Tag(TypeTag::Mutable)),
};
let lifetime = Box::new(next_type_variable(cache));
let constructor = Box::new(Type::Ref { sharedness, mutability, lifetime });
TypeApplication(constructor, vec![typ])
}
/// Replace any typevars found in typevars_to_replace with the
/// associated value in the same table, leave them otherwise
fn replace_typevars(
typ: &Type, typevars_to_replace: &HashMap<TypeVariableId, TypeVariableId>, cache: &ModuleCache<'_>,
) -> Type {
let typevars_to_replace = typevars_to_replace.iter().map(|(key, id)| (*key, TypeVariable(*id))).collect();
bind_typevars(typ, &typevars_to_replace, cache)
}
/// Return a new type with all typevars found in the given type
/// replaced with fresh ones, along with the type bindings used.
///
/// Note that unlike `generalize(typ).instantiate(..)`, this will
/// replace all type variables rather than only type variables
/// that have not originated from an outer scope.
pub fn replace_all_typevars(types: &[Type], cache: &mut ModuleCache<'_>) -> (Vec<Type>, TypeBindings) {
let mut bindings = HashMap::new();
let types = fmap(types, |typ| replace_all_typevars_with_bindings(typ, &mut bindings, cache));
(types, bindings)
}
/// Replace all type variables in the given type, using new_bindings
/// to lookup what each variable should be bound to, inserting a
/// fresh type variable into new_bindings if that type variable was not present.
pub fn replace_all_typevars_with_bindings(
typ: &Type, new_bindings: &mut TypeBindings, cache: &mut ModuleCache<'_>,
) -> Type {
match typ {
Primitive(p) => Primitive(*p),
Tag(tag) => Tag(*tag),
TypeVariable(id) => replace_typevar_with_binding(*id, new_bindings, cache),
Function(function) => {
let parameters = fmap(&function.parameters, |parameter| {
replace_all_typevars_with_bindings(parameter, new_bindings, cache)
});
let return_type = Box::new(replace_all_typevars_with_bindings(&function.return_type, new_bindings, cache));
let environment = Box::new(replace_all_typevars_with_bindings(&function.environment, new_bindings, cache));
let is_varargs = function.has_varargs;
let effects = Box::new(replace_all_typevars_with_bindings(&function.effects, new_bindings, cache));
Function(FunctionType { parameters, return_type, environment, has_varargs: is_varargs, effects })
},
UserDefined(id) => UserDefined(*id),
Ref { mutability, sharedness, lifetime } => {
let mutability = Box::new(replace_all_typevars_with_bindings(mutability, new_bindings, cache));
let sharedness = Box::new(replace_all_typevars_with_bindings(sharedness, new_bindings, cache));
let lifetime = Box::new(replace_all_typevars_with_bindings(lifetime, new_bindings, cache));
Ref { sharedness, mutability, lifetime }
},
TypeApplication(typ, args) => {
let typ = replace_all_typevars_with_bindings(typ, new_bindings, cache);
let args = fmap(args, |arg| replace_all_typevars_with_bindings(arg, new_bindings, cache));
TypeApplication(Box::new(typ), args)
},
Struct(fields, id) => {
if let Some(binding) = new_bindings.get(id) {
binding.clone()
} else {
let fields = fields
.iter()
.map(|(name, typ)| {
let typ = replace_all_typevars_with_bindings(typ, new_bindings, cache);
(name.clone(), typ)
})
.collect();
Struct(fields, *id)
}
},
Effects(effects) => effects.replace_all_typevars_with_bindings(new_bindings, cache),
}
}
/// If the given TypeVariableId is unbound then return the matching binding in new_bindings.
/// If there is no binding found, instantiate a new type variable and use that.
pub fn replace_typevar_with_binding(
id: TypeVariableId, new_bindings: &mut TypeBindings, cache: &mut ModuleCache<'_>,
) -> Type {
if let Bound(typ) = &cache.type_bindings[id.0] {
replace_all_typevars_with_bindings(&typ.clone(), new_bindings, cache)
} else if let Some(var) = new_bindings.get(&id) {
var.clone()
} else {
let new_typevar = next_type_variable_id(cache);
let typ = Type::TypeVariable(new_typevar);
new_bindings.insert(id, typ.clone());
typ
}
}
/// Replace any typevars found with the given type bindings
///
/// Compared to `replace_all_typevars_with_bindings`, this function does not instantiate
/// unbound type variables that were not in type_bindings. Thus if type_bindings is empty,
/// this function will just clone the original Type.
pub fn bind_typevars(typ: &Type, type_bindings: &TypeBindings, cache: &ModuleCache<'_>) -> Type {
match typ {
Primitive(p) => Primitive(*p),
Tag(tag) => Tag(*tag),
TypeVariable(id) => bind_typevar(*id, type_bindings, cache),
Function(function) => {
let parameters = fmap(&function.parameters, |parameter| bind_typevars(parameter, type_bindings, cache));
let return_type = Box::new(bind_typevars(&function.return_type, type_bindings, cache));
let environment = Box::new(bind_typevars(&function.environment, type_bindings, cache));
let is_varargs = function.has_varargs;
let effects = Box::new(bind_typevars(&function.effects, type_bindings, cache));
Function(FunctionType { parameters, return_type, environment, has_varargs: is_varargs, effects })
},
UserDefined(id) => UserDefined(*id),
Ref { mutability, sharedness, lifetime } => {
let mutability = Box::new(bind_typevars(mutability, type_bindings, cache));
let sharedness = Box::new(bind_typevars(sharedness, type_bindings, cache));
let lifetime = Box::new(bind_typevars(lifetime, type_bindings, cache));
Ref { sharedness, mutability, lifetime }
},
TypeApplication(typ, args) => {
let typ = bind_typevars(typ, type_bindings, cache);
let args = fmap(args, |arg| bind_typevars(arg, type_bindings, cache));
TypeApplication(Box::new(typ), args)
},
Struct(fields, id) => {
match type_bindings.get(id) {
Some(TypeVariable(binding_id)) => {
let fields = fields
.iter()
.map(|(name, field)| (name.clone(), bind_typevars(field, type_bindings, cache)))
.collect();
Struct(fields, *binding_id)
},
// TODO: Should we follow all typevars here?
Some(binding) => binding.clone(),
None => {
if let Bound(typ) = &cache.type_bindings[id.0] {
bind_typevars(&typ.clone(), type_bindings, cache)
} else {
let fields = fields
.iter()
.map(|(name, typ)| {
let typ = bind_typevars(typ, type_bindings, cache);
(name.clone(), typ)
})
.collect();
Struct(fields, *id)
}
},
}
},
Effects(effects) => effects.bind_typevars(type_bindings, cache),
}
}
/// Helper for bind_typevars which binds a single TypeVariableId if it is Unbound
/// and it is found in the type_bindings. If a type_binding wasn't found, a
/// default TypeVariable is constructed.
fn bind_typevar(id: TypeVariableId, type_bindings: &TypeBindings, cache: &ModuleCache<'_>) -> Type {
// TODO: This ordering of checking type_bindings first is important.
// There seems to be an issue currently where forall-bound variables
// can be bound in the cache, so checking the cache for bindings first
// can prevent us from instantiating these variables.
match type_bindings.get(&id) {
Some(binding) => binding.clone(),
None => {
if let Bound(typ) = &cache.type_bindings[id.0] {
bind_typevars(&typ.clone(), type_bindings, cache)
} else {
Type::TypeVariable(id)
}
},
}
}
/// Recurse on typ, returning true if it contains any of the TypeVariableIds
/// contained within list.
pub fn contains_any_typevars_from_list(typ: &Type, list: &[TypeVariableId], cache: &ModuleCache<'_>) -> bool {
match typ {
Primitive(_) => false,
UserDefined(_) => false,
Tag(_) => false,
TypeVariable(id) => type_variable_contains_any_typevars_from_list(*id, list, cache),
Function(function) => {
function.parameters.iter().any(|parameter| contains_any_typevars_from_list(parameter, list, cache))
|| contains_any_typevars_from_list(&function.return_type, list, cache)
|| contains_any_typevars_from_list(&function.environment, list, cache)
|| contains_any_typevars_from_list(&function.effects, list, cache)
},
Ref { mutability, sharedness, lifetime } => {
contains_any_typevars_from_list(mutability, list, cache)
|| contains_any_typevars_from_list(sharedness, list, cache)
|| contains_any_typevars_from_list(lifetime, list, cache)
},
TypeApplication(typ, args) => {
contains_any_typevars_from_list(typ, list, cache)
|| args.iter().any(|arg| contains_any_typevars_from_list(arg, list, cache))
},
Struct(fields, id) => {
type_variable_contains_any_typevars_from_list(*id, list, cache)
|| fields.iter().any(|(_, field)| contains_any_typevars_from_list(field, list, cache))
},
Effects(effects) => effects.contains_any_typevars_from_list(list, cache),
}
}
fn type_variable_contains_any_typevars_from_list(
id: TypeVariableId, list: &[TypeVariableId], cache: &ModuleCache<'_>,
) -> bool {
if let Bound(typ) = &cache.type_bindings[id.0] {
contains_any_typevars_from_list(typ, list, cache)
} else {
list.contains(&id)
}
}
/// Helper function for getting the next type variable at the current level
pub fn next_type_variable_id(cache: &mut ModuleCache) -> TypeVariableId {
let level = LetBindingLevel(CURRENT_LEVEL.load(Ordering::SeqCst));
cache.next_type_variable_id(level)
}
pub fn next_type_variable(cache: &mut ModuleCache) -> Type {
let level = LetBindingLevel(CURRENT_LEVEL.load(Ordering::SeqCst));
cache.next_type_variable(level)
}
fn to_trait_constraints(
id: DefinitionInfoId, scope: ImplScopeId, callsite: VariableId, cache: &mut ModuleCache,
) -> TraitConstraints {
let info = &cache.definition_infos[id.0];
let current_constraint_id = &mut cache.current_trait_constraint_id;
let mut traits = fmap(&info.required_traits, |required_trait| {
let id = current_constraint_id.next();
required_trait.as_constraint(scope, callsite, id)
});
// If this definition is from a trait, we must add the initial constraint directly
if let Some((trait_id, args)) = &info.trait_info {
let id = current_constraint_id.next();
traits.push(TraitConstraint {
required: RequiredTrait {
signature: ConstraintSignature { trait_id: *trait_id, args: args.clone(), id },
callsite: Callsite::Direct(callsite),
},
scope,
});
}
traits
}
/// specializes the polytype s by copying the term and replacing the
/// bound type variables consistently by new monotype variables.
/// Returns the type bindings used to instantiate the type.
///
/// E.g. instantiate (forall a b. a -> b -> a) = c -> d -> c
///
/// This will also instantiate each given trait constraint, replacing
/// each free typevar of the constraint's argument types.
impl GeneralizedType {
pub fn instantiate(
&self, mut constraints: TraitConstraints, cache: &mut ModuleCache<'_>,
) -> (Type, TraitConstraints, TypeBindings) {
// Note that the returned type is no longer a PolyType,
// this means it is now monomorphic and not forall-quantified
match self {
GeneralizedType::MonoType(typ) => (typ.clone(), constraints, HashMap::new()),
GeneralizedType::PolyType(typevars, typ) => {
// Must replace all typevars in typ and the required_traits list with new ones
let mut typevars_to_replace = HashMap::new();
for var in typevars.iter().copied() {
typevars_to_replace.insert(var, next_type_variable_id(cache));
}
let typ = replace_typevars(typ, &typevars_to_replace, cache);
for var in find_all_typevars_in_traits(&constraints, cache).iter().copied() {
typevars_to_replace.entry(var).or_insert_with(|| next_type_variable_id(cache));
}
for constraint in constraints.iter_mut() {
for typ in constraint.args_mut() {
*typ = replace_typevars(typ, &typevars_to_replace, cache);
}
}
let type_bindings = typevars_to_replace.into_iter().map(|(k, v)| (k, TypeVariable(v))).collect();
(typ, constraints, type_bindings)
},
}
}
}
/// Similar to instantiate but uses an explicitly passed map to map
/// the old type variables to. This version is used during trait impl
/// type inference to ensure all definitions in the trait impl are
/// mapped to the same typevars, rather than each definition instantiated
/// separately as is normal.
///
/// This version is also different in that it also replaces the type variables
/// of monotypes.
fn instantiate_impl_with_bindings(
typ: &GeneralizedType, bindings: &mut TypeBindings, cache: &mut ModuleCache<'_>,
) -> GeneralizedType {
use GeneralizedType::*;
match typ {
MonoType(typ) => MonoType(replace_all_typevars_with_bindings(typ, bindings, cache)),
PolyType(_, typ) => {
// unreachable!("Impl already inferred to have polymorphic typ, {}", typ.debug(cache)),
MonoType(replace_all_typevars_with_bindings(typ, bindings, cache))
},
}
}
fn find_binding(id: TypeVariableId, map: &UnificationBindings, cache: &ModuleCache<'_>) -> TypeBinding {
match &cache.type_bindings[id.0] {
Bound(typ) => Bound(typ.clone()),
Unbound(level, kind) => match map.bindings.get(&id) {
Some(typ) => Bound(typ.clone()),
None => Unbound(*level, kind.clone()),
},
}
}
pub(super) struct OccursResult {
occurs: bool,
level_bindings: LevelBindings,
}
impl OccursResult {
pub(super) fn does_not_occur() -> OccursResult {
OccursResult { occurs: false, level_bindings: vec![] }
}
fn new(occurs: bool, level_bindings: LevelBindings) -> OccursResult {
OccursResult { occurs, level_bindings }
}
fn then(mut self, mut f: impl FnMut() -> OccursResult) -> OccursResult {
if !self.occurs {
let mut other = f();
self.occurs = other.occurs;
self.level_bindings.append(&mut other.level_bindings);
}
self
}
pub(super) fn then_all<'a>(
mut self, types: impl IntoIterator<Item = &'a Type>, mut f: impl FnMut(&'a Type) -> OccursResult,
) -> OccursResult {
if !self.occurs {
for typ in types {
let mut other = f(typ);
self.occurs = other.occurs;
self.level_bindings.append(&mut other.level_bindings);
if self.occurs {
return self;
}
}
}
self
}
}
/// Can a monomorphic TypeVariable(id) be found inside this type?
/// This will mutate any typevars found to increase their LetBindingLevel.
/// Doing so increases the lifetime of the typevariable and lets us keep
/// track of which type variables to generalize later on. It also means
/// that occurs should only be called during unification however.
pub(super) fn occurs(
id: TypeVariableId, level: LetBindingLevel, typ: &Type, bindings: &mut UnificationBindings, fuel: u32,
cache: &mut ModuleCache<'_>,
) -> OccursResult {
if fuel == 0 {
panic!("Recursion limit reached in occurs");
}
let fuel = fuel - 1;
match typ {
Primitive(_) => OccursResult::does_not_occur(),
UserDefined(_) => OccursResult::does_not_occur(),
Tag(_) => OccursResult::does_not_occur(),
TypeVariable(var_id) => typevars_match(id, level, *var_id, bindings, fuel, cache),
Function(function) => occurs_in_function(id, level, function, bindings, fuel, cache),
TypeApplication(typ, args) => occurs(id, level, typ, bindings, fuel, cache)
.then_all(args, |arg| occurs(id, level, arg, bindings, fuel, cache)),
Ref { mutability, sharedness, lifetime } => occurs(id, level, mutability, bindings, fuel, cache)
.then(|| occurs(id, level, sharedness, bindings, fuel, cache))
.then(|| occurs(id, level, lifetime, bindings, fuel, cache)),
Struct(fields, var_id) => typevars_match(id, level, *var_id, bindings, fuel, cache)
.then_all(fields.iter().map(|(_, typ)| typ), |field| occurs(id, level, field, bindings, fuel, cache)),
Effects(effects) => effects.occurs(id, level, bindings, fuel, cache),
}
}
pub(super) fn occurs_in_function(
id: TypeVariableId, level: LetBindingLevel, function: &FunctionType, bindings: &mut UnificationBindings, fuel: u32,
cache: &mut ModuleCache<'_>,
) -> OccursResult {
occurs(id, level, &function.return_type, bindings, fuel, cache)
.then(|| occurs(id, level, &function.environment, bindings, fuel, cache))
.then(|| occurs(id, level, &function.effects, bindings, fuel, cache))
.then_all(&function.parameters, |param| occurs(id, level, param, bindings, fuel, cache))
}
/// Helper function for the `occurs` check.
///
/// Recurse within `haystack` to try to find an Unbound typevar and check if it
/// has the same Id as the needle TypeVariableId.
pub(super) fn typevars_match(
needle: TypeVariableId, level: LetBindingLevel, haystack: TypeVariableId, bindings: &mut UnificationBindings,
fuel: u32, cache: &mut ModuleCache<'_>,
) -> OccursResult {
match find_binding(haystack, bindings, cache) {
Bound(binding) => occurs(needle, level, &binding, bindings, fuel, cache),
Unbound(original_level, _) => {
let binding = if level < original_level { vec![(needle, level)] } else { vec![] };
OccursResult::new(needle == haystack, binding)
},
}
}
/// Returns what a given type is bound to, following all typevar links until it reaches an Unbound one.
pub fn follow_bindings_in_cache_and_map(typ: &Type, bindings: &UnificationBindings, cache: &ModuleCache<'_>) -> Type {
match typ {
TypeVariable(id) => match find_binding(*id, bindings, cache) {
Bound(typ) => follow_bindings_in_cache_and_map(&typ, bindings, cache),
Unbound(..) => typ.clone(),
},
_ => typ.clone(),
}
}
pub fn follow_bindings_in_cache(typ: &Type, cache: &ModuleCache<'_>) -> Type {
match typ {
TypeVariable(id) => match &cache.type_bindings[id.0] {
Bound(typ) => follow_bindings_in_cache(typ, cache),
Unbound(..) => typ.clone(),
},
_ => typ.clone(),
}
}
/// Try to unify the two given types, with the given addition set of type bindings.
/// This will not perform any binding of type variables in-place, instead it will insert
/// their mapping into the given set of bindings, letting the user of this function decide
/// whether to use the unification results or not.
///
/// If there is an error during unification, an appropriate error message is returned,
/// and the given bindings set may still be modified with prior type bindings.
///
/// This function performs the bulk of the work for the various unification functions.
#[allow(clippy::nonminimal_bool)]
pub fn try_unify_with_bindings_inner<'b>(
actual: &Type, expected: &Type, bindings: &mut UnificationBindings, location: Location<'b>,
cache: &mut ModuleCache<'b>,
) -> Result<(), ()> {
match (actual, expected) {
(Primitive(p1), Primitive(p2)) if p1 == p2 => Ok(()),
(UserDefined(id1), UserDefined(id2)) if id1 == id2 => Ok(()),
// Any type variable can be bound or unbound.
// - If bound: unify the bound type with the other type.
// - If unbound: 'unify' the LetBindingLevel of the type variable by setting
// it to the minimum scope of type variables in b. This happens within the occurs check.
// The unification of the LetBindingLevel here is a form of lifetime inference for the
// typevar and is used during generalization to determine which variables to generalize.
(TypeVariable(id), _) => {
try_unify_type_variable_with_bindings(*id, actual, expected, true, bindings, location, cache)
},
(_, TypeVariable(id)) => {
try_unify_type_variable_with_bindings(*id, expected, actual, false, bindings, location, cache)
},
(Function(function1), Function(function2)) => {
if function1.parameters.len() != function2.parameters.len() {
// Whether a function is varargs or not is never unified,
// so if one function is varargs, assume they both should be.
if !(function1.has_varargs && function2.parameters.len() >= function1.parameters.len())
&& !(function2.has_varargs && function1.parameters.len() >= function2.parameters.len())
{
return Err(());
}
}
for (a_arg, b_arg) in function1.parameters.iter().zip(function2.parameters.iter()) {
try_unify_with_bindings_inner(a_arg, b_arg, bindings, location, cache)?
}
// Reverse the arguments when checking return types to preserve
// some subtyping relations with mutable & immutable references.
try_unify_with_bindings_inner(&function2.return_type, &function1.return_type, bindings, location, cache)?;
try_unify_with_bindings_inner(&function1.environment, &function2.environment, bindings, location, cache)?;
try_unify_with_bindings_inner(&function1.effects, &function2.effects, bindings, location, cache)
},
(TypeApplication(a_constructor, a_args), TypeApplication(b_constructor, b_args)) => {
// Unify the constructors before checking the arg lengths, it gives better error messages
try_unify_with_bindings_inner(a_constructor, b_constructor, bindings, location, cache)?;
if a_args.len() != b_args.len() {
return Err(());
}
for (a_arg, b_arg) in a_args.iter().zip(b_args.iter()) {
try_unify_with_bindings_inner(a_arg, b_arg, bindings, location, cache)?;
}
Ok(())
},
// Refs have a hidden lifetime variable we need to unify here
(
Ref { sharedness: a_shared, mutability: a_mut, lifetime: a_lifetime },
Ref { sharedness: b_shared, mutability: b_mut, lifetime: b_lifetime },
) => {
try_unify_with_bindings_inner(a_shared, b_shared, bindings, location, cache)?;
try_unify_with_bindings_inner(a_mut, b_mut, bindings, location, cache)?;
try_unify_with_bindings_inner(a_lifetime, b_lifetime, bindings, location, cache)
},
// Follow any bindings here for convenience so we don't have to check if a or b
// are bound in all Struct cases below.
(Struct(_, var), t2) | (t2, Struct(_, var)) if matches!(&cache.type_bindings[var.0], Bound(_)) => {
match &cache.type_bindings[var.0] {
Bound(bound) => try_unify_with_bindings_inner(&bound.clone(), t2, bindings, location, cache),
_ => unreachable!(),
}
},
(Struct(fields1, rest1), Struct(fields2, rest2)) => {
bind_struct_fields(fields1, fields2, *rest1, *rest2, bindings, location, cache)
},
(Struct(fields1, rest), other) | (other, Struct(fields1, rest)) => {
let fields2 = get_fields(other, &[], bindings, cache)?;
bind_struct_fields_subset(fields1, &fields2, bindings, location, cache)?;
bindings.bindings.insert(*rest, other.clone());
Ok(())
},
(Effects(effects1), Effects(effects2)) => effects1.try_unify_with_bindings(effects2, bindings, cache),
(Tag(tag1), Tag(tag2)) if tag1 == tag2 => Ok(()),
// ! <: &
(Tag(TypeTag::Mutable), Tag(TypeTag::Immutable)) => Ok(()),
// owned <: shared
(Tag(TypeTag::Owned), Tag(TypeTag::Shared)) => Ok(()),
_ => Err(()),
}
}
fn bind_struct_fields<'c>(
fields1: &BTreeMap<String, Type>, fields2: &BTreeMap<String, Type>, rest1: TypeVariableId, rest2: TypeVariableId,
bindings: &mut UnificationBindings, location: Location<'c>, cache: &mut ModuleCache<'c>,
) -> Result<(), ()> {
let mut new_fields = fields1.clone();
for (name, typ2) in fields2 {
if let Some(typ1) = new_fields.get(name) {
try_unify_with_bindings_inner(typ1, typ2, bindings, location, cache)?;
} else {
new_fields.insert(name.clone(), typ2.clone());
}
}
if new_fields.len() != fields1.len() && new_fields.len() != fields2.len() {
try_unify_type_variable_with_bindings(
rest1,
&TypeVariable(rest1),
&TypeVariable(rest2),
true,
bindings,
location,
cache,
)?;
let new_rest = new_row_variable(rest1, rest2, cache);
let new_struct = Struct(new_fields, new_rest);
// We set rest1 := rest2 above, so we should insert into rest2 to bind both structs
bindings.bindings.insert(rest2, new_struct);
} else if new_fields.len() != fields1.len() {
// Set 1 := 2
let struct2 = Struct(new_fields, rest2);
try_unify_type_variable_with_bindings(rest1, &TypeVariable(rest1), &struct2, true, bindings, location, cache)?;
} else if new_fields.len() != fields2.len() {
// Set 2 := 1
let struct1 = Struct(new_fields, rest1);
try_unify_type_variable_with_bindings(rest2, &TypeVariable(rest2), &struct1, false, bindings, location, cache)?;
}
Ok(())
}
/// Create a new row variable with a LetBindingLevel of the min of the
/// levels of the two given row variables. Expects both given variables
/// to be unbound.
fn new_row_variable(row1: TypeVariableId, row2: TypeVariableId, cache: &mut ModuleCache) -> TypeVariableId {
match (&cache.type_bindings[row1.0], &cache.type_bindings[row2.0]) {
(Unbound(level1, _), Unbound(level2, _)) => {
let new_level = std::cmp::min(*level1, *level2);
cache.next_type_variable_id(new_level)
},
_ => unreachable!(),
}
}
/// Like bind_struct_fields but enforces `fields` must be a subset of the fields in the template.
fn bind_struct_fields_subset<'c>(
fields: &BTreeMap<String, Type>, template: &BTreeMap<String, Type>, bindings: &mut UnificationBindings,
location: Location<'c>, cache: &mut ModuleCache<'c>,
) -> Result<(), ()> {
// FIXME: Enforcing a struct type's fields are a subset of
// a data type's fields works for cases like
// ```
// foo bar = bar.x
//
// type T = x: i32, y: i32
// foo (T 2)
// ```
// But for the following case it'd be unsound if we ever allowed struct literals:
// ```
// baz (t: T) = t.x + t.y
//
// baz { x: 3 }
// ```
// Since the struct has a subset of T's fields this would currently pass.
if fields.len() > template.len() {
return Err(());
}
for (name, field) in fields {
match template.get(name) {
Some(template_field) => {
try_unify_with_bindings_inner(template_field, field, bindings, location, cache)?;
},
None => return Err(()),
}
}
Ok(())
}
fn get_fields(
typ: &Type, args: &[Type], bindings: &mut UnificationBindings, cache: &mut ModuleCache<'_>,
) -> Result<BTreeMap<String, Type>, ()> {
match typ {
UserDefined(id) => {
let info = &cache[*id];
match &info.body {
TypeInfoBody::Alias(typ) => get_fields(&typ.clone(), args, bindings, cache),
TypeInfoBody::Union(_) => Err(()),
TypeInfoBody::Unknown => unreachable!(),
TypeInfoBody::Struct(fields) => {
let mut more_bindings = HashMap::new();
if !args.is_empty() {
more_bindings = type_application_bindings(info, args, cache);
}
Ok(fields
.iter()
.map(|field| {
let typ = if more_bindings.is_empty() {
field.field_type.clone()
} else {
bind_typevars(&field.field_type, &more_bindings, cache)
};
(field.name.clone(), typ)
})
.collect())
},
}
},
TypeApplication(constructor, args) => match follow_bindings_in_cache_and_map(constructor, bindings, cache) {
Ref { .. } => get_fields(&args[0], &[], bindings, cache),
other => get_fields(&other, args, bindings, cache),
},
Struct(fields, rest) => match &cache.type_bindings[rest.0] {
Bound(binding) => get_fields(&binding.clone(), args, bindings, cache),
Unbound(_, _) => Ok(fields.clone()),
},
TypeVariable(id) => match &cache.type_bindings[id.0] {
Bound(binding) => get_fields(&binding.clone(), args, bindings, cache),
Unbound(_, _) => Err(()),
},
_ => Err(()),
}
}
/// Unify a single type variable (id arising from the type a) with an expected type b.
/// Follows the given TypeBindings in bindings and the cache if a is Bound.
fn try_unify_type_variable_with_bindings<'c>(
id: TypeVariableId, a: &Type, b: &Type, typevar_on_lhs: bool, bindings: &mut UnificationBindings,
location: Location<'c>, cache: &mut ModuleCache<'c>,
) -> Result<(), ()> {
match find_binding(id, bindings, cache) {
Bound(a) => {
if typevar_on_lhs {
try_unify_with_bindings_inner(&a, b, bindings, location, cache)
} else {
try_unify_with_bindings_inner(b, &a, bindings, location, cache)
}
},
Unbound(a_level, _a_kind) => {
// Create binding for boundTy that is currently empty.
// Ensure not to create recursive bindings to the same variable
let b = follow_bindings_in_cache_and_map(b, bindings, cache);
if *a != b {
let result = occurs(id, a_level, &b, bindings, RECURSION_LIMIT, cache);
if result.occurs {
// TODO: Need better error messages for recursive types
Err(())
} else {
bindings.bindings.insert(id, b);
Ok(())
}
} else {
Ok(())
}
},
}
}
pub fn try_unify_with_bindings<'b>(
actual: &Type, expected: &Type, bindings: &mut UnificationBindings, location: Location<'b>,
cache: &mut ModuleCache<'b>, error: TypeErrorKind,
) -> Result<(), Diagnostic<'b>> {
match try_unify_with_bindings_inner(actual, expected, bindings, location, cache) {
Ok(()) => Ok(()),
Err(()) => {
let t1 = actual.display(cache).to_string();
let t2 = expected.display(cache).to_string();
Err(Diagnostic::new(location, D::TypeError(error, t1, t2)))
},
}
}
/// A convenience wrapper for try_unify_with_bindings, creating an empty
/// set of type bindings, and returning all the newly-created bindings on success,
/// or the unification error message on error.
pub fn try_unify<'c>(
actual: &Type, expected: &Type, location: Location<'c>, cache: &mut ModuleCache<'c>, error_kind: TypeErrorKind,
) -> UnificationResult<'c> {
let mut bindings = UnificationBindings::empty();
try_unify_with_bindings(actual, expected, &mut bindings, location, cache, error_kind).map(|()| bindings)
}
/// Try to unify all the given type, with the given bindings in scope.
/// Will add new bindings to the given TypeBindings and return them all on success.
pub fn try_unify_all_with_bindings<'c>(
actual: &[Type], expected: &[Type], mut bindings: UnificationBindings, location: Location<'c>,
cache: &mut ModuleCache<'c>, error_kind: TypeErrorKind,
) -> UnificationResult<'c> {
if actual.len() != expected.len() {
// This bad error message is the reason this function isn't used within
// try_unify_with_bindings! We'd need access to the full type to give better
// errors like the other function does.
let vec1 = fmap(actual, |typ| typ.display(cache).to_string());
let vec2 = fmap(expected, |typ| typ.display(cache).to_string());
return Err(Diagnostic::new(location, D::TypeLengthMismatch(vec1, vec2)));
}
for (actual, expected) in actual.iter().zip(expected.iter()) {
try_unify_with_bindings(actual, expected, &mut bindings, location, cache, error_kind.clone())?;
}
Ok(bindings)
}
/// The same as `try_unify_all_with_bindings` but always starts with an empty set of bindings
/// and displays no error on failure.
pub fn try_unify_all_hide_error<'c>(
actual: &[Type], expected: &[Type], cache: &mut ModuleCache<'c>,
) -> UnificationResult<'c> {
let bindings = UnificationBindings::empty();
let location = Location::builtin();
try_unify_all_with_bindings(actual, expected, bindings, location, cache, TE::NeverShown)
}
/// Unifies the two given types, remembering the unification results in the cache.
/// If this operation fails, a user-facing error message is emitted.
pub fn unify<'c>(
actual: &Type, expected: &Type, location: Location<'c>, cache: &mut ModuleCache<'c>, error_kind: TypeErrorKind,
) {
perform_bindings_or_push_error(try_unify(actual, expected, location, cache, error_kind), cache);
}
/// Helper for committing to the results of try_unify.
/// Places all the typevar bindings in the cache to be remembered,
/// or otherwise prints out the given error message.
pub fn perform_bindings_or_push_error<'c>(unification_result: UnificationResult<'c>, cache: &mut ModuleCache<'c>) {
match unification_result {
Ok(bindings) => bindings.perform(cache),
Err(diagnostic) => cache.push_full_diagnostic(diagnostic),
}
}
/// Remember all the given type bindings in the cache,
/// permanently binding the given type variables to the given bindings.
fn perform_type_bindings(bindings: TypeBindings, cache: &mut ModuleCache) {
for (id, binding) in bindings.into_iter() {
cache.bind(id, binding);
}
}
fn level_is_polymorphic(level: LetBindingLevel) -> bool {
level.0 >= CURRENT_LEVEL.load(Ordering::SeqCst)
}
/// Collects all the type variables contained within typ into a Vec.
/// If polymorphic_only is true, any polymorphic type variables will be filtered out.
///
/// Since this function uses CURRENT_LEVEL when polymorphic_only = true, the function
/// should only be used with polymorphic_only = false outside of the typechecking pass.
/// Otherwise the decision of whether to propagate the variable would be incorrect.
pub fn find_all_typevars(typ: &Type, polymorphic_only: bool, cache: &ModuleCache<'_>) -> Vec<TypeVariableId> {