forked from tweag/nickel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtypecheck.rs
2107 lines (1953 loc) · 84.5 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
//! Implementation of the typechecker.
//!
//! # Mode
//!
//! Typechecking can be made in to different modes:
//! - **Strict**: correspond to traditional typechecking in strongly, statically typed languages.
//! This happens inside a `Promise` block.
//! - **Non strict**: do not enforce any typing, but still store the annotations of let bindings in
//! the environment, and continue to traverse the AST looking for other `Promise` blocks to
//! typecheck.
//!
//! The algorithm starts in non strict mode. It is switched to strict mode when entering a
//! `Promise` block, and is switched to non-strict mode when entering an `Assume` block. `Promise`
//! and `Assume` thus serve both two purposes: annotate a term with a type, and set the
//! typechecking mode.
//!
//! # Type inference
//!
//! Type inference is done via a standard unification algorithm. The type of unannotated let-bound
//! expressions (the type of `bound_exp` in `let x = bound_exp in body`) is inferred in strict
//! mode, but it is never implicitly generalized. For example, the following program is rejected:
//!
//! ```
//! // Rejected
//! Promise(Num, let id = fun x => x in seq (id "a") (id 5))
//! ```
//!
//! Indeed, `id` is given the type `_a -> _a`, where `_a` is a unification variable, but is not
//! generalized to `forall a. a -> a`. At the first call site, `_a` is unified with `Str`, and at the second
//! call site the typechecker complains that `5` is not of type `Str`.
//!
//! This restriction is on purpose, as generalization is not trivial to implement efficiently and
//! can interact with other parts of type inference. If polymorphism is required, a simple
//! annotation is sufficient:
//!
//! ```
//! // Accepted
//! Promise(Num, let id = Promise(forall a. a -> a, fun x => x) in seq (id "a") (id 5))
//! ```
//!
//! In non-strict mode, all let-bound expressions are given type `Dyn`, unless annotated.
use crate::error::TypecheckError;
use crate::eval;
use crate::identifier::Ident;
use crate::label::ty_path;
use crate::position::RawSpan;
use crate::program::ImportResolver;
use crate::term::{BinaryOp, RichTerm, StrChunk, Term, UnaryOp};
use crate::types::{AbsType, Types};
use std::collections::{HashMap, HashSet};
/// Error during the unification of two row types.
#[derive(Debug, PartialEq)]
pub enum RowUnifError {
/// The LHS had a binding that was missing in the RHS.
MissingRow(Ident),
/// The RHS had a binding that was not in the LHS.
ExtraRow(Ident),
/// There were two incompatible definitions for the same row.
RowMismatch(Ident, UnifError),
/// Tried to unify an enum row and a record row.
RowKindMismatch(Ident, Option<TypeWrapper>, Option<TypeWrapper>),
/// One of the row was ill-formed (typically, a tail was neither a row nor a variable).
///
/// This should probably not happen with proper restrictions on the parser and a correct
/// typechecking algorithm. We let it as an error for now, but it could be removed and turned
/// into a panic! in the future.
IllformedRow(TypeWrapper),
/// A [row constraint](./type.RowConstr.html) was violated.
UnsatConstr(Ident, Option<TypeWrapper>),
/// Tried to unify a type constant with another different type.
WithConst(usize, TypeWrapper),
/// Tried to unify two distinct type constants.
ConstMismatch(usize, usize),
}
impl RowUnifError {
/// Convert a row unification error to a unification error.
///
/// There is a hierarchy between error types, from the most local/specific to the most high-level:
/// - [`RowUnifError`](./enum.RowUnifError.html)
/// - [`UnifError`](./enum.UnifError.html)
/// - [`TypecheckError`](../errors/enum.TypecheckError.html)
///
/// Each level usually adds information (such as types or positions) and group different
/// specific errors into most general ones.
pub fn to_unif_err(self, left: TypeWrapper, right: TypeWrapper) -> UnifError {
match self {
RowUnifError::MissingRow(id) => UnifError::MissingRow(id, left, right),
RowUnifError::ExtraRow(id) => UnifError::ExtraRow(id, left, right),
RowUnifError::RowKindMismatch(id, tyw1, tyw2) => {
UnifError::RowKindMismatch(id, tyw1, tyw2)
}
RowUnifError::RowMismatch(id, err) => {
UnifError::RowMismatch(id, left, right, Box::new(err))
}
RowUnifError::IllformedRow(tyw) => UnifError::IllformedRow(tyw),
RowUnifError::UnsatConstr(id, tyw) => UnifError::RowConflict(id, tyw, left, right),
RowUnifError::WithConst(c, tyw) => UnifError::WithConst(c, tyw),
RowUnifError::ConstMismatch(c1, c2) => UnifError::ConstMismatch(c1, c2),
}
}
}
/// Error during the unification of two types.
#[derive(Debug, PartialEq)]
pub enum UnifError {
/// Tried to unify two incompatible types.
TypeMismatch(TypeWrapper, TypeWrapper),
/// There are two incompatible definitions for the same row.
RowMismatch(Ident, TypeWrapper, TypeWrapper, Box<UnifError>),
/// Tried to unify an enum row and a record row.
RowKindMismatch(Ident, Option<TypeWrapper>, Option<TypeWrapper>),
/// Tried to unify two distinct type constants.
ConstMismatch(usize, usize),
/// Tried to unify two rows, but an identifier of the LHS was absent from the RHS.
MissingRow(Ident, TypeWrapper, TypeWrapper),
/// Tried to unify two rows, but an identifier of the RHS was absent from the LHS.
ExtraRow(Ident, TypeWrapper, TypeWrapper),
/// A row was ill-formed.
IllformedRow(TypeWrapper),
/// Tried to unify a unification variable with a row type violating the [row
/// constraints](./type.RowConstr.html) of the variable.
RowConflict(Ident, Option<TypeWrapper>, TypeWrapper, TypeWrapper),
/// Tried to unify a type constant with another different type.
WithConst(usize, TypeWrapper),
/// A flat type, which is an opaque type corresponding to custom contracts, contained a Nickel
/// term different from a variable. Only a variables is a legal inner term of a flat type.
IllformedFlatType(RichTerm),
/// A generic type was ill-formed. Currently, this happens if a `StatRecord` or `Enum` type
/// does not contain a row type.
IllformedType(TypeWrapper),
/// An unbound type variable was referenced.
UnboundTypeVariable(Ident),
/// An error occurred when unifying the domains of two arrows.
DomainMismatch(TypeWrapper, TypeWrapper, Box<UnifError>),
/// An error occurred when unifying the codomains of two arrows.
CodomainMismatch(TypeWrapper, TypeWrapper, Box<UnifError>),
}
impl UnifError {
/// Convert a unification error to a typechecking error.
///
/// Wrapper that calls [`to_typecheck_err_`](./fn.to_typecheck_err_.html) with an empty [name
/// registry](./reporting/struct.NameReg.html).
pub fn to_typecheck_err(self, state: &State, pos_opt: &Option<RawSpan>) -> TypecheckError {
self.to_typecheck_err_(state, &mut reporting::NameReg::new(), pos_opt)
}
/// Convert a unification error to a typechecking error.
///
/// There is a hierarchy between error types, from the most local/specific to the most high-level:
/// - [`RowUnifError`](./enum.RowUnifError.html)
/// - [`UnifError`](./enum.UnifError.html)
/// - [`TypecheckError`](../errors/enum.TypecheckError.html)
///
/// Each level usually adds information (such as types or positions) and group different
/// specific errors into most general ones.
///
/// # Parameters
///
/// - `state`: the state of unification. Used to access the unification table, and the original
/// names of of unification variable or type constant.
/// - `names`: a [name registry](./reporting/struct.NameReg.html), structure used to assign
/// unique a humain-readable names to unification variables and type constants.
/// - `pos_opt`: the position span of the expression that failed to typecheck.
pub fn to_typecheck_err_(
self,
state: &State,
names: &mut reporting::NameReg,
pos_opt: &Option<RawSpan>,
) -> TypecheckError {
let pos_opt = pos_opt.as_ref().cloned();
match self {
UnifError::TypeMismatch(ty1, ty2) => TypecheckError::TypeMismatch(
reporting::to_type(state, names, ty1),
reporting::to_type(state, names, ty2),
pos_opt,
),
UnifError::RowMismatch(ident, tyw1, tyw2, err) => TypecheckError::RowMismatch(
ident,
reporting::to_type(state, names, tyw1),
reporting::to_type(state, names, tyw2),
Box::new((*err).to_typecheck_err_(state, names, &None)),
pos_opt,
),
UnifError::RowKindMismatch(id, ty1, ty2) => TypecheckError::RowKindMismatch(
id,
ty1.map(|tw| reporting::to_type(state, names, tw)),
ty2.map(|tw| reporting::to_type(state, names, tw)),
pos_opt,
),
// TODO: for now, failure to unify with a type constant causes the same error as a
// usual type mismatch. It could be nice to have a specific error message in the
// future.
UnifError::ConstMismatch(c1, c2) => TypecheckError::TypeMismatch(
reporting::to_type(state, names, TypeWrapper::Constant(c1)),
reporting::to_type(state, names, TypeWrapper::Constant(c2)),
pos_opt,
),
UnifError::WithConst(c, ty) => TypecheckError::TypeMismatch(
reporting::to_type(state, names, TypeWrapper::Constant(c)),
reporting::to_type(state, names, ty),
pos_opt,
),
UnifError::IllformedFlatType(rt) => {
TypecheckError::IllformedType(Types(AbsType::Flat(rt)))
}
UnifError::IllformedType(tyw) => {
TypecheckError::IllformedType(reporting::to_type(state, names, tyw))
}
UnifError::MissingRow(id, tyw1, tyw2) => TypecheckError::MissingRow(
id,
reporting::to_type(state, names, tyw1),
reporting::to_type(state, names, tyw2),
pos_opt,
),
UnifError::ExtraRow(id, tyw1, tyw2) => TypecheckError::ExtraRow(
id,
reporting::to_type(state, names, tyw1),
reporting::to_type(state, names, tyw2),
pos_opt,
),
UnifError::IllformedRow(tyw) => {
TypecheckError::IllformedType(reporting::to_type(state, names, tyw))
}
UnifError::RowConflict(id, tyw, left, right) => TypecheckError::RowConflict(
id,
tyw.map(|tyw| reporting::to_type(state, names, tyw)),
reporting::to_type(state, names, left),
reporting::to_type(state, names, right),
pos_opt,
),
UnifError::UnboundTypeVariable(ident) => {
TypecheckError::UnboundTypeVariable(ident, pos_opt)
}
err @ UnifError::CodomainMismatch(_, _, _)
| err @ UnifError::DomainMismatch(_, _, _) => {
let (expd, actual, path, err_final) = err.to_type_path().unwrap();
TypecheckError::ArrowTypeMismatch(
reporting::to_type(state, names, expd),
reporting::to_type(state, names, actual),
path,
Box::new(err_final.to_typecheck_err_(state, names, &None)),
pos_opt,
)
}
}
}
/// Transform a `(Co)DomainMismatch` into a type path and other data.
///
/// `(Co)DomainMismatch` can be nested: when unifying `Num -> Num -> Num` with `Num -> Bool ->
/// Num`, the resulting error is of the form `CodomainMismatch(.., DomainMismatch(..,
/// TypeMismatch(..)))`. The heading sequence of `(Co)DomainMismatch` is better represented as
/// a type path, here `[Codomain, Domain]`, while the last error of the chain -- which thus
/// cannot be a `(Co)DomainMismatch` -- is the actual cause of the unification failure.
///
/// This function breaks down a `(Co)Domain` mismatch into a more convenient representation.
///
/// # Return
///
/// Return `None` if `self` is not a `DomainMismatch` nor a `CodomainMismatch`.
///
/// Otherwise, return the following tuple:
/// - the original expected type.
/// - the original actual type.
/// - a type path pointing at the subtypes which failed to be unified.
/// - the final error, which is the actual cause of that failure.
pub fn to_type_path(self) -> Option<(TypeWrapper, TypeWrapper, ty_path::Path, Self)> {
let mut curr: Self = self;
let mut path = ty_path::Path::new();
// The original expected and actual type. They are just updated once, in the first
// iteration of the loop below.
let mut tyws: Option<(TypeWrapper, TypeWrapper)> = None;
loop {
match curr {
UnifError::DomainMismatch(
tyw1 @ TypeWrapper::Concrete(AbsType::Arrow(_, _)),
tyw2 @ TypeWrapper::Concrete(AbsType::Arrow(_, _)),
err,
) => {
tyws = tyws.or(Some((tyw1, tyw2)));
path.push(ty_path::Elem::Domain);
curr = *err;
}
UnifError::DomainMismatch(_, _, _) => panic!(
"typechecking::to_type_path(): domain mismatch error on a non arrow type"
),
UnifError::CodomainMismatch(
tyw1 @ TypeWrapper::Concrete(AbsType::Arrow(_, _)),
tyw2 @ TypeWrapper::Concrete(AbsType::Arrow(_, _)),
err,
) => {
tyws = tyws.or(Some((tyw1, tyw2)));
path.push(ty_path::Elem::Codomain);
curr = *err;
}
UnifError::CodomainMismatch(_, _, _) => panic!(
"typechecking::to_type_path(): codomain mismatch error on a non arrow type"
),
// tyws equals to `None` iff we did not even enter the case above once, i.e. if
// `self` was indeed neither a `DomainMismatch` nor a `CodomainMismatch`
_ => break tyws.map(|(expd, actual)| (expd, actual, path, curr)),
}
}
}
}
/// The typing environment.
pub type Environment = HashMap<Ident, TypeWrapper>;
/// A structure holding the two typing environments, the global and the local.
///
/// The global typing environment is constructed from the global term environment (see
/// [`eval`](../eval/fn.eval.html)) which holds the Nickel builtin functions. It is a read-only
/// shared environment used to retrieve the type of such functions.
#[derive(Debug, PartialEq, Clone)]
pub struct Envs<'a> {
global: &'a Environment,
local: Environment,
}
impl<'a> Envs<'a> {
/// Create an `Envs` value with an empty local environment from a global environment.
pub fn from_global(global: &'a Environment) -> Self {
Envs {
global,
local: Environment::new(),
}
}
/// Populate a new global typing environment from a global term environment.
pub fn mk_global(eval_env: &eval::Environment, table: &mut UnifTable) -> Environment {
eval_env
.iter()
.map(|(id, (rc, _))| {
(
id.clone(),
apparent_type(rc.borrow().body.as_ref(), table, false),
)
})
.collect()
}
/// Fetch a binding from the environment. Try first in the local environment, and then in the
/// global.
pub fn get(&self, ident: &Ident) -> Option<TypeWrapper> {
self.local
.get(ident)
.or_else(|| self.global.get(ident))
.cloned()
}
/// Wrapper to insert a new binding in the local environment.
pub fn insert(&mut self, ident: Ident, tyw: TypeWrapper) -> Option<TypeWrapper> {
self.local.insert(ident, tyw)
}
}
/// The shared state of unification.
pub struct State<'a> {
/// The import resolver, to retrieve and typecheck imports.
resolver: &'a mut dyn ImportResolver,
/// The unification table.
table: &'a mut UnifTable,
/// Row constraints.
constr: &'a mut RowConstr,
/// A mapping from unification variable or constants to the name of the corresponding type
/// variable which introduced it, if any.
///
/// Used for error reporting.
names: &'a mut HashMap<usize, Ident>,
}
/// Typecheck a term.
///
/// Return the inferred type in case of success. This is just a wrapper that calls
/// [`type_check_`](fn.type_check_.html) with a fresh unification variable as goal.
pub fn type_check(
t: &RichTerm,
global_eval_env: &eval::Environment,
resolver: &mut dyn ImportResolver,
) -> Result<Types, TypecheckError> {
let mut state = State {
resolver,
table: &mut UnifTable::new(),
constr: &mut RowConstr::new(),
names: &mut HashMap::new(),
};
let ty = TypeWrapper::Ptr(new_var(state.table));
let global = Envs::mk_global(global_eval_env, state.table);
type_check_(&mut state, Envs::from_global(&global), false, t, ty.clone())?;
Ok(to_type(&state.table, ty))
}
/// Typecheck a term using the given global typing environment. Same as
/// [`type_check`](./fun.type_check.html), but it directly takes a global typing environment,
/// instead of building one from a term environment as `type_check` does.
///
/// This function is used to typecheck an import in a clean environment, when we don't have access
/// to the original term environment anymore, and hence cannot call `type_check` directly, but we
/// already have built a global typing environment.
///
/// Return the inferred type in case of success. This is just a wrapper that calls
/// [`type_check_`](fn.type_check_.html) with a fresh unification variable as goal.
pub fn type_check_in_env(
t: &RichTerm,
global: &Environment,
resolver: &mut dyn ImportResolver,
) -> Result<Types, TypecheckError> {
let mut state = State {
resolver,
table: &mut UnifTable::new(),
constr: &mut RowConstr::new(),
names: &mut HashMap::new(),
};
let ty = TypeWrapper::Ptr(new_var(state.table));
type_check_(&mut state, Envs::from_global(global), false, t, ty.clone())?;
Ok(to_type(&state.table, ty))
}
/// Typecheck a term against a specific type.
///
/// # Arguments
///
/// - `state`: the unification state (see [`State`](struct.State.html)).
/// - `env`: the typing environment, mapping free variable to types.
/// - `strict`: the typechecking mode.
/// - `t`: the term to check.
/// - `ty`: the type to check the term against.
fn type_check_(
state: &mut State,
mut envs: Envs,
strict: bool,
rt: &RichTerm,
ty: TypeWrapper,
) -> Result<(), TypecheckError> {
let RichTerm { term: t, pos } = rt;
match t.as_ref() {
Term::Bool(_) => unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Bool()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos)),
Term::Num(_) => unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Num()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos)),
Term::Str(_) => unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Str()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos)),
Term::StrChunks(chunks) => {
unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Str()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
chunks
.iter()
.try_for_each(|chunk| -> Result<(), TypecheckError> {
match chunk {
StrChunk::Literal(_) => Ok(()),
StrChunk::Expr(t) => type_check_(
state,
envs.clone(),
strict,
t,
TypeWrapper::Concrete(AbsType::Dyn()),
),
}
})
}
Term::Fun(x, t) => {
let src = TypeWrapper::Ptr(new_var(state.table));
// TODO what to do here, this makes more sense to me, but it means let x = foo in bar
// behaves quite different to (\x.bar) foo, worth considering if it's ok to type these two differently
// let src = TypeWrapper::The(AbsType::Dyn());
let trg = TypeWrapper::Ptr(new_var(state.table));
let arr =
TypeWrapper::Concrete(AbsType::arrow(Box::new(src.clone()), Box::new(trg.clone())));
unify(state, strict, ty, arr).map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
envs.insert(x.clone(), src);
type_check_(state, envs, strict, t, trg)
}
Term::List(terms) => {
unify(state, strict, ty, TypeWrapper::Concrete(AbsType::List()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
terms
.iter()
.try_for_each(|t| -> Result<(), TypecheckError> {
// Since lists elements are checked against the type `Dyn`, it does not make sense
// to typecheck them even in strict mode, as this will always fails, unless they
// are annotated with an `Assume(Dyn, ..)`, which will always succeed.
type_check_(
state,
envs.clone(),
false,
t,
TypeWrapper::Concrete(AbsType::Dyn()),
)
})
}
Term::Lbl(_) => {
// TODO implement lbl type
unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Dyn()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos))
}
Term::Let(x, re, rt) => {
let ty_let = apparent_type(re.as_ref(), state.table, strict);
type_check_(state, envs.clone(), strict, re, ty_let.clone())?;
// TODO move this up once lets are rec
envs.insert(x.clone(), ty_let);
type_check_(state, envs, strict, rt, ty)
}
Term::App(e, t) => {
let src = TypeWrapper::Ptr(new_var(state.table));
let arr = TypeWrapper::Concrete(AbsType::arrow(Box::new(src.clone()), Box::new(ty)));
// This order shouldn't be changed, since applying a function to a record
// may change how it's typed (static or dynamic)
// This is good hint a bidirectional algorithm would make sense...
type_check_(state, envs.clone(), strict, e, arr)?;
type_check_(state, envs, strict, t, src)
}
Term::Var(x) => {
let x_ty = envs
.get(&x)
.ok_or_else(|| TypecheckError::UnboundIdentifier(x.clone(), pos.clone()))?;
let instantiated = instantiate_foralls_with(state, x_ty.clone(), TypeWrapper::Ptr);
unify(state, strict, ty, instantiated)
.map_err(|err| err.to_typecheck_err(state, &rt.pos))
}
Term::Enum(id) => {
let row = TypeWrapper::Ptr(new_var(state.table));
unify(
state,
strict,
ty,
TypeWrapper::Concrete(AbsType::Enum(Box::new(TypeWrapper::Concrete(
AbsType::RowExtend(id.clone(), None, Box::new(row)),
)))),
)
.map_err(|err| err.to_typecheck_err(state, &rt.pos))
}
Term::Record(stat_map) | Term::RecRecord(stat_map) => {
// For recursive records, we look at the apparent type of each field and bind it in
// env before actually typechecking the content of fields
if let Term::RecRecord(_) = t.as_ref() {
envs.local.extend(
stat_map.iter().map(|(id, rt)| {
(id.clone(), apparent_type(rt.as_ref(), state.table, strict))
}),
);
}
let root_ty = if let TypeWrapper::Ptr(p) = ty {
get_root(state.table, p)
} else {
ty.clone()
};
if let TypeWrapper::Concrete(AbsType::DynRecord(rec_ty)) = root_ty.clone() {
// Checking for an dynamic record
stat_map
.into_iter()
.try_for_each(|(_, t)| -> Result<(), TypecheckError> {
type_check_(state, envs.clone(), strict, t, (*rec_ty).clone())
})
} else {
let row = stat_map.into_iter().try_fold(
TypeWrapper::Concrete(AbsType::RowEmpty()),
|acc, (id, field)| -> Result<TypeWrapper, TypecheckError> {
// In the case of a recursive record, new types (either type variables or
// annotations) have already be determined and put in the typing
// environment, and we need to use the same.
let ty = if let Term::RecRecord(_) = t.as_ref() {
envs.get(&id).unwrap().clone()
} else {
TypeWrapper::Ptr(new_var(state.table))
};
type_check_(state, envs.clone(), strict, field, ty.clone())?;
Ok(TypeWrapper::Concrete(AbsType::RowExtend(
id.clone(),
Some(Box::new(ty)),
Box::new(acc),
)))
},
)?;
unify(
state,
strict,
ty,
TypeWrapper::Concrete(AbsType::StaticRecord(Box::new(row))),
)
.map_err(|err| err.to_typecheck_err(state, &rt.pos))
}
}
Term::Op1(op, t) => {
let ty_op = get_uop_type(state, envs.clone(), strict, op)?;
let src = TypeWrapper::Ptr(new_var(state.table));
let arr = TypeWrapper::Concrete(AbsType::arrow(Box::new(src.clone()), Box::new(ty)));
unify(state, strict, arr, ty_op).map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
type_check_(state, envs.clone(), strict, t, src)
}
Term::Op2(op, e, t) => {
let ty_op = get_bop_type(state, envs.clone(), strict, op)?;
let src1 = TypeWrapper::Ptr(new_var(state.table));
let src2 = TypeWrapper::Ptr(new_var(state.table));
let arr = TypeWrapper::Concrete(AbsType::arrow(
Box::new(src1.clone()),
Box::new(TypeWrapper::Concrete(AbsType::arrow(
Box::new(src2.clone()),
Box::new(ty),
))),
));
unify(state, strict, arr, ty_op).map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
type_check_(state, envs.clone(), strict, e, src1)?;
type_check_(state, envs, strict, t, src2)
}
Term::Promise(ty2, _, t) => {
let tyw2 = to_typewrapper(ty2.clone());
let instantiated = instantiate_foralls_with(state, tyw2, TypeWrapper::Constant);
unify(state, strict, ty.clone(), to_typewrapper(ty2.clone()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
type_check_(state, envs, true, t, instantiated)
}
Term::Assume(ty2, _, t) => {
unify(state, strict, ty.clone(), to_typewrapper(ty2.clone()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos))?;
let new_ty = TypeWrapper::Ptr(new_var(state.table));
type_check_(state, envs, false, t, new_ty)
}
Term::Sym(_) => unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Sym()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos)),
Term::Wrapped(_, t)
| Term::DefaultValue(t)
| Term::ContractWithDefault(_, _, t)
| Term::Docstring(_, t) => type_check_(state, envs, strict, t, ty),
Term::Contract(_, _) => Ok(()),
Term::Import(_) => unify(state, strict, ty, TypeWrapper::Concrete(AbsType::Dyn()))
.map_err(|err| err.to_typecheck_err(state, &rt.pos)),
Term::ResolvedImport(file_id) => {
let t = state
.resolver
.get(file_id.clone())
.expect("Internal error: resolved import not found ({:?}) during typechecking.");
type_check_in_env(&t, envs.global, state.resolver).map(|_ty| ())
}
}
}
/// Determine the apparent type of a let-bound expression.
///
/// When a let-binding `let x = bound_exp in body` is processed, the type of `bound_exp` must be
/// determined to be associated to the bound variable `x` in the typing environment (`typed_vars`).
/// Then, future occurrences of `x` can be given this type when used in a `Promise` block.
///
/// The role of `apparent_type` is precisely to determine the type of `bound_exp`:
/// - if `bound_exp` is annotated by an `Assume` or a `Promise`, use the user-provided type.
/// - Otherwise:
/// * in non strict mode, we won't (and possibly can't) infer the type of `bound_exp`: just
/// return `Dyn`.
/// * in strict mode, we will typecheck `bound_exp`: return a new unification variable to be
/// associated to `bound_exp`.
fn apparent_type(t: &Term, table: &mut UnifTable, strict: bool) -> TypeWrapper {
match t {
Term::Assume(ty, _, _) | Term::Promise(ty, _, _) => to_typewrapper(ty.clone()),
_ if strict => TypeWrapper::Ptr(new_var(table)),
_ => TypeWrapper::Concrete(AbsType::Dyn()),
}
}
/// The types on which the unification algorithm operates, which may be either a concrete type, a
/// type constant or a unification variable.
#[derive(Clone, PartialEq, Debug)]
pub enum TypeWrapper {
/// A concrete type (like `Num` or `Str -> Str`).
Concrete(AbsType<Box<TypeWrapper>>),
/// A rigid type constant which cannot be unified with anything but itself.
Constant(usize),
/// A unification variable.
Ptr(usize),
}
impl TypeWrapper {
pub fn subst(self, id: Ident, to: TypeWrapper) -> TypeWrapper {
use self::TypeWrapper::*;
match self {
Concrete(AbsType::Var(ref i)) if *i == id => to,
Concrete(AbsType::Var(i)) => Concrete(AbsType::Var(i)),
Concrete(AbsType::Forall(i, t)) => {
if i == id {
Concrete(AbsType::Forall(i, t))
} else {
let tt = *t;
Concrete(AbsType::Forall(i, Box::new(tt.subst(id, to))))
}
}
// Trivial recursion
Concrete(AbsType::Dyn()) => Concrete(AbsType::Dyn()),
Concrete(AbsType::Num()) => Concrete(AbsType::Num()),
Concrete(AbsType::Bool()) => Concrete(AbsType::Bool()),
Concrete(AbsType::Str()) => Concrete(AbsType::Str()),
Concrete(AbsType::Sym()) => Concrete(AbsType::Sym()),
Concrete(AbsType::Flat(t)) => Concrete(AbsType::Flat(t)),
Concrete(AbsType::Arrow(s, t)) => {
let fs = s.subst(id.clone(), to.clone());
let ft = t.subst(id, to);
Concrete(AbsType::Arrow(Box::new(fs), Box::new(ft)))
}
Concrete(AbsType::RowEmpty()) => Concrete(AbsType::RowEmpty()),
Concrete(AbsType::RowExtend(tag, ty, rest)) => Concrete(AbsType::RowExtend(
tag,
ty.map(|x| Box::new(x.subst(id.clone(), to.clone()))),
Box::new(rest.subst(id, to)),
)),
Concrete(AbsType::Enum(row)) => Concrete(AbsType::Enum(Box::new(row.subst(id, to)))),
Concrete(AbsType::StaticRecord(row)) => {
Concrete(AbsType::StaticRecord(Box::new(row.subst(id, to))))
}
Concrete(AbsType::DynRecord(def_ty)) => {
Concrete(AbsType::DynRecord(Box::new(def_ty.subst(id, to))))
}
Concrete(AbsType::List()) => Concrete(AbsType::List()),
Constant(x) => Constant(x),
Ptr(x) => Ptr(x),
}
}
}
/// Look for a binding in a row, or add a new one if it is not present and if allowed by [row
/// constraints](type.RowConstr.html).
///
/// The row may be given as a concrete type or as a unification variable.
///
/// # Return
///
/// The type newly bound to `id` in the row together with the tail of the new row. If `id` was
/// already in `r`, it does not change the binding and return the corresponding type instead as a
/// first component.
fn row_add(
state: &mut State,
id: &Ident,
ty: Option<Box<TypeWrapper>>,
mut r: TypeWrapper,
) -> Result<(Option<Box<TypeWrapper>>, TypeWrapper), RowUnifError> {
if let TypeWrapper::Ptr(p) = r {
r = get_root(state.table, p);
}
match r {
TypeWrapper::Concrete(AbsType::RowEmpty()) => Err(RowUnifError::MissingRow(id.clone())),
TypeWrapper::Concrete(AbsType::RowExtend(id2, ty2, r2)) => {
if *id == id2 {
Ok((ty2, *r2))
} else {
let (extracted_type, subrow) = row_add(state, id, ty, *r2)?;
Ok((
extracted_type,
TypeWrapper::Concrete(AbsType::RowExtend(id2, ty2, Box::new(subrow))),
))
}
}
TypeWrapper::Ptr(root) => {
if let Some(set) = state.constr.get(&root) {
if set.contains(&id) {
return Err(RowUnifError::UnsatConstr(id.clone(), ty.map(|tyw| *tyw)));
}
}
let new_row = TypeWrapper::Ptr(new_var(state.table));
constraint(state, new_row.clone(), id.clone())?;
state.table.insert(
root,
Some(TypeWrapper::Concrete(AbsType::RowExtend(
id.clone(),
ty.clone(),
Box::new(new_row.clone()),
))),
);
Ok((ty, new_row))
}
other => Err(RowUnifError::IllformedRow(other)),
}
}
/// Try to unify two types.
///
/// A wrapper around `unify_` which just checks if `strict` is set to true. If not, it directly
/// returns `Ok(())` without unifying anything.
pub fn unify(
state: &mut State,
strict: bool,
t1: TypeWrapper,
t2: TypeWrapper,
) -> Result<(), UnifError> {
if strict {
unify_(state, t1, t2)
} else {
Ok(())
}
}
/// Try to unify two types.
pub fn unify_(
state: &mut State,
mut t1: TypeWrapper,
mut t2: TypeWrapper,
) -> Result<(), UnifError> {
if let TypeWrapper::Ptr(pt1) = t1 {
t1 = get_root(state.table, pt1);
}
if let TypeWrapper::Ptr(pt2) = t2 {
t2 = get_root(state.table, pt2);
}
// t1 and t2 are roots of the type
match (t1, t2) {
(TypeWrapper::Concrete(s1), TypeWrapper::Concrete(s2)) => match (s1, s2) {
(AbsType::Dyn(), AbsType::Dyn()) => Ok(()),
(AbsType::Num(), AbsType::Num()) => Ok(()),
(AbsType::Bool(), AbsType::Bool()) => Ok(()),
(AbsType::Str(), AbsType::Str()) => Ok(()),
(AbsType::List(), AbsType::List()) => Ok(()),
(AbsType::Sym(), AbsType::Sym()) => Ok(()),
(AbsType::Arrow(s1s, s1t), AbsType::Arrow(s2s, s2t)) => {
unify_(state, (*s1s).clone(), (*s2s).clone()).map_err(|err| {
UnifError::DomainMismatch(
TypeWrapper::Concrete(AbsType::Arrow(s1s.clone(), s1t.clone())),
TypeWrapper::Concrete(AbsType::Arrow(s2s.clone(), s2t.clone())),
Box::new(err),
)
})?;
unify_(state, (*s1t).clone(), (*s2t).clone()).map_err(|err| {
UnifError::CodomainMismatch(
TypeWrapper::Concrete(AbsType::Arrow(s1s, s1t)),
TypeWrapper::Concrete(AbsType::Arrow(s2s, s2t)),
Box::new(err),
)
})
}
(AbsType::Flat(s), AbsType::Flat(t)) => match (s.as_ref(), t.as_ref()) {
(Term::Var(vs), Term::Var(ts)) if vs == ts => Ok(()),
(Term::Var(_), Term::Var(_)) => Err(UnifError::TypeMismatch(
TypeWrapper::Concrete(AbsType::Flat(s)),
TypeWrapper::Concrete(AbsType::Flat(t)),
)),
(Term::Var(_), _) => Err(UnifError::IllformedFlatType(t)),
_ => Err(UnifError::IllformedFlatType(s)),
},
(r1, r2) if r1.is_row_type() && r2.is_row_type() => {
unify_rows(state, r1.clone(), r2.clone()).map_err(|err| {
err.to_unif_err(TypeWrapper::Concrete(r1), TypeWrapper::Concrete(r2))
})
}
(AbsType::Enum(tyw1), AbsType::Enum(tyw2)) => match (*tyw1, *tyw2) {
(TypeWrapper::Concrete(r1), TypeWrapper::Concrete(r2))
if r1.is_row_type() && r2.is_row_type() =>
{
unify_rows(state, r1.clone(), r2.clone()).map_err(|err| {
err.to_unif_err(
TypeWrapper::Concrete(AbsType::Enum(Box::new(TypeWrapper::Concrete(
r1,
)))),
TypeWrapper::Concrete(AbsType::Enum(Box::new(TypeWrapper::Concrete(
r2,
)))),
)
})
}
(TypeWrapper::Concrete(r), _) if !r.is_row_type() => Err(UnifError::IllformedType(
TypeWrapper::Concrete(AbsType::Enum(Box::new(TypeWrapper::Concrete(r)))),
)),
(_, TypeWrapper::Concrete(r)) if !r.is_row_type() => Err(UnifError::IllformedType(
TypeWrapper::Concrete(AbsType::Enum(Box::new(TypeWrapper::Concrete(r)))),
)),
(tyw1, tyw2) => unify_(state, tyw1, tyw2),
},
(AbsType::StaticRecord(tyw1), AbsType::StaticRecord(tyw2)) => match (*tyw1, *tyw2) {
(TypeWrapper::Concrete(r1), TypeWrapper::Concrete(r2))
if r1.is_row_type() && r2.is_row_type() =>
{
unify_rows(state, r1.clone(), r2.clone()).map_err(|err| {
err.to_unif_err(
TypeWrapper::Concrete(AbsType::StaticRecord(Box::new(
TypeWrapper::Concrete(r1),
))),
TypeWrapper::Concrete(AbsType::StaticRecord(Box::new(
TypeWrapper::Concrete(r2),
))),
)
})
}
(TypeWrapper::Concrete(r), _) if !r.is_row_type() => {
Err(UnifError::IllformedType(TypeWrapper::Concrete(
AbsType::StaticRecord(Box::new(TypeWrapper::Concrete(r))),
)))
}
(_, TypeWrapper::Concrete(r)) if !r.is_row_type() => {
Err(UnifError::IllformedType(TypeWrapper::Concrete(
AbsType::StaticRecord(Box::new(TypeWrapper::Concrete(r))),
)))
}
(tyw1, tyw2) => unify_(state, tyw1, tyw2),
},
(AbsType::DynRecord(t), AbsType::DynRecord(t2)) => unify_(state, *t, *t2),
(AbsType::Forall(i1, t1t), AbsType::Forall(i2, t2t)) => {
// Very stupid (slow) implementation
let constant_type = TypeWrapper::Constant(new_var(state.table));
unify_(
state,
t1t.subst(i1, constant_type.clone()),
t2t.subst(i2, constant_type),
)
}
(AbsType::Var(ident), _) | (_, AbsType::Var(ident)) => {
Err(UnifError::UnboundTypeVariable(ident))
}
(ty1, ty2) => Err(UnifError::TypeMismatch(
TypeWrapper::Concrete(ty1),
TypeWrapper::Concrete(ty2),
)),
},
(TypeWrapper::Ptr(r1), TypeWrapper::Ptr(r2)) => {
if r1 != r2 {
let mut r1_constr = state.constr.remove(&r1).unwrap_or_default();
let mut r2_constr = state.constr.remove(&r2).unwrap_or_default();
state
.constr
.insert(r1, r1_constr.drain().chain(r2_constr.drain()).collect());
state.table.insert(r1, Some(TypeWrapper::Ptr(r2)));
}
Ok(())
}
(TypeWrapper::Ptr(p), s @ TypeWrapper::Concrete(_))
| (TypeWrapper::Ptr(p), s @ TypeWrapper::Constant(_))
| (s @ TypeWrapper::Concrete(_), TypeWrapper::Ptr(p))
| (s @ TypeWrapper::Constant(_), TypeWrapper::Ptr(p)) => {
state.table.insert(p, Some(s));
Ok(())
}
(TypeWrapper::Constant(i1), TypeWrapper::Constant(i2)) if i1 == i2 => Ok(()),
(TypeWrapper::Constant(i1), TypeWrapper::Constant(i2)) => {
Err(UnifError::ConstMismatch(i1, i2))
}
(ty, TypeWrapper::Constant(i)) | (TypeWrapper::Constant(i), ty) => {
Err(UnifError::WithConst(i, ty))
}
}
}
/// Try to unify two row types. Return an [`IllformedRow`](./enum.RowUnifError.html#variant.IllformedRow) error if one of the given type
/// is not a row type.
pub fn unify_rows(
state: &mut State,
t1: AbsType<Box<TypeWrapper>>,
t2: AbsType<Box<TypeWrapper>>,
) -> Result<(), RowUnifError> {
match (t1, t2) {
(AbsType::RowEmpty(), AbsType::RowEmpty()) => Ok(()),
(AbsType::RowEmpty(), AbsType::RowExtend(ident, _, _))
| (AbsType::RowExtend(ident, _, _), AbsType::RowEmpty()) => {
Err(RowUnifError::ExtraRow(ident))
}
(AbsType::RowExtend(id, ty, t), r2 @ AbsType::RowExtend(_, _, _)) => {
let (ty2, t2_tail) =
row_add(state, &id, ty.clone(), TypeWrapper::Concrete(r2.clone()))?;
match (ty, ty2) {
(None, None) => Ok(()),
(Some(ty), Some(ty2)) => unify_(state, *ty, *ty2)
.map_err(|err| RowUnifError::RowMismatch(id.clone(), err)),
(ty1, ty2) => Err(RowUnifError::RowKindMismatch(
id,
ty1.map(|t| *t),
ty2.map(|t| *t),
)),
}?;
match (*t, t2_tail) {
(TypeWrapper::Concrete(r1_tail), TypeWrapper::Concrete(r2_tail)) => {
unify_rows(state, r1_tail, r2_tail)
}
// If one of the tail is not a concrete type, it is either a unification variable
// or a constant (rigid type variable). `unify` already knows how to treat these
// cases, so we delegate the work. However it returns `UnifError` instead of
// `RowUnifError`, hence we have a bit of wrapping and unwrapping to do. Note that