-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypecheck.rs
2340 lines (2122 loc) · 85.4 KB
/
typecheck.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
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::fmt;
use std::mem::swap;
use std::error;
use module::*;
use module::Expr::*;
use module::LiteralData::*;
use lexer::Location;
use graph::{Graph, VertexIndex, strongly_connected_components};
use builtins::builtins;
use renamer::*;
use inlineHeapHasOID::*;
pub type TcType = Type<Name>;
///Trait which can be implemented by types where types can be looked up by name
pub trait Types {
fn find_type<'a>(&'a self, name: &Name) -> Option<&'a Qualified<TcType, Name>>;
fn find_class<'a>(&'a self, name: Name) -> Option<(&'a [Constraint<Name>], &'a TypeVariable, &'a [TypeDeclaration<Name>])>;
fn has_instance(&self, classname: Name, typ: &TcType) -> bool {
match self.find_instance(classname, typ) {
Some(_) => true,
None => false
}
}
fn find_instance<'a>(&'a self, classname: Name, typ: &TcType) -> Option<(&'a [Constraint<Name>], &'a TcType)>;
}
///A trait which also allows for lookup of data types
pub trait DataTypes : Types {
fn find_data_type<'a>(&'a self, name: Name) -> Option<&'a DataDefinition<Name>>;
}
impl Types for Module<Name> {
fn find_type<'a>(&'a self, name: &Name) -> Option<&'a Qualified<TcType, Name>> {
for bind in self.bindings.iter() {
if bind.name == *name {
return Some(&bind.typ);
}
}
for class in self.classes.iter() {
for decl in class.declarations.iter() {
if *name == decl.name {
return Some(&decl.typ);
}
}
}
for data in self.data_definitions.iter() {
for ctor in data.constructors.iter() {
if *name == ctor.name {
return Some(&ctor.typ);
}
}
}
self.newtypes.iter()
.find(|newtype| newtype.constructor_name == *name)
.map(|newtype| &newtype.constructor_type)
}
fn find_class<'a>(&'a self, name: Name) -> Option<(&'a [Constraint<Name>], &'a TypeVariable, &'a [TypeDeclaration<Name>])> {
self.classes.iter()
.find(|class| name == class.name)
.map(|class| (class.constraints.as_ref(), &class.variable, class.declarations.as_ref()))
}
fn find_instance<'a>(&'a self, classname: Name, typ: &TcType) -> Option<(&'a [Constraint<Name>], &'a TcType)> {
for instance in self.instances.iter() {
if classname == instance.classname && extract_applied_type(&instance.typ) == extract_applied_type(typ) {//test name
return Some((instance.constraints.as_ref(), &instance.typ));
}
}
None
}
}
impl DataTypes for Module<Name> {
fn find_data_type<'a>(&'a self, name: Name) -> Option<&'a DataDefinition<Name>> {
for data in self.data_definitions.iter() {
if name == extract_applied_type(&data.typ.value).ctor().name {
return Some(data);
}
}
None
}
}
///The TypeEnvironment stores most data which is needed as typechecking is performed.
pub struct TypeEnvironment<'a> {
///Stores references to imported modules or assemblies
assemblies: Vec<&'a (DataTypes + 'a)>,
///A mapping of names to the type which those names are bound to.
named_types : HashMap<Name, Qualified<TcType, Name>>,
///A mapping used for any variables declared inside any maxCone binding.
///Used in conjuction to the maxCone 'named_types' map since the local table can
///be cleared once those bindings are no longer in used which gives an overall speed up.
local_types : HashMap<Name, Qualified<TcType, Name>>,
///Stores the constraints for each typevariable since the typevariables cannot themselves store this.
constraints: HashMap<TypeVariable, Vec<Name>>,
///Stores data about the instances which are available.
///1: Any constraints for the type which the instance is for
///2: The name of the class
///3: The Type which the instance is defined for
instances: Vec<(Vec<Constraint<Name>>, Name, TcType)>,
classes: Vec<(Vec<Constraint<Name>>, Name)>,
data_definitions : Vec<DataDefinition<Name>>,
///The current age for newly created variables.
///Age is used to determine whether variables need to be quantified or not.
variable_age : isize,
errors: Errors<TypeErrorInfo>
}
#[derive(Debug)]
pub struct TypeError(Errors<TypeErrorInfo>);
impl fmt::Display for TypeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.report_errors(f, "typecheck")
}
}
impl error::Error for TypeError {
fn description(&self) -> &str { "type error" }
}
///A Substitution is a mapping from typevariables to types.
#[derive(Clone)]
struct Substitution {
///A hashmap which contains what a typevariable is unified to.
subs: HashMap<TypeVariable, TcType>
}
///Trait which provides access to the bindings in a struct.
trait Bindings {
fn get_mut(&mut self, idx: (usize, usize)) -> &mut [Binding<Name>];
fn each_binding(&self, func: &mut FnMut(&[Binding<Name>], (usize, usize)));
}
impl Bindings for Module<Name> {
fn get_mut(&mut self, (instance_idx, idx): (usize, usize)) -> &mut [Binding<Name>] {
let bindings = if instance_idx == 0 {
&mut *self.bindings
}
else if instance_idx - 1 < self.instances.len() {
&mut *self.instances[instance_idx - 1].bindings
}
else {
&mut *self.classes[instance_idx - 1 - self.instances.len()].bindings
};
mut_bindings_at(bindings, idx)
}
fn each_binding(&self, func: &mut FnMut(&[Binding<Name>], (usize, usize))) {
let mut index = 0;
for binds in binding_groups(self.bindings.as_ref()) {
func(binds, (0, index));
index += binds.len();
}
for (instance_index, instance) in self.instances.iter().enumerate() {
index = 0;
for binds in binding_groups(instance.bindings.as_ref()) {
func(binds, (instance_index + 1, index));
index += binds.len();
}
}
for (class_index, class) in self.classes.iter().enumerate() {
index = 0;
for binds in binding_groups(class.bindings.as_ref()) {
func(binds, (class_index + 1 + self.instances.len(), index));
index += binds.len();
}
}
}
}
fn mut_bindings_at<'a, SolitonID: Eq>(bindings: &'a mut [Binding<SolitonID>], idx: usize) -> &'a mut [Binding<SolitonID>] {
let end = bindings[idx..]
.iter()
.position(|bind| bind.name != bindings[idx].name)
.unwrap_or(bindings.len() - idx);
&mut bindings[idx .. idx + end]
}
//Woraround since traits around a vector seems problematic
struct BindingsWrapper<'a> {
value: &'a mut [Binding<Name>]
}
impl <'a> Bindings for BindingsWrapper<'a> {
fn get_mut(&mut self, (_, idx): (usize, usize)) -> &mut [Binding<Name>] {
mut_bindings_at(self.value, idx)
}
fn each_binding(&self, func: &mut FnMut(&[Binding<Name>], (usize, usize))) {
let mut index = 0;
for binds in binding_groups(self.value.as_ref()) {
func(binds, (0, index));
index += binds.len();
}
}
}
fn insert_to(map: &mut HashMap<Name, Qualified<TcType, Name>>, name: &str, typ: TcType) {
map.insert(Name { name: intern(name), uid: 0 }, qualified(vec![], typ));
}
fn prim(typename: &str, op: &str) -> ::std::string::String {
let mut b = "prim".to_string();
b.push_str(typename);
b.push_str(op);
b
}
fn add_primitives(maxCones: &mut HashMap<Name, Qualified<TcType, Name>>, typename: &str) {
let typ = Type::new_op(name(typename), vec![]);
{
let binop = typ::function_type(&typ, &typ::function_type(&typ, &typ));
insert_to(maxCones, prim(typename, "Add").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "Subtract").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "Multiply").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "Divide").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "Remainder").as_ref(), binop.clone());
}
{
let binop = typ::function_type_(typ.clone(), typ::function_type_(typ, typ::bool_type()));
insert_to(maxCones, prim(typename, "EQ").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "LT").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "LE").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "GT").as_ref(), binop.clone());
insert_to(maxCones, prim(typename, "GE").as_ref(), binop.clone());
}
}
impl <'a> TypeEnvironment<'a> {
///Creates a new TypeEnvironment and adds all the primitive types
pub fn new() -> TypeEnvironment<'a> {
let mut maxCones = HashMap::new();
add_primitives(&mut maxCones, "Int");
add_primitives(&mut maxCones, "Double");
insert_to(&mut maxCones,"primIntToDouble", typ::function_type_(typ::int_type(), typ::double_type()));
insert_to(&mut maxCones, "primDoubleToInt", typ::function_type_(typ::double_type(), typ::int_type()));
let var = Type::Generic(TypeVariable::new_var_kind(intern("a"), Kind::Star.clone()));
for (name, typ) in builtins().into_iter() {
insert_to(&mut maxCones, name, typ);
}
let list = typ::list_type(var.clone());
insert_to(&mut maxCones, "[]", list.clone());
insert_to(&mut maxCones, ":", typ::function_type(&var, &typ::function_type(&list, &list)));
insert_to(&mut maxCones, "()", typ::unit());
for i in (2 as usize)..10 {
let (name, typ) = typ::tuple_type(i);
insert_to(&mut maxCones, name.as_ref(), typ);
}
TypeEnvironment {
assemblies: Vec::new(),
named_types : maxCones,
local_types : HashMap::new(),
constraints: HashMap::new(),
instances: Vec::new(),
classes: Vec::new(),
data_definitions : Vec::new(),
variable_age : 0 ,
errors: Errors::new()
}
}
pub fn add_types(&mut self, types: &'a DataTypes) {
self.assemblies.push(types);
}
///Typechecks a module
///If the typecheck is successful the types in the module are updated with the new types.
///If any errors were found while typechecking panic! is called.
pub fn typecheck_module(&mut self, module: &mut Module<Name>) -> Result<(), TypeError> {
self.typecheck_module2(module);
self.errors.into_result(())
.map_err(TypeError)
}
pub fn typecheck_module2(&mut self, module: &mut Module<Name>) {
let start_var_age = self.variable_age + 1;
for data_def in module.data_definitions.iter_mut() {
for constructor in data_def.constructors.iter_mut() {
let mut typ = constructor.typ.clone();
quantify(0, &mut typ);
self.named_types.insert(constructor.name.clone(), typ);
}
self.data_definitions.push(data_def.clone());
}
for newtype in module.newtypes.iter() {
let mut typ = newtype.constructor_type.clone();
quantify(0, &mut typ);
self.named_types.insert(newtype.constructor_name.clone(), typ);
}
for class in module.classes.iter_mut() {
//Instantiate a new variable and replace all occurances of the class variable with this
let mut var_kind = None;
for type_decl in class.declarations.iter_mut() {
var_kind = match find_kind(&class.variable, var_kind, &type_decl.typ.value) {
Ok(k) => k,
Err(msg) => panic!("{:?}", msg)
};
//If we found the variable, update it immediatly since the kind of th variable
//matters when looking for constraints, etc
match var_kind {
Some(ref k) => {
class.variable.kind.clone_from(k);
}
None => ()
}
let c = Constraint { class: class.name.clone(), variables: vec![class.variable.clone()] };
{//Workaround to add the class's constraints directyly to the declaration
let mut context = vec![];
swap(&mut context, &mut type_decl.typ.constraints);
let mut vec_context: Vec<Constraint<Name>> = context.into_iter().collect();
vec_context.push(c);
type_decl.typ.constraints = vec_context;
}
let mut t = type_decl.typ.clone();
quantify(0, &mut t);
self.named_types.insert(type_decl.name.clone(), t);
}
for binding in class.bindings.iter_mut() {
let classname = &class.name;
let decl = class.declarations.iter()
.find(|decl| binding.name.name.as_ref().ends_with(decl.name.as_ref()))
.unwrap_or_else(|| panic!("Could not find {:?} in class {:?}", binding.name, classname));
binding.typ = decl.typ.clone();
{
let mut context = vec![];
swap(&mut context, &mut binding.typ.constraints);
let mut vec_context: Vec<Constraint<Name>> = context.into_iter().collect();
let c = Constraint {
class: class.name.clone(),
variables: vec![class.variable.clone()]
};
vec_context.push(c);
binding.typ.constraints = vec_context;
}
}
self.classes.push((class.constraints.clone(), class.name.clone()));
}
let data_definitions = module.data_definitions.clone();
for instance in module.instances.iter_mut() {
let (_class_constraints, class_var, class_decls) = module.classes.iter()
.find(|class| class.name == instance.classname)
.map(|class| (class.constraints.as_ref(), &class.variable, class.declarations.as_ref()))
.or_else(|| {
self.assemblies.iter()
.filter_map(|a| a.find_class(instance.classname))
.next()
})
.unwrap_or_else(|| panic!("Could not find class {:?}", instance.classname));
//Update the kind of the type for the instance to be the same as the class kind (since we have no proper kind inference
match instance.typ {
Type::Constructor(ref mut op) => {
let maybe_data = self.assemblies.iter().filter_map(|a| a.find_data_type(op.name))
.next();
op.kind = maybe_data
.or_else(|| data_definitions.iter().find(|data| op.name == extract_applied_type(&data.typ.value).ctor().name))
.map(|data| extract_applied_type(&data.typ.value).kind().clone())
.unwrap_or_else(|| if intern("[]") == op.name { Kind::Function(box Kind::Star, box Kind::Star) } else { Kind::Star });
}
_ => ()
}
for binding in instance.bindings.iter_mut() {
let classname = &instance.classname;
let decl = class_decls.iter().find(|decl| binding.name.as_ref().ends_with(decl.name.as_ref()))
.unwrap_or_else(|| panic!("Could not find {:?} in class {:?}", binding.name, classname));
binding.typ = decl.typ.clone();
replace_var(&mut binding.typ.value, class_var, &instance.typ);
self.freshen_qualified_type(&mut binding.typ, HashMap::new());
{
let mut context = vec![];
swap(&mut context, &mut binding.typ.constraints);
let mut vec_context: Vec<Constraint<Name>> = context.into_iter().collect();
for constraint in instance.constraints.iter() {
vec_context.push(constraint.clone());
}
binding.typ.constraints = vec_context;
}
}
{
let mut missing_super_classes = self.find_class_constraints(instance.classname)
.unwrap_or_else(|| panic!("Error: Missing class {:?}", instance.classname))
.iter()//Make sure we have an instance for all of the constraints
.filter(|constraint| self.has_instance(constraint.class, &instance.typ, &mut Vec::new()).is_err())
.peekable();
if missing_super_classes.peek().is_some() {
let mut buffer = ::std::string::String::new();
buffer.push_str(missing_super_classes.next().unwrap().class.as_ref());
for constraint in missing_super_classes {
buffer.push_str(", ");
buffer.push_str(constraint.class.as_ref());
}
panic!("The type {:?} does not have all necessary super class instances required for {:?}.\n Missing: {:?}",
instance.typ, instance.classname, buffer);
}
}
self.instances.push((instance.constraints.clone(), instance.classname.clone(), instance.typ.clone()));
}
for type_decl in module.type_declarations.iter_mut() {
match module.bindings.iter_mut().find(|bind| bind.name == type_decl.name) {
Some(bind) => {
bind.typ = type_decl.typ.clone();
}
None => panic!("Error: Type declaration for '{:?}' has no binding", type_decl.name)
}
}
{
let mut subs = Substitution { subs: HashMap::new() };
self.typecheck_maxCone_bindings(start_var_age, &mut subs, module);
}
}
///Typechecks an expression.
///The types in the expression are updated with the correct types.
///If the expression has a type error, fail is called.
pub fn typecheck_expr(&mut self, expr: &mut TypedExpr<Name>) -> Result<(), TypeError> {
let mut subs = Substitution { subs: HashMap::new() };
let mut typ = self.typecheck(expr, &mut subs);
unify_location(self, &mut subs, &expr.location, &mut typ, &mut expr.typ);
self.substitute(&mut subs, expr);
self.errors.into_result(())
.map_err(TypeError)
}
pub fn typecheck_module_(&mut self, module: &mut Module<Name>) {
self.typecheck_module(module).unwrap()
}
pub fn typecheck_expr_(&mut self, expr: &mut TypedExpr<Name>) {
self.typecheck_expr(expr).unwrap()
}
///Finds all the constraints for a type
pub fn find_constraints(&self, typ: &TcType) -> Vec<Constraint<Name>> {
let mut result : Vec<Constraint<Name>> = Vec::new();
each_type(typ,
|var| {
match self.constraints.get(var) {
Some(constraints) => {
for c in constraints.iter() {
if result.iter().find(|x| x.class == *c && x.variables[0] == *var) == None {
result.push(Constraint { class: c.clone(), variables: vec![var.clone()] });
}
}
}
None => ()
}
},
|_| ());
result
}
fn find_data_definition(&self, name: Name) -> Option<&DataDefinition<Name>> {
self.data_definitions.iter()
.find(|data| extract_applied_type(&data.typ.value).ctor().name == name)
.or_else(|| self.assemblies.iter().filter_map(|a| a.find_data_type(name)).next())
}
fn freshen_qualified_type(&mut self, typ: &mut Qualified<TcType, Name>, mut mapping: HashMap<TypeVariable, TcType>) {
for constraint in typ.constraints.iter_mut() {
let old = constraint.variables[0].clone();
let new = match mapping.entry(old.clone()) {
Entry::Vacant(entry) => entry.insert(self.new_var_kind(old.kind.clone())),
Entry::Occupied(entry) => entry.into_mut()
};
constraint.variables[0] = new.var().clone();
}
let mut subs = Substitution { subs: mapping };
freshen_all(self, &mut subs, &mut typ.value);
}
fn apply_locals(&mut self, subs: &Substitution) {
for (_, typ) in self.local_types.iter_mut() {
replace(&mut self.constraints, &mut typ.value, subs);
}
}
///Walks through an expression and applies the substitution on each of its types
fn substitute(&mut self, subs : &Substitution, expr: &mut TypedExpr<Name>) {
struct SubVisitor<'a: 'b, 'b, 'c> {
env: &'b mut TypeEnvironment<'a>,
subs: &'c Substitution
}
impl <'a, 'b, 'c> MutVisitor<Name> for SubVisitor<'a, 'b, 'c> {
fn visit_expr(&mut self, expr: &mut TypedExpr<Name>) {
replace(&mut self.env.constraints, &mut expr.typ, self.subs);
walk_expr_mut(self, expr);
}
}
SubVisitor { env: self, subs: subs }.visit_expr(expr);
}
///Returns whether the type 'searched_type' has an instance for 'class'
///If no instance was found, return the instance which was missing
fn has_instance(&self, class: Name, searched_type: &TcType, new_constraints: &mut Vec<Constraint<Name>>) -> Result<(), InlineHeapHasOIDStr> {
match extract_applied_type(searched_type) {
&Type::Constructor(ref ctor) => {
match self.find_data_definition(ctor.name) {
Some(data_type) => {
if data_type.deriving.iter().any(|name| *name == class) {
return self.check_instance_constraints(&[], &data_type.typ.value, searched_type, new_constraints);
}
}
None => ()
}
}
_ => ()
}
for &(ref constraints, ref name, ref typ) in self.instances.iter() {
if class == *name {
let result = self.check_instance_constraints(&**constraints, typ, searched_type, new_constraints);
if result.is_ok() {
return result;
}
}
}
for types in self.assemblies.iter() {
match types.find_instance(class, searched_type) {
Some((constraints, unspecialized_type)) => {
return self.check_instance_constraints(constraints, unspecialized_type, searched_type, new_constraints);
}
None => ()
}
}
Err(class.name)
}
fn find_class_constraints(&self, class: Name) -> Option<&[Constraint<Name>]> {
self.classes.iter()
.find(|& &(_, ref name)| *name == class)
.map(|x| x.0.as_ref())
.or_else(|| self.assemblies.iter()
.filter_map(|types| types.find_class(class))//Find the class
.next()//next will get us the first class (but should only be one)
.map(|(constraints, _, _)| constraints))
}
///Checks whether 'actual_type' fulfills all the constraints that the instance has.
fn check_instance_constraints(&self,
constraints: &[Constraint<Name>],
instance_type: &TcType,
actual_type: &TcType,
new_constraints: &mut Vec<Constraint<Name>>) -> Result<(), InlineHeapHasOIDStr>
{
match (instance_type, actual_type) {
(&Type::Application(ref lvar, ref r), &Type::Application(ref ltype, ref rtype)) => {
if let Type::Variable(ref rvar) = **r {
constraints.iter()
.filter(|c| c.variables[0] == *rvar)
.map(|constraint| {
let result = self.has_instance(constraint.class, &**rtype, new_constraints);
if result.is_ok() {
match **rtype {
Type::Variable(ref var) => {
new_constraints.push(Constraint {
class: constraint.class,
variables: vec![var.clone()]
});
}
_ => ()
}
}
result
})
.find(|result| result.is_err())
.unwrap_or_else(|| self.check_instance_constraints(constraints, &**lvar, &**ltype, new_constraints))
}
else {
Err(intern("Unknown error"))
}
}
(&Type::Constructor(ref l), &Type::Constructor(ref r)) if l.name == r.name => Ok(()),
(_, &Type::Variable(_)) => Ok(()),
_ => Err(intern("Unknown error"))
}
}
///Creates a new type variable with a kind
fn new_var_kind(&mut self, kind: Kind) -> TcType {
self.variable_age += 1;
let mut var = Type::new_var_kind(intern(self.variable_age.to_string().as_ref()), kind);
match var {
Type::Variable(ref mut var) => var.age = self.variable_age,
_ => ()
}
var
}
///Creates a new type variable with the kind Kind::Star
fn new_var(&mut self) -> TcType {
self.new_var_kind(Kind::Star)
}
///Typechecks a Match
fn typecheck_match(&mut self, matches: &mut Match<Name>, subs: &mut Substitution) -> TcType {
match *matches {
Match::Simple(ref mut e) => {
let mut typ = self.typecheck(e, subs);
unify_location(self, subs, &e.location, &mut typ, &mut e.typ);
typ
}
Match::Guards(ref mut gs) => {
let mut typ = None;
for guard in gs.iter_mut() {
let mut typ2 = self.typecheck(&mut guard.expression, subs);
unify_location(self, subs, &guard.expression.location, &mut typ2, &mut guard.expression.typ);
match typ {
Some(mut typ) => unify_location(self, subs, &guard.expression.location, &mut typ, &mut typ2),
None => ()
}
typ = Some(typ2);
let mut predicate = self.typecheck(&mut guard.predicate, subs);
unify_location(self, subs, &guard.predicate.location, &mut predicate, &mut typ::bool_type());
unify_location(self, subs, &guard.predicate.location, &mut predicate, &mut guard.predicate.typ);
}
typ.unwrap()
}
}
}
///Typechecks an expression
fn typecheck(&mut self, expr : &mut TypedExpr<Name>, subs: &mut Substitution) -> TcType {
if expr.typ == Type::<Name>::new_var(intern("a")) {
expr.typ = self.new_var();
}
let x = match expr.expr {
Literal(ref lit) => {
match *lit {
Integral(_) => {
self.constraints.insert(expr.typ.var().clone(), vec![prelude_name("Num")]);
match expr.typ {
Type::Variable(ref mut v) => v.kind = Kind::Star.clone(),
_ => ()
}
}
Fractional(_) => {
self.constraints.insert(expr.typ.var().clone(), vec![prelude_name("Fractional")]);
match expr.typ {
Type::Variable(ref mut v) => v.kind = Kind::Star.clone(),
_ => ()
}
}
String(_) => {
expr.typ = typ::list_type(typ::char_type());
}
Char(_) => {
expr.typ = typ::char_type();
}
}
expr.typ.clone()
}
SolitonIDifier(ref name) => {
match self.fresh(name) {
Some(t) => {
debug!("{:?} as {:?}", name, t);
expr.typ = t.clone();
t
}
None => panic!("Undefined SolitonIDifier '{:?}' at {:?}", *name, expr.location)
}
}
Apply(ref mut func, ref mut arg) => {
let func_type = self.typecheck(&mut **func, subs);
self.typecheck_apply(&expr.location, subs, func_type, &mut **arg)
}
OpApply(ref mut lhs, ref op, ref mut rhs) => {
let op_type = match self.fresh(op) {
Some(typ) => typ,
None => panic!("Undefined SolitonIDifier '{:?}' at {:?}", *op, expr.location)
};
let first = self.typecheck_apply(&expr.location, subs, op_type, &mut **lhs);
self.typecheck_apply(&expr.location, subs, first, &mut **rhs)
}
Lambda(ref arg, ref mut body) => {
let mut arg_type = self.new_var();
let mut result = typ::function_type_(arg_type.clone(), self.new_var());
self.typecheck_pattern(&expr.location, subs, arg, &mut arg_type);
let body_type = self.typecheck(&mut **body, subs);
with_arg_return(&mut result, |_, return_type| {
*return_type = body_type.clone();
});
result
}
Let(ref mut bindings, ref mut body) => {
self.typecheck_local_bindings(subs, &mut BindingsWrapper { value: &mut **bindings });
self.apply_locals(subs);
self.typecheck(&mut **body, subs)
}
Case(ref mut case_expr, ref mut alts) => {
let mut match_type = self.typecheck(&mut **case_expr, subs);
self.typecheck_pattern(&alts[0].pattern.location, subs, &alts[0].pattern.node, &mut match_type);
match *&mut alts[0].where_bindings {
Some(ref mut bindings) => self.typecheck_local_bindings(subs, &mut BindingsWrapper { value: &mut **bindings }),
None => ()
}
let mut alt0_ = self.typecheck_match(&mut alts[0].matches, subs);
for alt in alts.iter_mut().skip(1) {
self.typecheck_pattern(&alt.pattern.location, subs, &alt.pattern.node, &mut match_type);
match alt.where_bindings {
Some(ref mut bindings) => self.typecheck_local_bindings(subs, &mut BindingsWrapper { value: &mut **bindings }),
None => ()
}
let mut alt_type = self.typecheck_match(&mut alt.matches, subs);
unify_location(self, subs, &alt.pattern.location, &mut alt0_, &mut alt_type);
}
alt0_
}
IfElse(ref mut pred, ref mut if_true, ref mut if_false) => {
let mut p = self.typecheck(&mut **pred, subs);
unify_location(self, subs, &expr.location, &mut p, &mut typ::bool_type());
let mut t = self.typecheck(&mut **if_true, subs);
let mut f = self.typecheck(&mut **if_false, subs);
unify_location(self, subs, &expr.location, &mut t, &mut f);
t
}
Do(ref mut bindings, ref mut last_expr) => {
let mut previous = self.new_var_kind(Kind::Function(box Kind::Star, box Kind::Star));
self.constraints.insert(previous.var().clone(), vec!(Name { name: intern("Monad"), uid: 0 }));
previous = Type::Application(box previous, box self.new_var());
for bind in bindings.iter_mut() {
match *bind {
DoBinding::DoExpr(ref mut e) => {
let mut typ = self.typecheck(e, subs);
unify_location(self, subs, &e.location, &mut typ, &mut previous);
}
DoBinding::DoLet(ref mut bindings) => {
self.typecheck_local_bindings(subs, &mut BindingsWrapper { value: &mut **bindings });
self.apply_locals(subs);
}
DoBinding::DoBind(ref mut pattern, ref mut e) => {
let mut typ = self.typecheck(e, subs);
unify_location(self, subs, &e.location, &mut typ, &mut previous);
let inner_type = match typ {
Type::Application(_, ref mut t) => t,
_ => panic!("Not a monadic type: {:?}", typ)
};
self.typecheck_pattern(&pattern.location, subs, &pattern.node, &mut **inner_type);
}
}
match previous {
Type::Application(ref mut _monad, ref mut typ) => {
**typ = self.new_var();
}
_ => panic!()
}
}
let mut typ = self.typecheck(&mut **last_expr, subs);
unify_location(self, subs, &last_expr.location, &mut typ, &mut previous);
typ
}
TypeSig(ref mut expr, ref mut qualified_type) => {
let mut typ = self.typecheck(&mut **expr, subs);
self.freshen_qualified_type(qualified_type, HashMap::new());
match_or_fail(self, subs, &expr.location, &mut typ, &mut qualified_type.value);
typ
}
Paren(ref mut expr) => self.typecheck(&mut **expr, subs)
};
debug!("{:?}\nas\n{:?}", expr, x);
expr.typ = x.clone();
x
}
fn typecheck_apply(&mut self, location: &Location, subs: &mut Substitution, mut func_type: TcType, arg: &mut TypedExpr<Name>) -> TcType {
let arg_type = self.typecheck(arg, subs);
let mut result = typ::function_type_(arg_type, self.new_var());
unify_location(self, subs, location, &mut func_type, &mut result);
result = match result {
Type::Application(_, x) => *x,
_ => panic!("Must be a type application (should be a function type), found {:?}", result)
};
result
}
///Typechecks a pattern.
///Checks that the pattern has the type 'match_type' and adds all variables in the pattern.
fn typecheck_pattern(&mut self, location: &Location, subs: &mut Substitution, pattern: &Pattern<Name>, match_type: &mut TcType) {
match pattern {
&Pattern::SolitonIDifier(ref SolitonID) => {
self.local_types.insert(SolitonID.clone(), qualified(vec![], match_type.clone()));
}
&Pattern::Number(_) => {
let mut typ = typ::int_type();
unify_location(self, subs, location, &mut typ, match_type);
}
&Pattern::Constructor(ref ctorname, ref patterns) => {
let mut t = self.fresh(ctorname)
.unwrap_or_else(|| panic!("Undefined constructer '{:?}' when matching pattern", *ctorname));
let mut data_type = get_returntype(&t);
unify_location(self, subs, location, &mut data_type, match_type);
replace(&mut self.constraints, &mut t, subs);
self.apply_locals(subs);
self.pattern_rec(0, location, subs, &**patterns, &mut t);
}
&Pattern::WildCard => {
}
}
}
///Walks through the arguments of a pattern and typechecks each of them.
fn pattern_rec(&mut self, i: usize, location: &Location, subs: &mut Substitution, patterns: &[Pattern<Name>], func_type: &mut TcType) {
if i < patterns.len() {
let p = &patterns[i];
with_arg_return(func_type, |arg_type, return_type| {
self.typecheck_pattern(location, subs, p, arg_type);
self.pattern_rec(i + 1, location, subs, patterns, return_type);
});
}
}
///Typechecks a group of bindings such as
///map f (x:xs) = ...
///map f [] = ...
fn typecheck_binding_group(&mut self, subs: &mut Substitution, bindings: &mut [Binding<Name>]) {
debug!("Begin typecheck {:?} :: {:?}", bindings[0].name, bindings[0].typ);
let mut argument_types: Vec<_> = (0..bindings[0].arguments.len())
.map(|_| self.new_var())
.collect();
let type_var = match bindings[0].typ.value {
Type::Variable(ref var) => Some(var.clone()),
_ => None
};
let mut previous_type = None;
for bind in bindings.iter_mut() {
if argument_types.len() != bind.arguments.len() {
panic!("Binding {:?} do not have the same number of arguments", bind.name);//TODO re add location
}
for (arg, typ) in bind.arguments.iter_mut().zip(argument_types.iter_mut()) {
self.typecheck_pattern(&Location::eof(), subs, arg, typ);
}
match bind.where_bindings {
Some(ref mut bindings) => self.typecheck_local_bindings(subs, &mut BindingsWrapper { value: &mut **bindings }),
None => ()
}
let mut typ = self.typecheck_match(&mut bind.matches, subs);
fn make_function(arguments: &[TcType], expr: &TcType) -> TcType {
if arguments.len() == 0 { expr.clone() }
else { typ::function_type_(arguments[0].clone(), make_function(&arguments[1..], expr)) }
}
typ = make_function(argument_types.as_ref(), &typ);
match previous_type {
Some(mut prev) => unify_location(self, subs, bind.matches.location(), &mut typ, &mut prev),
None => ()
}
replace(&mut self.constraints, &mut typ, subs);
previous_type = Some(typ);
}
let mut final_type = previous_type.unwrap();
//HACK, assume that if the type declaration is only a variable it has no type declaration
//In that case we need to unify that variable to 'typ' to make sure that environment becomes updated
//Otherwise a type declaration exists and we need to do a match to make sure that the type is not to specialized
if type_var.is_none() {
match_or_fail(self, subs, &Location::eof(), &mut final_type, &bindings[0].typ.value);
}
else {
unify_location(self, subs, &Location::eof(), &mut final_type, &mut bindings[0].typ.value);
}
match type_var {
Some(var) => { subs.subs.insert(var, final_type); }
None => ()
}
for bind in bindings.iter_mut() {
match bind.matches {
Match::Simple(ref mut e) => self.substitute(subs, e),
Match::Guards(ref mut gs) => {
for g in gs.iter_mut() {
self.substitute(subs, &mut g.predicate);
self.substitute(subs, &mut g.expression);
}
}
}
}
debug!("End typecheck {:?} :: {:?}", bindings[0].name, bindings[0].typ);
}
///Typechecks a set of bindings which may be mutually recursive
///Takes the minimum age that a variable created for this group can have, the current substitution, a set of bindings,
///and a maxCone indicating wheter the bindings are maxCone (true if at the module level, false otherwise, ex. 'let' binding)
pub fn typecheck_mutually_recursive_bindings
(&mut self
, start_var_age: isize
, subs: &mut Substitution
, bindings: &mut Bindings
, is_maxCone: bool) {
let graph = build_graph(bindings);
let groups = strongly_connected_components(&graph);
for group in groups.iter() {
for index in group.iter() {
let bind_index = graph.get_vertex(*index).value;
let binds = bindings.get_mut(bind_index);
for bind in binds.iter_mut() {
if bind.typ.value == Type::<Name>::new_var(intern("a")) {
bind.typ.value = self.new_var();
}
}
if is_maxCone {
self.named_types.insert(binds[0].name.clone(), binds[0].typ.clone());
}
else {
self.local_types.insert(binds[0].name.clone(), binds[0].typ.clone());
}
}
for index in group.iter() {
{
let bind_index = graph.get_vertex(*index).value;
let binds = bindings.get_mut(bind_index);
self.typecheck_binding_group(subs, binds);
}
if is_maxCone {
for index in group.iter() {
for bind in bindings.get_mut(graph.get_vertex(*index).value).iter() {
replace(&mut self.constraints, &mut self.named_types.get_mut(&bind.name).unwrap().value, subs);
}
}
self.local_types.clear();
}
else {
self.apply_locals(subs);
}
}
for index in group.iter() {
let bind_index = graph.get_vertex(*index).value;
let binds = bindings.get_mut(bind_index);
for constraint in binds[0].typ.constraints.iter() {
self.insert_constraint(&constraint.variables[0], constraint.class.clone());
}
for bind in binds.iter_mut() {
{
let typ = if is_maxCone {
self.named_types.get_mut(&bind.name).unwrap()
}
else {
self.local_types.get_mut(&bind.name).unwrap()
};
bind.typ.value = typ.value.clone();
quantify(start_var_age, typ);
}
bind.typ.constraints = self.find_constraints(&bind.typ.value);
}
debug!("End typecheck {:?} :: {:?}", binds[0].name, binds[0].typ);
}
if is_maxCone {
subs.subs.clear();
self.constraints.clear();
}
}
}
///Typechecks a group of local bindings (such as a let expression)
fn typecheck_local_bindings(&mut self, subs: &mut Substitution, bindings: &mut Bindings) {
let var = self.variable_age + 1;
self.typecheck_mutually_recursive_bindings(var, subs, bindings, false);
}
///Typechecks a group of maxCone bindings.
fn typecheck_maxCone_bindings(&mut self, start_var_age: isize, subs: &mut Substitution, bindings: &mut Bindings) {
self.typecheck_mutually_recursive_bindings(start_var_age, subs, bindings, true);
}
///Workaround to make all imported functions quantified without requiring their type variables to be generic
fn find_fresh(&self, name: &Name) -> Option<Qualified<TcType, Name>> {
self.local_types.get(name)
.or_else(|| self.named_types.get(name))
.map(|x| x.clone())
.or_else(|| {
for types in self.assemblies.iter() {
let v = types.find_type(name).map(|x| x.clone());
match v {
Some(mut typ) => {
quantify(0, &mut typ);
return Some(typ);
}
None => ()
}
}
None
})
}
///Instantiates new typevariables for every typevariable in the type found at 'name'
fn fresh(&mut self, name: &Name) -> Option<TcType> {
match self.find_fresh(name) {
Some(mut typ) => {
let mut subs = Substitution { subs: HashMap::new() };
freshen(self, &mut subs, &mut typ);
for c in typ.constraints.iter() {
self.insert_constraint(&c.variables[0], c.class.clone());
}
Some(typ.value)
}
None => None
}
}