-
Notifications
You must be signed in to change notification settings - Fork 0
/
TcUnify.lhs
1904 lines (1626 loc) · 69.2 KB
/
TcUnify.lhs
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
%
% (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
%
\section{Type subsumption and unification}
\begin{code}
module TcUnify (
-- Full-blown subsumption
tcSubExp, tcFunResTy, tcGen,
checkSigTyVars, checkSigTyVarsWrt, bleatEscapedTvs, sigCtxt,
-- Various unifications
unifyType, unifyTypeList, unifyTheta,
unifyKind, unifyKinds, unifyFunKind,
checkExpectedKind,
preSubType, boxyMatchTypes,
--------------------------------
-- Holes
tcInfer, subFunTys, unBox, stripBoxyType, withBox,
boxyUnify, boxyUnifyList, zapToMonotype,
boxySplitListTy, boxySplitTyConApp, boxySplitAppTy,
wrapFunResCoercion
) where
#include "HsVersions.h"
import HsSyn ( HsWrapper(..), idHsWrapper, isIdHsWrapper, (<.>),
mkWpLams, mkWpTyLams, mkWpApps )
import TypeRep ( Type(..), PredType(..) )
import TcMType ( lookupTcTyVar, LookupTyVarResult(..),
tcInstBoxyTyVar, newKindVar, newMetaTyVar,
newBoxyTyVar, newBoxyTyVarTys, readFilledBox,
readMetaTyVar, writeMetaTyVar, newFlexiTyVarTy,
tcInstSkolTyVars, tcInstTyVar, tcInstSkolType,
zonkTcKind, zonkType, zonkTcType, zonkTcTyVarsAndFV,
readKindVar, writeKindVar )
import TcSimplify ( tcSimplifyCheck )
import TcEnv ( tcGetGlobalTyVars, findGlobals )
import TcIface ( checkWiredInTyCon )
import TcRnMonad -- TcType, amongst others
import TcType ( TcKind, TcType, TcTyVar, BoxyTyVar, TcTauType,
BoxySigmaType, BoxyRhoType, BoxyType,
TcTyVarSet, TcThetaType, TcTyVarDetails(..), BoxInfo(..),
SkolemInfo( GenSkol, UnkSkol ), MetaDetails(..), isImmutableTyVar,
pprSkolTvBinding, isTauTy, isTauTyCon, isSigmaTy,
mkFunTy, mkFunTys, mkTyConApp, isMetaTyVar,
tcSplitForAllTys, tcSplitAppTy_maybe, tcSplitFunTys, mkTyVarTys,
tcSplitSigmaTy, tyVarsOfType, mkPhiTy, mkTyVarTy, mkPredTy,
typeKind, mkForAllTys, mkAppTy, isBoxyTyVar,
tcView, exactTyVarsOfType,
tidyOpenType, tidyOpenTyVar, tidyOpenTyVars,
pprType, tidyKind, tidySkolemTyVar, isSkolemTyVar, isSigTyVar,
TvSubst, mkTvSubst, zipTyEnv, zipOpenTvSubst, emptyTvSubst,
substTy, substTheta,
lookupTyVar, extendTvSubst )
import Type ( Kind, SimpleKind, KindVar,
openTypeKind, liftedTypeKind, unliftedTypeKind,
mkArrowKind, defaultKind,
argTypeKind, isLiftedTypeKind, isUnliftedTypeKind,
isSubKind, pprKind, splitKindFunTys, isSubKindCon,
isOpenTypeKind, isArgTypeKind )
import TysPrim ( alphaTy, betaTy )
import Inst ( newDictBndrsO, instCall, instToId )
import TyCon ( TyCon, tyConArity, tyConTyVars, isSynTyCon )
import TysWiredIn ( listTyCon )
import Id ( Id )
import Var ( Var, varName, tyVarKind, isTcTyVar, tcTyVarDetails )
import VarSet
import VarEnv
import Name ( Name, isSystemName )
import ErrUtils ( Message )
import Maybes ( expectJust, isNothing )
import BasicTypes ( Arity )
import Util ( notNull, equalLength )
import Outputable
-- Assertion imports
#ifdef DEBUG
import TcType ( isBoxyTy, isFlexi )
#endif
\end{code}
%************************************************************************
%* *
\subsection{'hole' type variables}
%* *
%************************************************************************
\begin{code}
tcInfer :: (BoxyType -> TcM a) -> TcM (a, TcType)
tcInfer tc_infer
= do { box <- newBoxyTyVar openTypeKind
; res <- tc_infer (mkTyVarTy box)
; res_ty <- readFilledBox box -- Guaranteed filled-in by now
; return (res, res_ty) }
\end{code}
%************************************************************************
%* *
subFunTys
%* *
%************************************************************************
\begin{code}
subFunTys :: SDoc -- Somthing like "The function f has 3 arguments"
-- or "The abstraction (\x.e) takes 1 argument"
-> Arity -- Expected # of args
-> BoxyRhoType -- res_ty
-> ([BoxySigmaType] -> BoxyRhoType -> TcM a)
-> TcM (HsWrapper, a)
-- Attempt to decompse res_ty to have enough top-level arrows to
-- match the number of patterns in the match group
--
-- If (subFunTys n_args res_ty thing_inside) = (co_fn, res)
-- and the inner call to thing_inside passes args: [a1,...,an], b
-- then co_fn :: (a1 -> ... -> an -> b) -> res_ty
--
-- Note that it takes a BoxyRho type, and guarantees to return a BoxyRhoType
{- Error messages from subFunTys
The abstraction `\Just 1 -> ...' has two arguments
but its type `Maybe a -> a' has only one
The equation(s) for `f' have two arguments
but its type `Maybe a -> a' has only one
The section `(f 3)' requires 'f' to take two arguments
but its type `Int -> Int' has only one
The function 'f' is applied to two arguments
but its type `Int -> Int' has only one
-}
subFunTys error_herald n_pats res_ty thing_inside
= loop n_pats [] res_ty
where
-- In 'loop', the parameter 'arg_tys' accumulates
-- the arg types so far, in *reverse order*
loop n args_so_far res_ty
| Just res_ty' <- tcView res_ty = loop n args_so_far res_ty'
loop n args_so_far res_ty
| isSigmaTy res_ty -- Do this before checking n==0, because we
-- guarantee to return a BoxyRhoType, not a BoxySigmaType
= do { (gen_fn, (co_fn, res)) <- tcGen res_ty emptyVarSet $ \ _ res_ty' ->
loop n args_so_far res_ty'
; return (gen_fn <.> co_fn, res) }
loop 0 args_so_far res_ty
= do { res <- thing_inside (reverse args_so_far) res_ty
; return (idHsWrapper, res) }
loop n args_so_far (FunTy arg_ty res_ty)
= do { (co_fn, res) <- loop (n-1) (arg_ty:args_so_far) res_ty
; co_fn' <- wrapFunResCoercion [arg_ty] co_fn
; return (co_fn', res) }
-- res_ty might have a type variable at the head, such as (a b c),
-- in which case we must fill in with (->). Simplest thing to do
-- is to use boxyUnify, but we catch failure and generate our own
-- error message on failure
loop n args_so_far res_ty@(AppTy _ _)
= do { [arg_ty',res_ty'] <- newBoxyTyVarTys [argTypeKind, openTypeKind]
; (_, mb_unit) <- tryTcErrs $ boxyUnify res_ty (FunTy arg_ty' res_ty')
; if isNothing mb_unit then bale_out args_so_far
else loop n args_so_far (FunTy arg_ty' res_ty') }
loop n args_so_far (TyVarTy tv)
| not (isImmutableTyVar tv)
= do { cts <- readMetaTyVar tv
; case cts of
Indirect ty -> loop n args_so_far ty
Flexi -> do { (res_ty:arg_tys) <- withMetaTvs tv kinds mk_res_ty
; res <- thing_inside (reverse args_so_far ++ arg_tys) res_ty
; return (idHsWrapper, res) } }
where
mk_res_ty (res_ty' : arg_tys') = mkFunTys arg_tys' res_ty'
mk_res_ty [] = panic "TcUnify.mk_res_ty1"
kinds = openTypeKind : take n (repeat argTypeKind)
-- Note argTypeKind: the args can have an unboxed type,
-- but not an unboxed tuple.
loop n args_so_far res_ty = bale_out args_so_far
bale_out args_so_far
= do { env0 <- tcInitTidyEnv
; res_ty' <- zonkTcType res_ty
; let (env1, res_ty'') = tidyOpenType env0 res_ty'
; failWithTcM (env1, mk_msg res_ty'' (length args_so_far)) }
mk_msg res_ty n_actual
= error_herald <> comma $$
sep [ptext SLIT("but its type") <+> quotes (pprType res_ty),
if n_actual == 0 then ptext SLIT("has none")
else ptext SLIT("has only") <+> speakN n_actual]
\end{code}
\begin{code}
----------------------
boxySplitTyConApp :: TyCon -- T :: k1 -> ... -> kn -> *
-> BoxyRhoType -- Expected type (T a b c)
-> TcM [BoxySigmaType] -- Element types, a b c
-- It's used for wired-in tycons, so we call checkWiredInTyCOn
-- Precondition: never called with FunTyCon
-- Precondition: input type :: *
boxySplitTyConApp tc orig_ty
= do { checkWiredInTyCon tc
; loop (tyConArity tc) [] orig_ty }
where
loop n_req args_so_far ty
| Just ty' <- tcView ty = loop n_req args_so_far ty'
loop n_req args_so_far (TyConApp tycon args)
| tc == tycon
= ASSERT( n_req == length args) -- ty::*
return (args ++ args_so_far)
loop n_req args_so_far (AppTy fun arg)
= loop (n_req - 1) (arg:args_so_far) fun
loop n_req args_so_far (TyVarTy tv)
| not (isImmutableTyVar tv)
= do { cts <- readMetaTyVar tv
; case cts of
Indirect ty -> loop n_req args_so_far ty
Flexi -> do { arg_tys <- withMetaTvs tv arg_kinds mk_res_ty
; return (arg_tys ++ args_so_far) }
}
where
mk_res_ty arg_tys' = mkTyConApp tc arg_tys'
arg_kinds = map tyVarKind (take n_req (tyConTyVars tc))
loop _ _ _ = boxySplitFailure (mkTyConApp tc (mkTyVarTys (tyConTyVars tc))) orig_ty
----------------------
boxySplitListTy :: BoxyRhoType -> TcM BoxySigmaType -- Special case for lists
boxySplitListTy exp_ty = do { [elt_ty] <- boxySplitTyConApp listTyCon exp_ty
; return elt_ty }
----------------------
boxySplitAppTy :: BoxyRhoType -- Type to split: m a
-> TcM (BoxySigmaType, BoxySigmaType) -- Returns m, a
-- Assumes (m: * -> k), where k is the kind of the incoming type
-- If the incoming type is boxy, then so are the result types; and vice versa
boxySplitAppTy orig_ty
= loop orig_ty
where
loop ty
| Just ty' <- tcView ty = loop ty'
loop ty
| Just (fun_ty, arg_ty) <- tcSplitAppTy_maybe ty
= return (fun_ty, arg_ty)
loop (TyVarTy tv)
| not (isImmutableTyVar tv)
= do { cts <- readMetaTyVar tv
; case cts of
Indirect ty -> loop ty
Flexi -> do { [fun_ty,arg_ty] <- withMetaTvs tv kinds mk_res_ty
; return (fun_ty, arg_ty) } }
where
mk_res_ty [fun_ty', arg_ty'] = mkAppTy fun_ty' arg_ty'
mk_res_ty other = panic "TcUnify.mk_res_ty2"
tv_kind = tyVarKind tv
kinds = [mkArrowKind liftedTypeKind (defaultKind tv_kind),
-- m :: * -> k
liftedTypeKind] -- arg type :: *
-- The defaultKind is a bit smelly. If you remove it,
-- try compiling f x = do { x }
-- and you'll get a kind mis-match. It smells, but
-- not enough to lose sleep over.
loop _ = boxySplitFailure (mkAppTy alphaTy betaTy) orig_ty
------------------
boxySplitFailure actual_ty expected_ty
= unifyMisMatch False False actual_ty expected_ty
-- "outer" is False, so we don't pop the context
-- which is what we want since we have not pushed one!
\end{code}
--------------------------------
-- withBoxes: the key utility function
--------------------------------
\begin{code}
withMetaTvs :: TcTyVar -- An unfilled-in, non-skolem, meta type variable
-> [Kind] -- Make fresh boxes (with the same BoxTv/TauTv setting as tv)
-> ([BoxySigmaType] -> BoxySigmaType)
-- Constructs the type to assign
-- to the original var
-> TcM [BoxySigmaType] -- Return the fresh boxes
-- It's entirely possible for the [kind] to be empty.
-- For example, when pattern-matching on True,
-- we call boxySplitTyConApp passing a boolTyCon
-- Invariant: tv is still Flexi
withMetaTvs tv kinds mk_res_ty
| isBoxyTyVar tv
= do { box_tvs <- mapM (newMetaTyVar BoxTv) kinds
; let box_tys = mkTyVarTys box_tvs
; writeMetaTyVar tv (mk_res_ty box_tys)
; return box_tys }
| otherwise -- Non-boxy meta type variable
= do { tau_tys <- mapM newFlexiTyVarTy kinds
; writeMetaTyVar tv (mk_res_ty tau_tys) -- Write it *first*
-- Sure to be a tau-type
; return tau_tys }
withBox :: Kind -> (BoxySigmaType -> TcM a) -> TcM (a, TcType)
-- Allocate a *boxy* tyvar
withBox kind thing_inside
= do { box_tv <- newMetaTyVar BoxTv kind
; res <- thing_inside (mkTyVarTy box_tv)
; ty <- readFilledBox box_tv
; return (res, ty) }
\end{code}
%************************************************************************
%* *
Approximate boxy matching
%* *
%************************************************************************
\begin{code}
preSubType :: [TcTyVar] -- Quantified type variables
-> TcTyVarSet -- Subset of quantified type variables
-- see Note [Pre-sub boxy]
-> TcType -- The rho-type part; quantified tyvars scopes over this
-> BoxySigmaType -- Matching type from the context
-> TcM [TcType] -- Types to instantiate the tyvars
-- Perform pre-subsumption, and return suitable types
-- to instantiate the quantified type varibles:
-- info from the pre-subsumption, if there is any
-- a boxy type variable otherwise
--
-- Note [Pre-sub boxy]
-- The 'btvs' are a subset of 'qtvs'. They are the ones we can
-- instantiate to a boxy type variable, because they'll definitely be
-- filled in later. This isn't always the case; sometimes we have type
-- variables mentioned in the context of the type, but not the body;
-- f :: forall a b. C a b => a -> a
-- Then we may land up with an unconstrained 'b', so we want to
-- instantiate it to a monotype (non-boxy) type variable
--
-- The 'qtvs' that are *neither* fixed by the pre-subsumption, *nor* are in 'btvs',
-- are instantiated to TauTv meta variables.
preSubType qtvs btvs qty expected_ty
= do { tys <- mapM inst_tv qtvs
; traceTc (text "preSubType" <+> (ppr qtvs $$ ppr btvs $$ ppr qty $$ ppr expected_ty $$ ppr pre_subst $$ ppr tys))
; return tys }
where
pre_subst = boxySubMatchType (mkVarSet qtvs) qty expected_ty
inst_tv tv
| Just boxy_ty <- lookupTyVar pre_subst tv = return boxy_ty
| tv `elemVarSet` btvs = do { tv' <- tcInstBoxyTyVar tv
; return (mkTyVarTy tv') }
| otherwise = do { tv' <- tcInstTyVar tv
; return (mkTyVarTy tv') }
boxySubMatchType
:: TcTyVarSet -> TcType -- The "template"; the tyvars are skolems
-> BoxyRhoType -- Type to match (note a *Rho* type)
-> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
-- boxySubMatchType implements the Pre-subsumption judgement, in Fig 5 of the paper
-- "Boxy types: inference for higher rank types and impredicativity"
boxySubMatchType tmpl_tvs tmpl_ty boxy_ty
= go tmpl_tvs tmpl_ty emptyVarSet boxy_ty
where
go t_tvs t_ty b_tvs b_ty
| Just t_ty' <- tcView t_ty = go t_tvs t_ty' b_tvs b_ty
| Just b_ty' <- tcView b_ty = go t_tvs t_ty b_tvs b_ty'
go t_tvs (TyVarTy _) b_tvs b_ty = emptyTvSubst -- Rule S-ANY; no bindings
-- Rule S-ANY covers (a) type variables and (b) boxy types
-- in the template. Both look like a TyVarTy.
-- See Note [Sub-match] below
go t_tvs t_ty b_tvs b_ty
| isSigmaTy t_ty, (tvs, _, t_tau) <- tcSplitSigmaTy t_ty
= go (t_tvs `delVarSetList` tvs) t_tau b_tvs b_ty -- Rule S-SPEC
-- Under a forall on the left, if there is shadowing,
-- do not bind! Hence the delVarSetList.
| isSigmaTy b_ty, (tvs, _, b_tau) <- tcSplitSigmaTy b_ty
= go t_tvs t_ty (extendVarSetList b_tvs tvs) b_tau -- Rule S-SKOL
-- Add to the variables we must not bind to
-- NB: it's *important* to discard the theta part. Otherwise
-- consider (forall a. Eq a => a -> b) ~<~ (Int -> Int -> Bool)
-- and end up with a completely bogus binding (b |-> Bool), by lining
-- up the (Eq a) with the Int, whereas it should be (b |-> (Int->Bool)).
-- This pre-subsumption stuff can return too few bindings, but it
-- must *never* return bogus info.
go t_tvs (FunTy arg1 res1) b_tvs (FunTy arg2 res2) -- Rule S-FUN
= boxy_match t_tvs arg1 b_tvs arg2 (go t_tvs res1 b_tvs res2)
-- Match the args, and sub-match the results
go t_tvs t_ty b_tvs b_ty = boxy_match t_tvs t_ty b_tvs b_ty emptyTvSubst
-- Otherwise defer to boxy matching
-- This covers TyConApp, AppTy, PredTy
\end{code}
Note [Sub-match]
~~~~~~~~~~~~~~~~
Consider this
head :: [a] -> a
|- head xs : <rhobox>
We will do a boxySubMatchType between a ~ <rhobox>
But we *don't* want to match [a |-> <rhobox>] because
(a) The box should be filled in with a rho-type, but
but the returned substitution maps TyVars to boxy
*sigma* types
(b) In any case, the right final answer might be *either*
instantiate 'a' with a rho-type or a sigma type
head xs : Int vs head xs : forall b. b->b
So the matcher MUST NOT make a choice here. In general, we only
bind a template type variable in boxyMatchType, not in boxySubMatchType.
\begin{code}
boxyMatchTypes
:: TcTyVarSet -> [TcType] -- The "template"; the tyvars are skolems
-> [BoxySigmaType] -- Type to match
-> TvSubst -- Substitution of the [TcTyVar] to BoxySigmaTypes
-- boxyMatchTypes implements the Pre-matching judgement, in Fig 5 of the paper
-- "Boxy types: inference for higher rank types and impredicativity"
-- Find a *boxy* substitution that makes the template look as much
-- like the BoxySigmaType as possible.
-- It's always ok to return an empty substitution;
-- anything more is jam on the pudding
--
-- NB1: This is a pure, non-monadic function.
-- It does no unification, and cannot fail
--
-- Precondition: the arg lengths are equal
-- Precondition: none of the template type variables appear anywhere in the [BoxySigmaType]
--
------------
boxyMatchTypes tmpl_tvs tmpl_tys boxy_tys
= ASSERT( length tmpl_tys == length boxy_tys )
boxy_match_s tmpl_tvs tmpl_tys emptyVarSet boxy_tys emptyTvSubst
-- ToDo: add error context?
boxy_match_s tmpl_tvs [] boxy_tvs [] subst
= subst
boxy_match_s tmpl_tvs (t_ty:t_tys) boxy_tvs (b_ty:b_tys) subst
= boxy_match tmpl_tvs t_ty boxy_tvs b_ty $
boxy_match_s tmpl_tvs t_tys boxy_tvs b_tys subst
boxy_match_s tmpl_tvs _ boxy_tvs _ subst
= panic "boxy_match_s" -- Lengths do not match
------------
boxy_match :: TcTyVarSet -> TcType -- Template
-> TcTyVarSet -- boxy_tvs: do not bind template tyvars to any of these
-> BoxySigmaType -- Match against this type
-> TvSubst
-> TvSubst
-- The boxy_tvs argument prevents this match:
-- [a] forall b. a ~ forall b. b
-- We don't want to bind the template variable 'a'
-- to the quantified type variable 'b'!
boxy_match tmpl_tvs orig_tmpl_ty boxy_tvs orig_boxy_ty subst
= go orig_tmpl_ty orig_boxy_ty
where
go t_ty b_ty
| Just t_ty' <- tcView t_ty = go t_ty' b_ty
| Just b_ty' <- tcView b_ty = go t_ty b_ty'
go ty1 ty2 -- C.f. the isSigmaTy case for boxySubMatchType
| isSigmaTy ty1
, (tvs1, _, tau1) <- tcSplitSigmaTy ty1
, (tvs2, _, tau2) <- tcSplitSigmaTy ty2
, equalLength tvs1 tvs2
= boxy_match (tmpl_tvs `delVarSetList` tvs1) tau1
(boxy_tvs `extendVarSetList` tvs2) tau2 subst
go (TyConApp tc1 tys1) (TyConApp tc2 tys2)
| tc1 == tc2 = go_s tys1 tys2
go (FunTy arg1 res1) (FunTy arg2 res2)
= go_s [arg1,res1] [arg2,res2]
go t_ty b_ty
| Just (s1,t1) <- tcSplitAppTy_maybe t_ty,
Just (s2,t2) <- tcSplitAppTy_maybe b_ty,
typeKind t2 `isSubKind` typeKind t1 -- Maintain invariant
= go_s [s1,t1] [s2,t2]
go (TyVarTy tv) b_ty
| tv `elemVarSet` tmpl_tvs -- Template type variable in the template
, boxy_tvs `disjointVarSet` tyVarsOfType orig_boxy_ty
, typeKind b_ty `isSubKind` tyVarKind tv -- See Note [Matching kinds]
= extendTvSubst subst tv boxy_ty'
| otherwise
= subst -- Ignore others
where
boxy_ty' = case lookupTyVar subst tv of
Nothing -> orig_boxy_ty
Just ty -> ty `boxyLub` orig_boxy_ty
go _ _ = emptyTvSubst -- It's important to *fail* by returning the empty substitution
-- Example: Tree a ~ Maybe Int
-- We do not want to bind (a |-> Int) in pre-matching, because that can give very
-- misleading error messages. An even more confusing case is
-- a -> b ~ Maybe Int
-- Then we do not want to bind (b |-> Int)! It's always safe to discard bindings
-- from this pre-matching phase.
--------
go_s tys1 tys2 = boxy_match_s tmpl_tvs tys1 boxy_tvs tys2 subst
boxyLub :: BoxySigmaType -> BoxySigmaType -> BoxySigmaType
-- Combine boxy information from the two types
-- If there is a conflict, return the first
boxyLub orig_ty1 orig_ty2
= go orig_ty1 orig_ty2
where
go (AppTy f1 a1) (AppTy f2 a2) = AppTy (boxyLub f1 f2) (boxyLub a1 a2)
go (FunTy f1 a1) (FunTy f2 a2) = FunTy (boxyLub f1 f2) (boxyLub a1 a2)
go (TyConApp tc1 ts1) (TyConApp tc2 ts2)
| tc1 == tc2, length ts1 == length ts2
= TyConApp tc1 (zipWith boxyLub ts1 ts2)
go (TyVarTy tv1) ty2 -- This is the whole point;
| isTcTyVar tv1, isBoxyTyVar tv1 -- choose ty2 if ty2 is a box
= orig_ty2
-- Look inside type synonyms, but only if the naive version fails
go ty1 ty2 | Just ty1' <- tcView ty1 = go ty1' ty2
| Just ty2' <- tcView ty1 = go ty1 ty2'
-- For now, we don't look inside ForAlls, PredTys
go ty1 ty2 = orig_ty1 -- Default
\end{code}
Note [Matching kinds]
~~~~~~~~~~~~~~~~~~~~~
The target type might legitimately not be a sub-kind of template.
For example, suppose the target is simply a box with an OpenTypeKind,
and the template is a type variable with LiftedTypeKind.
Then it's ok (because the target type will later be refined).
We simply don't bind the template type variable.
It might also be that the kind mis-match is an error. For example,
suppose we match the template (a -> Int) against (Int# -> Int),
where the template type variable 'a' has LiftedTypeKind. This
matching function does not fail; it simply doesn't bind the template.
Later stuff will fail.
%************************************************************************
%* *
Subsumption checking
%* *
%************************************************************************
All the tcSub calls have the form
tcSub expected_ty offered_ty
which checks
offered_ty <= expected_ty
That is, that a value of type offered_ty is acceptable in
a place expecting a value of type expected_ty.
It returns a coercion function
co_fn :: offered_ty -> expected_ty
which takes an HsExpr of type offered_ty into one of type
expected_ty.
\begin{code}
-----------------
tcSubExp :: BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
-- (tcSub act exp) checks that
-- act <= exp
tcSubExp actual_ty expected_ty
= -- addErrCtxtM (unifyCtxt actual_ty expected_ty) $
-- Adding the error context here leads to some very confusing error
-- messages, such as "can't match forall a. a->a with forall a. a->a"
-- Example is tcfail165:
-- do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
-- putMVar var (show :: forall a. Show a => a -> String)
-- Here the info does not flow from the 'var' arg of putMVar to its 'show' arg
-- but after zonking it looks as if it does!
--
-- So instead I'm adding the error context when moving from tc_sub to u_tys
traceTc (text "tcSubExp" <+> ppr actual_ty <+> ppr expected_ty) >>
tc_sub SubOther actual_ty actual_ty False expected_ty expected_ty
tcFunResTy :: Name -> BoxySigmaType -> BoxySigmaType -> TcM HsWrapper -- Locally used only
tcFunResTy fun actual_ty expected_ty
= traceTc (text "tcFunResTy" <+> ppr actual_ty <+> ppr expected_ty) >>
tc_sub (SubFun fun) actual_ty actual_ty False expected_ty expected_ty
-----------------
data SubCtxt = SubDone -- Error-context already pushed
| SubFun Name -- Context is tcFunResTy
| SubOther -- Context is something else
tc_sub :: SubCtxt -- How to add an error-context
-> BoxySigmaType -- actual_ty, before expanding synonyms
-> BoxySigmaType -- ..and after
-> InBox -- True <=> expected_ty is inside a box
-> BoxySigmaType -- expected_ty, before
-> BoxySigmaType -- ..and after
-> TcM HsWrapper
-- The acual_ty is never inside a box
-- IMPORTANT pre-condition: if the args contain foralls, the bound type
-- variables are visible non-monadically
-- (i.e. tha args are sufficiently zonked)
-- This invariant is needed so that we can "see" the foralls, ad
-- e.g. in the SPEC rule where we just use splitSigmaTy
tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
= tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
-- This indirection is just here to make
-- it easy to insert a debug trace!
tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
| Just exp_ty' <- tcView exp_ty = tc_sub sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty'
tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
| Just act_ty' <- tcView act_ty = tc_sub sub_ctxt act_sty act_ty' exp_ib exp_sty exp_ty
-----------------------------------
-- Rule SBOXY, plus other cases when act_ty is a type variable
-- Just defer to boxy matching
-- This rule takes precedence over SKOL!
tc_sub1 sub_ctxt act_sty (TyVarTy tv) exp_ib exp_sty exp_ty
= do { addSubCtxt sub_ctxt act_sty exp_sty $
uVar True False tv exp_ib exp_sty exp_ty
; return idHsWrapper }
-----------------------------------
-- Skolemisation case (rule SKOL)
-- actual_ty: d:Eq b => b->b
-- expected_ty: forall a. Ord a => a->a
-- co_fn e /\a. \d2:Ord a. let d = eqFromOrd d2 in e
-- It is essential to do this *before* the specialisation case
-- Example: f :: (Eq a => a->a) -> ...
-- g :: Ord b => b->b
-- Consider f g !
tc_sub1 sub_ctxt act_sty act_ty exp_ib exp_sty exp_ty
| not exp_ib, -- SKOL does not apply if exp_ty is inside a box
isSigmaTy exp_ty
= do { (gen_fn, co_fn) <- tcGen exp_ty act_tvs $ \ _ body_exp_ty ->
tc_sub sub_ctxt act_sty act_ty False body_exp_ty body_exp_ty
; return (gen_fn <.> co_fn) }
where
act_tvs = tyVarsOfType act_ty
-- It's really important to check for escape wrt
-- the free vars of both expected_ty *and* actual_ty
-----------------------------------
-- Specialisation case (rule ASPEC):
-- actual_ty: forall a. Ord a => a->a
-- expected_ty: Int -> Int
-- co_fn e = e Int dOrdInt
tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
-- Implements the new SPEC rule in the Appendix of the paper
-- "Boxy types: inference for higher rank types and impredicativity"
-- (This appendix isn't in the published version.)
-- The idea is to *first* do pre-subsumption, and then full subsumption
-- Example: forall a. a->a <= Int -> (forall b. Int)
-- Pre-subsumpion finds a|->Int, and that works fine, whereas
-- just running full subsumption would fail.
| isSigmaTy actual_ty
= do { -- Perform pre-subsumption, and instantiate
-- the type with info from the pre-subsumption;
-- boxy tyvars if pre-subsumption gives no info
let (tyvars, theta, tau) = tcSplitSigmaTy actual_ty
tau_tvs = exactTyVarsOfType tau
; inst_tys <- if exp_ib then -- Inside a box, do not do clever stuff
do { tyvars' <- mapM tcInstBoxyTyVar tyvars
; return (mkTyVarTys tyvars') }
else -- Outside, do clever stuff
preSubType tyvars tau_tvs tau expected_ty
; let subst' = zipOpenTvSubst tyvars inst_tys
tau' = substTy subst' tau
-- Perform a full subsumption check
; traceTc (text "tc_sub_spec" <+> vcat [ppr actual_ty,
ppr tyvars <+> ppr theta <+> ppr tau,
ppr tau'])
; co_fn2 <- tc_sub sub_ctxt tau' tau' exp_ib exp_sty expected_ty
-- Deal with the dictionaries
; co_fn1 <- instCall InstSigOrigin inst_tys (substTheta subst' theta)
; return (co_fn2 <.> co_fn1) }
-----------------------------------
-- Function case (rule F1)
tc_sub1 sub_ctxt act_sty (FunTy act_arg act_res) exp_ib exp_sty (FunTy exp_arg exp_res)
= addSubCtxt sub_ctxt act_sty exp_sty $
tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
-- Function case (rule F2)
tc_sub1 sub_ctxt act_sty act_ty@(FunTy act_arg act_res) _ exp_sty (TyVarTy exp_tv)
| isBoxyTyVar exp_tv
= addSubCtxt sub_ctxt act_sty exp_sty $
do { cts <- readMetaTyVar exp_tv
; case cts of
Indirect ty -> tc_sub SubDone act_sty act_ty True exp_sty ty
Flexi -> do { [arg_ty,res_ty] <- withMetaTvs exp_tv fun_kinds mk_res_ty
; tc_sub_funs act_arg act_res True arg_ty res_ty } }
where
mk_res_ty [arg_ty', res_ty'] = mkFunTy arg_ty' res_ty'
mk_res_ty other = panic "TcUnify.mk_res_ty3"
fun_kinds = [argTypeKind, openTypeKind]
-- Everything else: defer to boxy matching
tc_sub1 sub_ctxt act_sty actual_ty exp_ib exp_sty expected_ty
= do { addSubCtxt sub_ctxt act_sty exp_sty $
u_tys True False act_sty actual_ty exp_ib exp_sty expected_ty
; return idHsWrapper }
-----------------------------------
tc_sub_funs act_arg act_res exp_ib exp_arg exp_res
= do { uTys False act_arg exp_ib exp_arg
; co_fn_res <- tc_sub SubDone act_res act_res exp_ib exp_res exp_res
; wrapFunResCoercion [exp_arg] co_fn_res }
-----------------------------------
wrapFunResCoercion
:: [TcType] -- Type of args
-> HsWrapper -- HsExpr a -> HsExpr b
-> TcM HsWrapper -- HsExpr (arg_tys -> a) -> HsExpr (arg_tys -> b)
wrapFunResCoercion arg_tys co_fn_res
| isIdHsWrapper co_fn_res = return idHsWrapper
| null arg_tys = return co_fn_res
| otherwise
= do { arg_ids <- newSysLocalIds FSLIT("sub") arg_tys
; return (mkWpLams arg_ids <.> co_fn_res <.> mkWpApps arg_ids) }
\end{code}
%************************************************************************
%* *
\subsection{Generalisation}
%* *
%************************************************************************
\begin{code}
tcGen :: BoxySigmaType -- expected_ty
-> TcTyVarSet -- Extra tyvars that the universally
-- quantified tyvars of expected_ty
-- must not be unified
-> ([TcTyVar] -> BoxyRhoType -> TcM result)
-> TcM (HsWrapper, result)
-- The expression has type: spec_ty -> expected_ty
tcGen expected_ty extra_tvs thing_inside -- We expect expected_ty to be a forall-type
-- If not, the call is a no-op
= do { -- We want the GenSkol info in the skolemised type variables to
-- mention the *instantiated* tyvar names, so that we get a
-- good error message "Rigid variable 'a' is bound by (forall a. a->a)"
-- Hence the tiresome but innocuous fixM
((tvs', theta', rho'), skol_info) <- fixM (\ ~(_, skol_info) ->
do { (forall_tvs, theta, rho_ty) <- tcInstSkolType skol_info expected_ty
; span <- getSrcSpanM
; let skol_info = GenSkol forall_tvs (mkPhiTy theta rho_ty) span
; return ((forall_tvs, theta, rho_ty), skol_info) })
#ifdef DEBUG
; traceTc (text "tcGen" <+> vcat [text "extra_tvs" <+> ppr extra_tvs,
text "expected_ty" <+> ppr expected_ty,
text "inst ty" <+> ppr tvs' <+> ppr theta' <+> ppr rho',
text "free_tvs" <+> ppr free_tvs])
#endif
-- Type-check the arg and unify with poly type
; (result, lie) <- getLIE (thing_inside tvs' rho')
-- Check that the "forall_tvs" havn't been constrained
-- The interesting bit here is that we must include the free variables
-- of the expected_ty. Here's an example:
-- runST (newVar True)
-- Here, if we don't make a check, we'll get a type (ST s (MutVar s Bool))
-- for (newVar True), with s fresh. Then we unify with the runST's arg type
-- forall s'. ST s' a. That unifies s' with s, and a with MutVar s Bool.
-- So now s' isn't unconstrained because it's linked to a.
-- Conclusion: include the free vars of the expected_ty in the
-- list of "free vars" for the signature check.
; dicts <- newDictBndrsO (SigOrigin skol_info) theta'
; inst_binds <- tcSimplifyCheck sig_msg tvs' dicts lie
; checkSigTyVarsWrt free_tvs tvs'
; traceTc (text "tcGen:done")
; let
-- The WpLet binds any Insts which came out of the simplification.
dict_ids = map instToId dicts
co_fn = mkWpTyLams tvs' <.> mkWpLams dict_ids <.> WpLet inst_binds
; returnM (co_fn, result) }
where
free_tvs = tyVarsOfType expected_ty `unionVarSet` extra_tvs
sig_msg = ptext SLIT("expected type of an expression")
\end{code}
%************************************************************************
%* *
Boxy unification
%* *
%************************************************************************
The exported functions are all defined as versions of some
non-exported generic functions.
\begin{code}
boxyUnify :: BoxyType -> BoxyType -> TcM ()
-- Acutal and expected, respectively
boxyUnify ty1 ty2
= addErrCtxtM (unifyCtxt ty1 ty2) $
uTysOuter False ty1 False ty2
---------------
boxyUnifyList :: [BoxyType] -> [BoxyType] -> TcM ()
-- Arguments should have equal length
-- Acutal and expected types
boxyUnifyList tys1 tys2 = uList boxyUnify tys1 tys2
---------------
unifyType :: TcTauType -> TcTauType -> TcM ()
-- No boxes expected inside these types
-- Acutal and expected types
unifyType ty1 ty2 -- ty1 expected, ty2 inferred
= ASSERT2( not (isBoxyTy ty1), ppr ty1 )
ASSERT2( not (isBoxyTy ty2), ppr ty2 )
addErrCtxtM (unifyCtxt ty1 ty2) $
uTysOuter True ty1 True ty2
---------------
unifyPred :: PredType -> PredType -> TcM ()
-- Acutal and expected types
unifyPred p1 p2 = addErrCtxtM (unifyCtxt (mkPredTy p1) (mkPredTy p2)) $
uPred True True p1 True p2
unifyTheta :: TcThetaType -> TcThetaType -> TcM ()
-- Acutal and expected types
unifyTheta theta1 theta2
= do { checkTc (equalLength theta1 theta2)
(ptext SLIT("Contexts differ in length"))
; uList unifyPred theta1 theta2 }
---------------
uList :: (a -> a -> TcM ())
-> [a] -> [a] -> TcM ()
-- Unify corresponding elements of two lists of types, which
-- should be f equal length. We charge down the list explicitly so that
-- we can complain if their lengths differ.
uList unify [] [] = return ()
uList unify (ty1:tys1) (ty2:tys2) = do { unify ty1 ty2; uList unify tys1 tys2 }
uList unify ty1s ty2s = panic "Unify.uList: mismatched type lists!"
\end{code}
@unifyTypeList@ takes a single list of @TauType@s and unifies them
all together. It is used, for example, when typechecking explicit
lists, when all the elts should be of the same type.
\begin{code}
unifyTypeList :: [TcTauType] -> TcM ()
unifyTypeList [] = returnM ()
unifyTypeList [ty] = returnM ()
unifyTypeList (ty1:tys@(ty2:_)) = do { unifyType ty1 ty2
; unifyTypeList tys }
\end{code}
%************************************************************************
%* *
\subsection[Unify-uTys]{@uTys@: getting down to business}
%* *
%************************************************************************
@uTys@ is the heart of the unifier. Each arg happens twice, because
we want to report errors in terms of synomyms if poss. The first of
the pair is used in error messages only; it is always the same as the
second, except that if the first is a synonym then the second may be a
de-synonym'd version. This way we get better error messages.
We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
\begin{code}
type InBox = Bool -- True <=> we are inside a box
-- False <=> we are outside a box
-- The importance of this is that if we get "filled-box meets
-- filled-box", we'll look into the boxes and unify... but
-- we must not allow polytypes. But if we are in a box on
-- just one side, then we can allow polytypes
type Outer = Bool -- True <=> this is the outer level of a unification
-- so that the types being unified are the
-- very ones we began with, not some sub
-- component or synonym expansion
-- The idea is that if Outer is true then unifyMisMatch should
-- pop the context to remove the "Expected/Acutal" context
uTysOuter, uTys
:: InBox -> TcType -- ty1 is the *expected* type
-> InBox -> TcType -- ty2 is the *actual* type
-> TcM ()
uTysOuter nb1 ty1 nb2 ty2 = do { traceTc (text "uTysOuter" <+> ppr ty1 <+> ppr ty2)
; u_tys True nb1 ty1 ty1 nb2 ty2 ty2 }
uTys nb1 ty1 nb2 ty2 = do { traceTc (text "uTys" <+> ppr ty1 <+> ppr ty2)
; u_tys False nb1 ty1 ty1 nb2 ty2 ty2 }
--------------
uTys_s :: InBox -> [TcType] -- ty1 is the *actual* types
-> InBox -> [TcType] -- ty2 is the *expected* types
-> TcM ()
uTys_s nb1 [] nb2 [] = returnM ()
uTys_s nb1 (ty1:tys1) nb2 (ty2:tys2) = do { uTys nb1 ty1 nb2 ty2
; uTys_s nb1 tys1 nb2 tys2 }
uTys_s nb1 ty1s nb2 ty2s = panic "Unify.uTys_s: mismatched type lists!"
--------------
u_tys :: Outer
-> InBox -> TcType -> TcType -- ty1 is the *actual* type
-> InBox -> TcType -> TcType -- ty2 is the *expected* type
-> TcM ()
u_tys outer nb1 orig_ty1 ty1 nb2 orig_ty2 ty2
= go outer ty1 ty2
where
-- Always expand synonyms (see notes at end)
-- (this also throws away FTVs)
go outer ty1 ty2
| Just ty1' <- tcView ty1 = go False ty1' ty2
| Just ty2' <- tcView ty2 = go False ty1 ty2'
-- Variables; go for uVar
go outer (TyVarTy tyvar1) ty2 = uVar outer False tyvar1 nb2 orig_ty2 ty2
go outer ty1 (TyVarTy tyvar2) = uVar outer True tyvar2 nb1 orig_ty1 ty1
-- "True" means args swapped
-- Predicates
go outer (PredTy p1) (PredTy p2) = uPred outer nb1 p1 nb2 p2
-- Type constructors must match
go _ (TyConApp con1 tys1) (TyConApp con2 tys2)
| con1 == con2 = uTys_s nb1 tys1 nb2 tys2
-- See Note [TyCon app]
-- Functions; just check the two parts
go _ (FunTy fun1 arg1) (FunTy fun2 arg2)
= do { uTys nb1 fun1 nb2 fun2
; uTys nb1 arg1 nb2 arg2 }
-- Applications need a bit of care!
-- They can match FunTy and TyConApp, so use splitAppTy_maybe
-- NB: we've already dealt with type variables and Notes,
-- so if one type is an App the other one jolly well better be too
go outer (AppTy s1 t1) ty2
| Just (s2,t2) <- tcSplitAppTy_maybe ty2
= do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
-- Now the same, but the other way round
-- Don't swap the types, because the error messages get worse
go outer ty1 (AppTy s2 t2)
| Just (s1,t1) <- tcSplitAppTy_maybe ty1
= do { uTys nb1 s1 nb2 s2; uTys nb1 t1 nb2 t2 }
go _ ty1@(ForAllTy _ _) ty2@(ForAllTy _ _)
| length tvs1 == length tvs2
= do { tvs <- tcInstSkolTyVars UnkSkol tvs1 -- Not a helpful SkolemInfo
; let tys = mkTyVarTys tvs
in_scope = mkInScopeSet (mkVarSet tvs)
subst1 = mkTvSubst in_scope (zipTyEnv tvs1 tys)