-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathInfer.hs
2529 lines (2030 loc) · 91 KB
/
Infer.hs
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
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
{-| This module is based on the bidirectional type-checking algorithm from:
Dunfield, Jana, and Neelakantan R. Krishnaswami. \"Complete and easy bidirectional typechecking for higher-rank polymorphism.\" ACM SIGPLAN Notices 48.9 (2013): 429-442.
The main differences from the original algorithm are:
* This uses `Control.Monad.State.Strict.StateT` to thread around
`Context`s and manipulate them instead of explicit `Context` passing as
in the original paper
* This algorithm adds support for existential quantification
* This algorithm adds support for row polymorphic and polymorphic variants
-}
module Grace.Infer
( -- * Type inference
typeOf
, typeWith
-- * Errors related to type inference
, TypeInferenceError(..)
) where
import Control.Applicative ((<|>))
import Control.Exception.Safe (Exception(..))
import Control.Monad (when)
import Control.Monad.Except (MonadError(..))
import Control.Monad.State.Strict (MonadState)
import Data.Foldable (traverse_)
import Data.Sequence (ViewL(..))
import Data.Text (Text)
import Data.Void (Void)
import Grace.Context (Context, Entry)
import Grace.Existential (Existential)
import Grace.Location (Location(..))
import Grace.Monotype (Monotype)
import Grace.Pretty (Pretty(..))
import Grace.Syntax (Syntax)
import Grace.Type (Type(..))
import Grace.Value (Value)
import qualified Control.Monad as Monad
import qualified Control.Monad.State as State
import qualified Data.Map as Map
import qualified Data.Sequence as Seq
import qualified Data.Text as Text
import qualified Grace.Context as Context
import qualified Grace.Domain as Domain
import qualified Grace.Location as Location
import qualified Grace.Monotype as Monotype
import qualified Grace.Pretty
import qualified Grace.Syntax as Syntax
import qualified Grace.Type as Type
import qualified Grace.Width as Width
import qualified Prettyprinter as Pretty
-- | Type-checking state
data Status = Status
{ count :: !Int
-- ^ Used to generate fresh unsolved variables (e.g. α̂, β̂ from the
-- original paper)
, context :: Context Location
-- ^ The type-checking context (e.g. Γ, Δ, Θ)
}
orDie :: MonadError e m => Maybe a -> e -> m a
Just x `orDie` _ = return x
Nothing `orDie` e = throwError e
-- | Generate a fresh existential variable (of any type)
fresh :: MonadState Status m => m (Existential a)
fresh = do
Status{ count = n, .. } <- State.get
State.put $! Status{ count = n + 1, .. }
return (fromIntegral n)
-- Unlike the original paper, we don't explicitly thread the `Context` around.
-- Instead, we modify the ambient state using the following utility functions:
-- | Push a new `Context` `Entry` onto the stack
push :: MonadState Status m => Entry Location -> m ()
push entry = State.modify (\s -> s { context = entry : context s })
-- | Retrieve the current `Context`
get :: MonadState Status m => m (Context Location)
get = State.gets context
-- | Set the `Context` to a new value
set :: MonadState Status m => Context Location -> m ()
set context = State.modify (\s -> s{ context })
{-| This is used to temporarily add a `Context` entry that is discarded at the
end of the entry's scope, along with any downstream entries that were
created within that same scope
-}
scoped :: MonadState Status m => Entry Location -> m r -> m r
scoped entry k = do
push entry
r <- k
State.modify (\s -> s{ context = Context.discardUpTo entry (context s) })
return r
scopedUnsolvedType :: MonadState Status m => s -> (Type.Type s -> m a) -> m a
scopedUnsolvedType location k = do
existential <- fresh
scoped (Context.MarkerType existential) do
push (Context.UnsolvedType existential)
k Type.UnsolvedType{..}
scopedUnsolvedFields :: MonadState Status m => (Type.Record s -> m a) -> m a
scopedUnsolvedFields k = do
a <- fresh
scoped (Context.MarkerFields a) do
push (Context.UnsolvedFields a)
k (Type.Fields [] (Monotype.UnsolvedFields a))
scopedUnsolvedAlternatives
:: MonadState Status m => (Type.Union s -> m a) -> m a
scopedUnsolvedAlternatives k = do
a <- fresh
scoped (Context.MarkerAlternatives a) do
push (Context.UnsolvedAlternatives a)
k (Type.Alternatives [] (Monotype.UnsolvedAlternatives a))
{-| This corresponds to the judgment:
> Γ ⊢ A
… which checks that under context Γ, the type A is well-formed
-}
wellFormedType
:: MonadError TypeInferenceError m
=> Context Location -> Type Location -> m ()
wellFormedType _Γ type0 =
case type0 of
-- UvarWF
Type.VariableType{..}
| Context.Variable Domain.Type name `elem` _Γ -> do
return ()
| otherwise -> throwError (UnboundTypeVariable location name)
-- ArrowWF
Type.Function{..} -> do
wellFormedType _Γ input
wellFormedType _Γ output
-- ForallWF
Type.Forall{..} -> do
wellFormedType (Context.Variable domain name : _Γ) type_
-- ForallWF
Type.Exists{..} -> do
wellFormedType (Context.Variable domain name : _Γ) type_
-- EvarWF / SolvedEvarWF
_A@Type.UnsolvedType{..}
| any predicate _Γ -> do
return ()
| otherwise -> do
throwError (IllFormedType location _A _Γ)
where
predicate (Context.UnsolvedType a ) = existential == a
predicate (Context.SolvedType a _) = existential == a
predicate _ = False
Type.Optional{..} -> do
wellFormedType _Γ type_
Type.List{..} -> do
wellFormedType _Γ type_
Type.Record{ fields = Type.Fields kAs Monotype.EmptyFields } -> do
traverse_ (\(_, _A) -> wellFormedType _Γ _A) kAs
Type.Record{ fields = Type.Fields kAs (Monotype.UnsolvedFields a0), .. }
| any predicate _Γ -> do
traverse_ (\(_, _A) -> wellFormedType _Γ _A) kAs
| otherwise -> do
throwError (IllFormedFields location a0 _Γ)
where
predicate (Context.UnsolvedFields a1 ) = a0 == a1
predicate (Context.SolvedFields a1 _) = a0 == a1
predicate _ = False
Type.Record{ fields = Type.Fields kAs (Monotype.VariableFields a), .. }
| Context.Variable Domain.Fields a `elem` _Γ -> do
traverse_ (\(_, _A) -> wellFormedType _Γ _A) kAs
| otherwise -> do
throwError (UnboundFields location a)
Type.Union{ alternatives = Type.Alternatives kAs Monotype.EmptyAlternatives } -> do
traverse_ (\(_, _A) -> wellFormedType _Γ _A) kAs
Type.Union{ alternatives = Type.Alternatives kAs (Monotype.UnsolvedAlternatives a0), .. }
| any predicate _Γ -> do
traverse_ (\(_, _A) -> wellFormedType _Γ _A) kAs
| otherwise -> do
throwError (IllFormedAlternatives location a0 _Γ)
where
predicate (Context.UnsolvedAlternatives a1 ) = a0 == a1
predicate (Context.SolvedAlternatives a1 _) = a0 == a1
predicate _ = False
Type.Union{ alternatives = Type.Alternatives kAs (Monotype.VariableAlternatives a), .. }
| Context.Variable Domain.Alternatives a `elem` _Γ -> do
traverse_ (\(_, _A) -> wellFormedType _Γ _A) kAs
| otherwise -> do
throwError (UnboundAlternatives location a)
Type.Scalar{} -> do
return ()
{-| This corresponds to the judgment:
> Γ ⊢ A <: B ⊣ Δ
… which updates the context Γ to produce the new context Δ, given that the
type A is a subtype of type B.
-}
subtype
:: (MonadState Status m, MonadError TypeInferenceError m)
=> Type Location -> Type Location -> m ()
subtype _A0 _B0 = do
_Γ <- get
case (_A0, _B0) of
-- <:Var
(Type.VariableType{ name = a0 }, Type.VariableType{ name = a1 })
| a0 == a1 -> do
wellFormedType _Γ _A0
-- <:Exvar
(Type.UnsolvedType{ existential = a0 }, Type.UnsolvedType{ existential = a1 })
| a0 == a1 && Context.UnsolvedType a0 `elem` _Γ -> do
return ()
-- InstantiateL
(Type.UnsolvedType{ existential = a }, _)
-- The `not (a `Type.typeFreeIn` _B)` is the "occurs check" which
-- prevents a type variable from being defined in terms of itself
-- (i.e. a type should not "occur" within itself).
--
-- Later on you'll see matching "occurs checks" for record types and
-- union types so that Fields variables and Alternatives variables
-- cannot refer to the record or union that they belong to,
-- respectively.
| not (a `Type.typeFreeIn` _B0)
&& elem (Context.UnsolvedType a) _Γ -> do
instantiateTypeL a _B0
-- InstantiateR
(_, Type.UnsolvedType{ existential = a})
| not (a `Type.typeFreeIn` _A0)
&& elem (Context.UnsolvedType a) _Γ -> do
instantiateTypeR _A0 a
-- <:→
(Type.Function{ input = _A1, output = _A2 }, Type.Function{ input= _B1, output = _B2 }) -> do
subtype _B1 _A1
_Θ <- get
-- CAREFULLY NOTE: Pay really close attention to how we need to use
-- `Context.solveType` any time we update the context. The paper
-- already mentions this, but if you forget to do this then you
-- will get bugs due to unsolved variables not getting solved
-- correctly.
--
-- A much more reliable way to fix this problem would simply be to
-- have every function (like `subtype`, `instantiateL`, …)
-- apply `solveType` to its inputs. For example, this very
-- `subtype` function could begin by doing:
--
-- _Γ <- get
-- let _A0' = Context.solveType _Γ _A0
-- let _B0' = Context.solveType _Γ _B0
--
-- … and then use _A0' and _B0' for downstream steps. If we did
-- that at the beginning of each function then everything would
-- "just work".
--
-- However, this would be more inefficient because we'd calling
-- `solveType` wastefully over and over with the exact same context
-- in many cases. So, the tradeoff here is that we get improved
-- performance if we're willing to remember to call `solveType` in
-- the right places.
subtype (Context.solveType _Θ _A2) (Context.solveType _Θ _B2)
-- One of the main extensions that is not present in the original paper
-- is the addition of existential quantification. This was actually
-- pretty easy to implement: you just take the rules for universal
-- quantification and flip them around and everything works. Elegant!
--
-- For example, the <:∃R rule is basically the same as the <:∀L rule,
-- except with the arguments flipped. Similarly, the <:∃L rule is
-- basically the same as the <:∀R rule with the arguments flipped.
-- <:∃L
(Type.Exists{..}, _) -> do
scoped (Context.Variable domain name) do
subtype type_ _B0
-- <:∀R
(_, Type.Forall{..}) -> do
scoped (Context.Variable domain name) do
subtype _A0 type_
-- <:∃R
(_, Type.Exists{ domain = Domain.Type, .. }) -> do
scopedUnsolvedType nameLocation \a ->
subtype _A0 (Type.substituteType name 0 a type_)
(_, Type.Exists{ domain = Domain.Fields, .. }) -> do
scopedUnsolvedFields \a -> do
subtype _A0 (Type.substituteFields name 0 a type_)
(_, Type.Exists{ domain = Domain.Alternatives, .. }) -> do
scopedUnsolvedAlternatives \a -> do
subtype _A0 (Type.substituteAlternatives name 0 a type_)
-- <:∀L
(Type.Forall{ domain = Domain.Type, .. }, _) -> do
scopedUnsolvedType nameLocation \a -> do
subtype (Type.substituteType name 0 a type_) _B0
(Type.Forall{ domain = Domain.Fields, .. }, _) -> do
scopedUnsolvedFields \a -> do
subtype (Type.substituteFields name 0 a type_) _B0
(Type.Forall{ domain = Domain.Alternatives, .. }, _) -> do
scopedUnsolvedAlternatives \a -> do
subtype (Type.substituteAlternatives name 0 a type_) _B0
(Type.Scalar{ scalar = s0 }, Type.Scalar{ scalar = s1 })
| s0 == s1 -> do
return ()
(Type.Optional{ type_ = _A }, Type.Optional{ type_ = _B }) -> do
subtype _A _B
(Type.List{ type_ = _A }, Type.List{ type_ = _B }) -> do
subtype _A _B
-- This is where you need to add any non-trivial subtypes. For example,
-- the following three rules specify that `Natural` is a subtype of
-- `Integer`, which is in turn a subtype of `Real`.
(Type.Scalar{ scalar = Monotype.Natural }, Type.Scalar{ scalar = Monotype.Integer }) -> do
return ()
(Type.Scalar{ scalar = Monotype.Natural }, Type.Scalar{ scalar = Monotype.Real }) -> do
return ()
(Type.Scalar{ scalar = Monotype.Integer }, Type.Scalar{ scalar = Monotype.Real }) -> do
return ()
-- Similarly, this is the rule that says that `T` is a subtype of
-- `Optional T`. If that feels unprincipled to you then delete this
-- rule.
(_, Type.Optional{..}) -> do
subtype _A0 type_
(Type.Scalar{ }, Type.Scalar{ scalar = Monotype.JSON }) -> do
return ()
(Type.List{ type_ = _A }, Type.Scalar{ scalar = Monotype.JSON }) -> do
subtype _A _B0
return ()
(Type.Record{ fields = Type.Fields kAs Monotype.EmptyFields }, Type.Scalar{ scalar = Monotype.JSON }) -> do
let process (_, _A) = do
_Γ <- get
subtype _A (Context.solveType _Γ _B0)
traverse_ process kAs
-- The type-checking code for records is the first place where we
-- implement a non-trivial type that wasn't already covered by the
-- paper, so we'll go into more detail here to explain the general
-- type-checking principles of the paper.
(_A@Type.Record{ fields = Type.Fields kAs0 fields0 }, _B@Type.Record{ fields = Type.Fields kBs0 fields1 }) -> do
let mapA = Map.fromList kAs0
let mapB = Map.fromList kBs0
let extraA = Map.difference mapA mapB
let extraB = Map.difference mapB mapA
let both = Map.intersectionWith (,) mapA mapB
let flexible Monotype.EmptyFields = False
flexible (Monotype.VariableFields _ ) = False
flexible (Monotype.UnsolvedFields _ ) = True
let okayA = Map.null extraA
|| (flexible fields1 && fields0 /= fields1)
let okayB = Map.null extraB
|| (flexible fields0 && fields0 /= fields1)
-- First we check that there are no mismatches in the record types
-- that cannot be resolved by just setting an unsolved Fields
-- variable to the right type.
--
-- For example, `{ x: Bool }` can never be a subtype of
-- `{ y: Text }`
if | not okayA && not okayB -> do
throwError (RecordTypeMismatch _A0 _B0 extraA extraB)
| not okayA -> do
throwError (RecordTypeMismatch _A0 _B0 extraA mempty)
| not okayB -> do
throwError (RecordTypeMismatch _A0 _B0 mempty extraB)
| otherwise -> do
return ()
-- If record A is a subtype of record B, then all fields in A
-- must be a subtype of the matching fields in record B
let process (_A1, _B1) = do
_Θ <- get
subtype
(Context.solveType _Θ _A1)
(Context.solveType _Θ _B1)
-- We only check fields are present in `both` records. For
-- mismatched fields present only in one record type we have to
-- skip to the next step of resolving the mismatch by solving Fields
-- variables.
traverse_ process both
-- Here is where we handle fields that were only present in one
-- record type. They still might be okay if one or both of the
-- record types has an unsolved fields variable.
case (fields0, fields1) of
-- The two records are identical, so there's nothing left to do
_ | null extraA && null extraB && fields0 == fields1 -> do
return ()
-- Both records type have unsolved Fields variables. Great!
-- This is the most flexible case, since we can replace these
-- unsolved variables with whatever fields we want to make the
-- types match.
--
-- However, it's not as simple as setting each Fields variable
-- to the extra fields from the opposing record type. For
-- example, if the two record types we're comparing are:
--
-- { x: Bool, p0 } <: { y: Text, p1 }
--
-- … then it's not correct to say:
--
-- p0 = y: Text
-- p1 = x: Bool
--
-- … because that is not the most general solution for `p0` and
-- `p1`! The actual most general solution is:
--
-- p0 = { y: Text, p2 }
-- p1 = { x: Bool, p2 }
--
-- … where `p2` is a fresh Fields type variable representing the
-- fact that both records could potentially have even more
-- fields other than `x` and `y`.
(Monotype.UnsolvedFields p0, Monotype.UnsolvedFields p1) -> do
p2 <- fresh
_Γ0 <- get
-- We have to insert p2 before both p0 and p1 within the
-- context because the bidirectional type-checking algorithm
-- requires that the context is ordered and all variables
-- within the context can only reference prior variables
-- within the context.
--
-- Since `p0` and `p1` both have to reference `p2`, then we
-- need to insert `p2` right before `p0` or `p1`, whichever
-- one comes first
let p0First = do
(_ΓR, _ΓL) <- Context.splitOnUnsolvedFields p0 _Γ0
Monad.guard (Context.UnsolvedFields p1 `elem` _ΓR)
let command =
set ( _ΓR
<> ( Context.UnsolvedFields p0
: Context.UnsolvedFields p2
: _ΓL
)
)
return command
let p1First = do
(_ΓR, _ΓL) <- Context.splitOnUnsolvedFields p1 _Γ0
Monad.guard (Context.UnsolvedFields p0 `elem` _ΓR)
let command =
set ( _ΓR
<> ( Context.UnsolvedFields p1
: Context.UnsolvedFields p2
: _ΓL
)
)
return command
case p0First <|> p1First of
Nothing -> do
throwError (MissingOneOfFields [Type.location _A0, Type.location _B0] p0 p1 _Γ)
Just setContext -> do
setContext
_Θ <- get
-- Now we solve for `p0`. This is basically saying:
--
-- p0 = { extraFieldsFromRecordB, p2 }
instantiateFieldsL
p0
(Type.location _B0)
(Context.solveRecord _Θ
(Type.Fields (Map.toList extraB)
(Monotype.UnsolvedFields p2)
)
)
_Δ <- get
-- Similarly, solve for `p1`. This is basically saying:
--
-- p1 = { extraFieldsFromRecordA, p2 }
instantiateFieldsR
(Type.location _A0)
(Context.solveRecord _Δ
(Type.Fields (Map.toList extraA)
(Monotype.UnsolvedFields p2)
)
)
p1
-- If only one of the records has a Fields variable then the
-- solution is simpler: just set the Fields variable to the
-- extra fields from the opposing record
(Monotype.UnsolvedFields p0, _) -> do
_Θ <- get
instantiateFieldsL
p0
(Type.location _B0)
(Context.solveRecord _Θ
(Type.Fields (Map.toList extraB) fields1)
)
(_, Monotype.UnsolvedFields p1) -> do
_Θ <- get
instantiateFieldsR
(Type.location _A0)
(Context.solveRecord _Θ
(Type.Fields (Map.toList extraA) fields0)
)
p1
(_, _) -> do
throwError (NotRecordSubtype (Type.location _A0) _A (Type.location _B0) _B)
-- Checking if one union is a subtype of another union is basically the
-- exact same as the logic for checking if a record is a subtype of
-- another record.
(_A@Type.Union{ alternatives = Type.Alternatives kAs0 alternatives0 }, _B@Type.Union{ alternatives = Type.Alternatives kBs0 alternatives1 }) -> do
let mapA = Map.fromList kAs0
let mapB = Map.fromList kBs0
let extraA = Map.difference mapA mapB
let extraB = Map.difference mapB mapA
let both = Map.intersectionWith (,) mapA mapB
let flexible Monotype.EmptyAlternatives = False
flexible (Monotype.VariableAlternatives _ ) = False
flexible (Monotype.UnsolvedAlternatives _ ) = True
let okayA = Map.null extraA
|| (flexible alternatives1 && alternatives0 /= alternatives1)
let okayB = Map.null extraB
|| (flexible alternatives0 && alternatives0 /= alternatives1)
if | not okayA && not okayB -> do
throwError (UnionTypeMismatch _A0 _B0 extraA extraB)
| not okayA && okayB -> do
throwError (UnionTypeMismatch _A0 _B0 extraA mempty)
| okayA && not okayB -> do
throwError (UnionTypeMismatch _A0 _B0 mempty extraB)
| otherwise -> do
return ()
let process (_A1, _B1) = do
_Θ <- get
subtype
(Context.solveType _Θ _A1)
(Context.solveType _Θ _B1)
traverse_ process both
case (alternatives0, alternatives1) of
_ | null extraA && null extraB && alternatives0 == alternatives1 -> do
return ()
(Monotype.UnsolvedAlternatives p0, Monotype.UnsolvedAlternatives p1) -> do
p2 <- fresh
_Γ0 <- get
let p0First = do
(_ΓR, _ΓL) <- Context.splitOnUnsolvedAlternatives p0 _Γ0
Monad.guard (Context.UnsolvedAlternatives p1 `elem` _ΓR)
let command =
set ( _ΓR
<> ( Context.UnsolvedAlternatives p0
: Context.UnsolvedAlternatives p2
: _ΓL
)
)
return command
let p1First = do
(_ΓR, _ΓL) <- Context.splitOnUnsolvedAlternatives p1 _Γ0
Monad.guard (Context.UnsolvedAlternatives p0 `elem` _ΓR)
let command =
set ( _ΓR
<> ( Context.UnsolvedAlternatives p1
: Context.UnsolvedAlternatives p2
: _ΓL
)
)
return command
case p0First <|> p1First of
Nothing -> do
throwError (MissingOneOfAlternatives [Type.location _A0, Type.location _B0] p0 p1 _Γ)
Just setContext -> do
setContext
_Θ <- get
instantiateAlternativesL
p0
(Type.location _B0)
(Context.solveUnion _Θ
(Type.Alternatives (Map.toList extraB)
(Monotype.UnsolvedAlternatives p2)
)
)
_Δ <- get
instantiateAlternativesR
(Type.location _A0)
(Context.solveUnion _Δ
(Type.Alternatives (Map.toList extraA)
(Monotype.UnsolvedAlternatives p2)
)
)
p1
(Monotype.EmptyAlternatives, Monotype.EmptyAlternatives) -> do
return ()
(Monotype.UnsolvedAlternatives p0, _) -> do
_Θ <- get
instantiateAlternativesL
p0
(Type.location _B0)
(Context.solveUnion _Θ
(Type.Alternatives (Map.toList extraB)
alternatives1
)
)
(Monotype.VariableAlternatives p0, Monotype.VariableAlternatives p1)
| p0 == p1 -> do
return ()
(_, Monotype.UnsolvedAlternatives p1) -> do
_Θ <- get
instantiateAlternativesR
(Type.location _A0)
(Context.solveUnion _Θ
(Type.Alternatives (Map.toList extraA)
alternatives0
)
)
p1
(_, _) -> do
throwError (NotUnionSubtype (Type.location _A0) _A (Type.location _B0) _B)
-- Unfortunately, we need to have this wildcard match at the end,
-- otherwise we'd have to specify a number of cases that is quadratic
-- in the number of `Type` constructors. That in turn means that you
-- can easily forget to add cases like:
--
-- (Type.List _A, Type.List _B) -> do
-- subtype _A _B
--
-- … because the exhaustivity checker won't warn you if you forget to
-- add that case.
--
-- The way I remember to do this is that when I add new complex types I
-- grep the codebase for all occurrences of an existing complex type
-- (like `List`), and then one of the occurrences will be here in this
-- `subtype` function and then I'll remember to add a case for my new
-- complex type here.
(_A, _B) -> do
throwError (NotSubtype (Type.location _A0) _A (Type.location _B0) _B)
{-| This corresponds to the judgment:
> Γ ⊢ α̂ :≦ A ⊣ Δ
… which updates the context Γ to produce the new context Δ, by instantiating
α̂ such that α̂ <: A.
The @instantiate*@ family of functions should really be called @solve*@
because their job is to solve an unsolved variable within the context.
However, for consistency with the paper we still name them @instantiate*@.
-}
instantiateTypeL
:: (MonadState Status m, MonadError TypeInferenceError m)
=> Existential Monotype -> Type Location -> m ()
instantiateTypeL a _A0 = do
_Γ0 <- get
(_Γ', _Γ) <- Context.splitOnUnsolvedType a _Γ0 `orDie` MissingVariable a _Γ0
let instLSolve τ = do
wellFormedType _Γ _A0
set (_Γ' <> (Context.SolvedType a τ : _Γ))
case _A0 of
-- InstLReach
Type.UnsolvedType{..}
| let _ΓL = _Γ
, Just (_ΓR, _ΓM) <- Context.splitOnUnsolvedType existential _Γ' -> do
set (_ΓR <> (Context.SolvedType existential (Monotype.UnsolvedType a) : _ΓM) <> (Context.UnsolvedType a : _ΓL))
-- InstLSolve
Type.UnsolvedType{..} -> do
instLSolve (Monotype.UnsolvedType existential)
Type.VariableType{..} -> do
instLSolve (Monotype.VariableType name)
Type.Scalar{..} -> do
instLSolve (Monotype.Scalar scalar)
-- InstLExt
Type.Exists{ domain = Domain.Type, .. } -> do
scopedUnsolvedType nameLocation \b -> do
instantiateTypeR (Type.substituteType name 0 b type_) a
Type.Exists{ domain = Domain.Fields, .. } -> do
scopedUnsolvedFields \b -> do
instantiateTypeR (Type.substituteFields name 0 b type_) a
Type.Exists{ domain = Domain.Alternatives, .. } -> do
scopedUnsolvedAlternatives \b -> do
instantiateTypeR (Type.substituteAlternatives name 0 b type_) a
-- InstLArr
Type.Function{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
a1 <- fresh
a2 <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.Function (Monotype.UnsolvedType a1) (Monotype.UnsolvedType a2)) : Context.UnsolvedType a1 : Context.UnsolvedType a2 : _ΓL))
instantiateTypeR input a1
_Θ <- get
instantiateTypeL a2 (Context.solveType _Θ output)
-- InstLAllR
Type.Forall{..} -> do
scoped (Context.Variable domain name) do
instantiateTypeL a type_
-- This case is the first example of a general pattern we have to
-- follow when solving unsolved variables.
--
-- Typically when you solve an unsolved variable (e.g. `a`) to some
-- type (e.g. `A`), you cannot just directly solve the variable as:
--
-- a = A
--
-- … because unsolved variables can only be solved to `Monotype`s, but
-- `A` is typically a `Type`.
--
-- So, instead, what you do is you solve the variable one layer at a
-- time. For example, if you try to solve `a` to (the `Type`)
-- `Optional (List Bool)`, you will actually get three solved variables
-- added to the context:
--
-- a = Optional b
-- b = List c
-- c = Bool
--
-- In other words, each time you solve one layer of a complex type, you
-- need to create a fresh unsolved variable for each inner type and
-- solve each inner unsolved variable.
--
-- This may seem really indirect and tedious, but if you try to skip
-- this one-layer-at-a-time solving process then you will likely get
-- bugs due to solved variables referring to each other out of order.
--
-- This wasn't obvious to me from reading the original paper since they
-- didn't really cover how to type-check complex types other than
-- function types.
Type.Optional{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
-- To solve `a` against `Optional _A` we create a fresh unsolved
-- variable named `a1`, …
a1 <- fresh
-- … solve `a` to `Optional a1`, taking care that `a1` comes before
-- `a` within the context, (since `a` refers to `a1`) …
set (_ΓR <> (Context.SolvedType a (Monotype.Optional (Monotype.UnsolvedType a1)) : Context.UnsolvedType a1 : _ΓL))
-- … and then solve `a1` against _A`
instantiateTypeL a1 type_
-- We solve an unsolved variable against `List` using the same
-- principles described above for solving `Optional`
Type.List{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
a1 <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.List (Monotype.UnsolvedType a1)) : Context.UnsolvedType a1 : _ΓL))
instantiateTypeL a1 type_
-- This is still the same one-layer-at-a-time principle, with a small
-- twist. In order to solve:
--
-- a = { r }
--
-- We replace `r` with a new unsolved Fields variable and then solve for
-- that Fields variable.
Type.Record{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
p <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.Record (Monotype.Fields [] (Monotype.UnsolvedFields p))) : Context.UnsolvedFields p : _ΓL))
instantiateFieldsL p (Type.location _A0) fields
-- Same principle as for `Record`, but replacing the Field variable with
-- an Alternatives variable
Type.Union{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
p <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.Union (Monotype.Alternatives [] (Monotype.UnsolvedAlternatives p))) : Context.UnsolvedAlternatives p : _ΓL))
instantiateAlternativesL p (Type.location _A0) alternatives
{-| This corresponds to the judgment:
> Γ ⊢ A ≦: α̂ ⊣ Δ
… which updates the context Γ to produce the new context Δ, by instantiating
α̂ such that A :< α̂.
-}
instantiateTypeR
:: (MonadState Status m, MonadError TypeInferenceError m)
=> Type Location -> Existential Monotype -> m ()
instantiateTypeR _A0 a = do
_Γ0 <- get
(_Γ', _Γ) <- Context.splitOnUnsolvedType a _Γ0 `orDie` MissingVariable a _Γ0
let instRSolve τ = do
wellFormedType _Γ _A0
set (_Γ' <> (Context.SolvedType a τ : _Γ))
case _A0 of
-- InstRReach
Type.UnsolvedType{..}
| let _ΓL = _Γ
, Just (_ΓR, _ΓM) <- Context.splitOnUnsolvedType existential _Γ' -> do
set (_ΓR <> (Context.SolvedType existential (Monotype.UnsolvedType a) : _ΓM) <> (Context.UnsolvedType a : _ΓL))
-- InstRSolve
Type.UnsolvedType{..} -> do
instRSolve (Monotype.UnsolvedType existential)
Type.VariableType{..} -> do
instRSolve (Monotype.VariableType name)
Type.Scalar{..} -> do
instRSolve (Monotype.Scalar scalar)
-- InstRArr
Type.Function{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
a1 <- fresh
a2 <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.Function (Monotype.UnsolvedType a1) (Monotype.UnsolvedType a2)) : Context.UnsolvedType a1 : Context.UnsolvedType a2 : _ΓL))
instantiateTypeL a1 input
_Θ <- get
instantiateTypeR (Context.solveType _Θ output) a2
-- InstRExtL
Type.Exists{..} -> do
scoped (Context.Variable domain name) do
instantiateTypeL a type_
-- InstRAllL
Type.Forall{ domain = Domain.Type, .. } -> do
scopedUnsolvedType nameLocation \b -> do
instantiateTypeR (Type.substituteType name 0 b type_) a
Type.Forall{ domain = Domain.Fields, .. } -> do
scopedUnsolvedFields \b -> do
instantiateTypeR (Type.substituteFields name 0 b type_) a
Type.Forall{ domain = Domain.Alternatives, .. } -> do
scopedUnsolvedAlternatives \b -> do
instantiateTypeR (Type.substituteAlternatives name 0 b type_) a
Type.Optional{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
a1 <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.Optional (Monotype.UnsolvedType a1)) : Context.UnsolvedType a1 : _ΓL))
instantiateTypeR type_ a1
Type.List{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'
a1 <- fresh
set (_ΓR <> (Context.SolvedType a (Monotype.List (Monotype.UnsolvedType a1)) : Context.UnsolvedType a1 : _ΓL))
instantiateTypeR type_ a1
Type.Record{..} -> do
let _ΓL = _Γ
let _ΓR = _Γ'