mirrored from https://gitlab.haskell.org/ghc/ghc.git
/
TyCoRep.hs
3110 lines (2552 loc) · 123 KB
/
TyCoRep.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
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[TyCoRep]{Type and Coercion - friends' interface}
Note [The Type-related module hierarchy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class
CoAxiom
TyCon imports Class, CoAxiom
TyCoRep imports Class, CoAxiom, TyCon
TysPrim imports TyCoRep ( including mkTyConTy )
Kind imports TysPrim ( mainly for primitive kinds )
Type imports Kind
Coercion imports Type
-}
-- We expose the relevant stuff from this module via the Type module
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE CPP, DeriveDataTypeable, MultiWayIf #-}
module TyCoRep (
TyThing(..), tyThingCategory, pprTyThingCategory, pprShortTyThing,
-- * Types
Type(..),
TyLit(..),
KindOrType, Kind,
PredType, ThetaType, -- Synonyms
ArgFlag(..),
-- * Coercions
Coercion(..),
UnivCoProvenance(..),
CoercionHole(..), coHoleCoVar, setCoHoleCoVar,
CoercionN, CoercionR, CoercionP, KindCoercion,
-- * Functions over types
mkTyConTy, mkTyVarTy, mkTyVarTys,
mkFunTy, mkFunTys, mkForAllTy, mkForAllTys,
mkPiTy, mkPiTys,
isTYPE, tcIsTYPE,
isLiftedTypeKind, isUnliftedTypeKind,
isCoercionType, isRuntimeRepTy, isRuntimeRepVar,
sameVis,
-- * Functions over binders
TyBinder(..), TyVarBinder,
binderVar, binderVars, binderKind, binderArgFlag,
delBinderVar,
isInvisibleArgFlag, isVisibleArgFlag,
isInvisibleBinder, isVisibleBinder,
-- * Functions over coercions
pickLR,
-- * Pretty-printing
pprType, pprParendType, pprPrecType,
pprTypeApp, pprTvBndr, pprTvBndrs,
pprSigmaType,
pprTheta, pprParendTheta, pprForAll, pprUserForAll,
pprTyVar, pprTyVars,
pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprTyLit,
PprPrec(..), topPrec, sigPrec, opPrec, funPrec, appPrec, maybeParen,
pprDataCons, ppSuggestExplicitKinds,
pprCo, pprParendCo,
debugPprType,
-- * Free variables
tyCoVarsOfType, tyCoVarsOfTypeDSet, tyCoVarsOfTypes, tyCoVarsOfTypesDSet,
tyCoFVsBndr, tyCoFVsOfType, tyCoVarsOfTypeList,
tyCoFVsOfTypes, tyCoVarsOfTypesList,
closeOverKindsDSet, closeOverKindsFV, closeOverKindsList,
coVarsOfType, coVarsOfTypes,
coVarsOfCo, coVarsOfCos,
tyCoVarsOfCo, tyCoVarsOfCos,
tyCoVarsOfCoDSet,
tyCoFVsOfCo, tyCoFVsOfCos,
tyCoVarsOfCoList, tyCoVarsOfProv,
closeOverKinds,
injectiveVarsOfBinder, injectiveVarsOfType,
noFreeVarsOfType, noFreeVarsOfCo,
-- * Substitutions
TCvSubst(..), TvSubstEnv, CvSubstEnv,
emptyTvSubstEnv, emptyCvSubstEnv, composeTCvSubstEnv, composeTCvSubst,
emptyTCvSubst, mkEmptyTCvSubst, isEmptyTCvSubst,
mkTCvSubst, mkTvSubst,
getTvSubstEnv,
getCvSubstEnv, getTCvInScope, getTCvSubstRangeFVs,
isInScope, notElemTCvSubst,
setTvSubstEnv, setCvSubstEnv, zapTCvSubst,
extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
extendTCvSubst,
extendCvSubst, extendCvSubstWithClone,
extendTvSubst, extendTvSubstBinderAndInScope, extendTvSubstWithClone,
extendTvSubstList, extendTvSubstAndInScope,
unionTCvSubst, zipTyEnv, zipCoEnv, mkTyCoInScopeSet,
zipTvSubst, zipCvSubst,
mkTvSubstPrs,
substTyWith, substTyWithCoVars, substTysWith, substTysWithCoVars,
substCoWith,
substTy, substTyAddInScope,
substTyUnchecked, substTysUnchecked, substThetaUnchecked,
substTyWithUnchecked,
substCoUnchecked, substCoWithUnchecked,
substTyWithInScope,
substTys, substTheta,
lookupTyVar, substTyVarBndr,
substCo, substCos, substCoVar, substCoVars, lookupCoVar,
substCoVarBndr, cloneTyVarBndr, cloneTyVarBndrs,
substTyVar, substTyVars,
substForAllCoBndr,
substTyVarBndrCallback, substForAllCoBndrCallback,
checkValidSubst, isValidTCvSubst,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
tidyOpenTyCoVar, tidyOpenTyCoVars,
tidyTyVarOcc,
tidyTopType,
tidyKind,
tidyCo, tidyCos,
tidyTyVarBinder, tidyTyVarBinders,
-- * Sizes
typeSize, coercionSize, provSize
) where
#include "HsVersions.h"
import GhcPrelude
import {-# SOURCE #-} DataCon( dataConFullSig
, dataConUserTyVarBinders
, DataCon )
import {-# SOURCE #-} Type( isPredTy, isCoercionTy, mkAppTy, mkCastTy
, tyCoVarsOfTypeWellScoped
, tyCoVarsOfTypesWellScoped
, toposortTyVars
, coreView, tcView )
-- Transitively pulls in a LOT of stuff, better to break the loop
import {-# SOURCE #-} Coercion
import {-# SOURCE #-} ConLike ( ConLike(..), conLikeName )
import {-# SOURCE #-} ToIface( toIfaceTypeX, toIfaceTyLit, toIfaceForAllBndr
, toIfaceTyCon, toIfaceTcArgs, toIfaceCoercionX )
-- friends:
import IfaceType
import Var
import VarEnv
import VarSet
import Name hiding ( varName )
import TyCon
import Class
import CoAxiom
import FV
-- others
import BasicTypes ( LeftOrRight(..), PprPrec(..), topPrec, sigPrec, opPrec
, funPrec, appPrec, maybeParen, pickLR )
import PrelNames
import Outputable
import DynFlags
import FastString
import Pair
import UniqSupply
import Util
import UniqFM
import UniqSet
-- libraries
import qualified Data.Data as Data hiding ( TyCon )
import Data.List
import Data.IORef ( IORef ) -- for CoercionHole
{-
%************************************************************************
%* *
TyThing
%* *
%************************************************************************
Despite the fact that DataCon has to be imported via a hi-boot route,
this module seems the right place for TyThing, because it's needed for
funTyCon and all the types in TysPrim.
It is also SOURCE-imported into Name.hs
Note [ATyCon for classes]
~~~~~~~~~~~~~~~~~~~~~~~~~
Both classes and type constructors are represented in the type environment
as ATyCon. You can tell the difference, and get to the class, with
isClassTyCon :: TyCon -> Bool
tyConClass_maybe :: TyCon -> Maybe Class
The Class and its associated TyCon have the same Name.
-}
-- | A global typecheckable-thing, essentially anything that has a name.
-- Not to be confused with a 'TcTyThing', which is also a typecheckable
-- thing but in the *local* context. See 'TcEnv' for how to retrieve
-- a 'TyThing' given a 'Name'.
data TyThing
= AnId Id
| AConLike ConLike
| ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes]
| ACoAxiom (CoAxiom Branched)
instance Outputable TyThing where
ppr = pprShortTyThing
instance NamedThing TyThing where -- Can't put this with the type
getName (AnId id) = getName id -- decl, because the DataCon instance
getName (ATyCon tc) = getName tc -- isn't visible there
getName (ACoAxiom cc) = getName cc
getName (AConLike cl) = conLikeName cl
pprShortTyThing :: TyThing -> SDoc
-- c.f. PprTyThing.pprTyThing, which prints all the details
pprShortTyThing thing
= pprTyThingCategory thing <+> quotes (ppr (getName thing))
pprTyThingCategory :: TyThing -> SDoc
pprTyThingCategory = text . capitalise . tyThingCategory
tyThingCategory :: TyThing -> String
tyThingCategory (ATyCon tc)
| isClassTyCon tc = "class"
| otherwise = "type constructor"
tyThingCategory (ACoAxiom _) = "coercion axiom"
tyThingCategory (AnId _) = "identifier"
tyThingCategory (AConLike (RealDataCon _)) = "data constructor"
tyThingCategory (AConLike (PatSynCon _)) = "pattern synonym"
{- **********************************************************************
* *
Type
* *
********************************************************************** -}
-- | The key representation of types within the compiler
type KindOrType = Type -- See Note [Arguments to type constructors]
-- | The key type representing kinds in the compiler.
type Kind = Type
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Type
-- See Note [Non-trivial definitional equality]
= TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
| AppTy
Type
Type -- ^ Type application to something other than a 'TyCon'. Parameters:
--
-- 1) Function: must /not/ be a 'TyConApp' or 'CastTy',
-- must be another 'AppTy', or 'TyVarTy'
-- See Note [Respecting definitional equality] (EQ1) about the
-- no 'CastTy' requirement
--
-- 2) Argument type
| TyConApp
TyCon
[KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
-- Invariant: saturated applications of 'FunTyCon' must
-- use 'FunTy' and saturated synonyms must use their own
-- constructors. However, /unsaturated/ 'FunTyCon's
-- do appear as 'TyConApp's.
-- Parameters:
--
-- 1) Type constructor being applied to.
--
-- 2) Type arguments. Might not have enough type arguments
-- here to saturate the constructor.
-- Even type synonyms are not necessarily saturated;
-- for example unsaturated type synonyms
-- can appear as the right hand side of a type synonym.
| ForAllTy
{-# UNPACK #-} !TyVarBinder
Type -- ^ A Π type.
| FunTy Type Type -- ^ t1 -> t2 Very common, so an important special case
| LitTy TyLit -- ^ Type literals are similar to type constructors.
| CastTy
Type
KindCoercion -- ^ A kind cast. The coercion is always nominal.
-- INVARIANT: The cast is never refl.
-- INVARIANT: The Type is not a CastTy (use TransCo instead)
-- See Note [Respecting definitional equality] (EQ2) and (EQ3)
| CoercionTy
Coercion -- ^ Injection of a Coercion into a type
-- This should only ever be used in the RHS of an AppTy,
-- in the list of a TyConApp, when applying a promoted
-- GADT data constructor
deriving Data.Data
-- NOTE: Other parts of the code assume that type literals do not contain
-- types or type variables.
data TyLit
= NumTyLit Integer
| StrTyLit FastString
deriving (Eq, Ord, Data.Data)
{- Note [Arguments to type constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because of kind polymorphism, in addition to type application we now
have kind instantiation. We reuse the same notations to do so.
For example:
Just (* -> *) Maybe
Right * Nat Zero
are represented by:
TyConApp (PromotedDataCon Just) [* -> *, Maybe]
TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)]
Important note: Nat is used as a *kind* and not as a type. This can be
confusing, since type-level Nat and kind-level Nat are identical. We
use the kind of (PromotedDataCon Right) to know if its arguments are
kinds or types.
This kind instantiation only happens in TyConApp currently.
Note [Non-trivial definitional equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Is Int |> <*> the same as Int? YES! In order to reduce headaches,
we decide that any reflexive casts in types are just ignored.
(Indeed they must be. See Note [Respecting definitional equality].)
More generally, the `eqType` function, which defines Core's type equality
relation, ignores casts and coercion arguments, as long as the
two types have the same kind. This allows us to be a little sloppier
in keeping track of coercions, which is a good thing. It also means
that eqType does not depend on eqCoercion, which is also a good thing.
Why is this sensible? That is, why is something different than α-equivalence
appropriate for the implementation of eqType?
Anything smaller than ~ and homogeneous is an appropriate definition for
equality. The type safety of FC depends only on ~. Let's say η : τ ~ σ. Any
expression of type τ can be transmuted to one of type σ at any point by
casting. The same is true of types of type τ. So in some sense, τ and σ are
interchangeable.
But let's be more precise. If we examine the typing rules of FC (say, those in
http://www.cis.upenn.edu/~eir/papers/2015/equalities/equalities-extended.pdf)
there are several places where the same metavariable is used in two different
premises to a rule. (For example, see Ty_App.) There is an implicit equality
check here. What definition of equality should we use? By convention, we use
α-equivalence. Take any rule with one (or more) of these implicit equality
checks. Then there is an admissible rule that uses ~ instead of the implicit
check, adding in casts as appropriate.
The only problem here is that ~ is heterogeneous. To make the kinds work out
in the admissible rule that uses ~, it is necessary to homogenize the
coercions. That is, if we have η : (τ : κ1) ~ (σ : κ2), then we don't use η;
we use η |> kind η, which is homogeneous.
The effect of this all is that eqType, the implementation of the implicit
equality check, can use any homogeneous relation that is smaller than ~, as
those rules must also be admissible.
A more drawn out argument around all of this is presented in Section 7.2 of
Richard E's thesis (http://cs.brynmawr.edu/~rae/papers/2016/thesis/eisenberg-thesis.pdf).
What would go wrong if we insisted on the casts matching? See the beginning of
Section 8 in the unpublished paper above. Theoretically, nothing at all goes
wrong. But in practical terms, getting the coercions right proved to be
nightmarish. And types would explode: during kind-checking, we often produce
reflexive kind coercions. When we try to cast by these, mkCastTy just discards
them. But if we used an eqType that distinguished between Int and Int |> <*>,
then we couldn't discard -- the output of kind-checking would be enormous,
and we would need enormous casts with lots of CoherenceCo's to straighten
them out.
Would anything go wrong if eqType respected type families? No, not at all. But
that makes eqType rather hard to implement.
Thus, the guideline for eqType is that it should be the largest
easy-to-implement relation that is still smaller than ~ and homogeneous. The
precise choice of relation is somewhat incidental, as long as the smart
constructors and destructors in Type respect whatever relation is chosen.
Another helpful principle with eqType is this:
(EQ) If (t1 `eqType` t2) then I can replace t1 by t2 anywhere.
This principle also tells us that eqType must relate only types with the
same kinds.
Note [Respecting definitional equality]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Note [Non-trivial definitional equality] introduces the property (EQ).
How is this upheld?
Any function that pattern matches on all the constructors will have to
consider the possibility of CastTy. Presumably, those functions will handle
CastTy appropriately and we'll be OK.
More dangerous are the splitXXX functions. Let's focus on splitTyConApp.
We don't want it to fail on (T a b c |> co). Happily, if we have
(T a b c |> co) `eqType` (T d e f)
then co must be reflexive. Why? eqType checks that the kinds are equal, as
well as checking that (a `eqType` d), (b `eqType` e), and (c `eqType` f).
By the kind check, we know that (T a b c |> co) and (T d e f) have the same
kind. So the only way that co could be non-reflexive is for (T a b c) to have
a different kind than (T d e f). But because T's kind is closed (all tycon kinds
are closed), the only way for this to happen is that one of the arguments has
to differ, leading to a contradiction. Thus, co is reflexive.
Accordingly, by eliminating reflexive casts, splitTyConApp need not worry
about outermost casts to uphold (EQ). Eliminating reflexive casts is done
in mkCastTy.
Unforunately, that's not the end of the story. Consider comparing
(T a b c) =? (T a b |> (co -> <Type>)) (c |> co)
These two types have the same kind (Type), but the left type is a TyConApp
while the right type is not. To handle this case, we say that the right-hand
type is ill-formed, requiring an AppTy never to have a casted TyConApp
on its left. It is easy enough to pull around the coercions to maintain
this invariant, as done in Type.mkAppTy. In the example above, trying to
form the right-hand type will instead yield (T a b (c |> co |> sym co) |> <Type>).
Both the casts there are reflexive and will be dropped. Huzzah.
This idea of pulling coercions to the right works for splitAppTy as well.
However, there is one hiccup: it's possible that a coercion doesn't relate two
Pi-types. For example, if we have @type family Fun a b where Fun a b = a -> b@,
then we might have (T :: Fun Type Type) and (T |> axFun) Int. That axFun can't
be pulled to the right. But we don't need to pull it: (T |> axFun) Int is not
`eqType` to any proper TyConApp -- thus, leaving it where it is doesn't violate
our (EQ) property.
Lastly, in order to detect reflexive casts reliably, we must make sure not
to have nested casts: we update (t |> co1 |> co2) to (t |> (co1 `TransCo` co2)).
In sum, in order to uphold (EQ), we need the following three invariants:
(EQ1) No decomposable CastTy to the left of an AppTy, where a decomposable
cast is one that relates either a FunTy to a FunTy or a
ForAllTy to a ForAllTy.
(EQ2) No reflexive casts in CastTy.
(EQ3) No nested CastTys.
These invariants are all documented above, in the declaration for Type.
-}
{- **********************************************************************
* *
TyBinder and ArgFlag
* *
********************************************************************** -}
-- | A 'TyBinder' represents an argument to a function. TyBinders can be dependent
-- ('Named') or nondependent ('Anon'). They may also be visible or not.
-- See Note [TyBinders]
data TyBinder
= Named TyVarBinder -- A type-lambda binder
| Anon Type -- A term-lambda binder
-- Visibility is determined by the type (Constraint vs. *)
deriving Data.Data
-- | Remove the binder's variable from the set, if the binder has
-- a variable.
delBinderVar :: VarSet -> TyVarBinder -> VarSet
delBinderVar vars (TvBndr tv _) = vars `delVarSet` tv
-- | Does this binder bind an invisible argument?
isInvisibleBinder :: TyBinder -> Bool
isInvisibleBinder (Named (TvBndr _ vis)) = isInvisibleArgFlag vis
isInvisibleBinder (Anon ty) = isPredTy ty
-- | Does this binder bind a visible argument?
isVisibleBinder :: TyBinder -> Bool
isVisibleBinder = not . isInvisibleBinder
{- Note [TyBinders]
~~~~~~~~~~~~~~~~~~~
A ForAllTy contains a TyVarBinder. But a type can be decomposed
to a telescope consisting of a [TyBinder]
A TyBinder represents the type of binders -- that is, the type of an
argument to a Pi-type. GHC Core currently supports two different
Pi-types:
* A non-dependent function type,
written with ->, e.g. ty1 -> ty2
represented as FunTy ty1 ty2. These are
lifted to Coercions with the corresponding FunCo.
* A dependent compile-time-only polytype,
written with forall, e.g. forall (a:*). ty
represented as ForAllTy (TvBndr a v) ty
Both Pi-types classify terms/types that take an argument. In other
words, if `x` is either a function or a polytype, `x arg` makes sense
(for an appropriate `arg`).
Note [TyVarBndrs, TyVarBinders, TyConBinders, and visibility]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* A ForAllTy (used for both types and kinds) contains a TyVarBinder.
Each TyVarBinder
TvBndr a tvis
is equipped with tvis::ArgFlag, which says whether or not arguments
for this binder should be visible (explicit) in source Haskell.
* A TyCon contains a list of TyConBinders. Each TyConBinder
TvBndr a cvis
is equipped with cvis::TyConBndrVis, which says whether or not type
and kind arguments for this TyCon should be visible (explicit) in
source Haskell.
This table summarises the visibility rules:
---------------------------------------------------------------------------------------
| Occurrences look like this
| GHC displays type as in Haskell source code
|-----------------------------------------------------------------------
| TvBndr a tvis :: TyVarBinder, in the binder of ForAllTy for a term
| tvis :: ArgFlag
| tvis = Inferred: f :: forall {a}. type Arg not allowed: f
| tvis = Specified: f :: forall a. type Arg optional: f or f @Int
| tvis = Required: T :: forall k -> type Arg required: T *
| This last form is illegal in terms: See Note [No Required TyBinder in terms]
|
| TvBndr k cvis :: TyConBinder, in the TyConBinders of a TyCon
| cvis :: TyConBndrVis
| cvis = AnonTCB: T :: kind -> kind Required: T *
| cvis = NamedTCB Inferred: T :: forall {k}. kind Arg not allowed: T
| cvis = NamedTCB Specified: T :: forall k. kind Arg not allowed[1]: T
| cvis = NamedTCB Required: T :: forall k -> kind Required: T *
---------------------------------------------------------------------------------------
[1] In types, in the Specified case, it would make sense to allow
optional kind applications, thus (T @*), but we have not
yet implemented that
---- Examples of where the different visibilities come from -----
In term declarations:
* Inferred. Function defn, with no signature: f1 x = x
We infer f1 :: forall {a}. a -> a, with 'a' Inferred
It's Inferred because it doesn't appear in any
user-written signature for f1
* Specified. Function defn, with signature (implicit forall):
f2 :: a -> a; f2 x = x
So f2 gets the type f2 :: forall a. a->a, with 'a' Specified
even though 'a' is not bound in the source code by an explicit forall
* Specified. Function defn, with signature (explicit forall):
f3 :: forall a. a -> a; f3 x = x
So f3 gets the type f3 :: forall a. a->a, with 'a' Specified
* Inferred/Specified. Function signature with inferred kind polymorphism.
f4 :: a b -> Int
So 'f4' gets the type f4 :: forall {k} (a:k->*) (b:k). a b -> Int
Here 'k' is Inferred (it's not mentioned in the type),
but 'a' and 'b' are Specified.
* Specified. Function signature with explicit kind polymorphism
f5 :: a (b :: k) -> Int
This time 'k' is Specified, because it is mentioned explicitly,
so we get f5 :: forall (k:*) (a:k->*) (b:k). a b -> Int
* Similarly pattern synonyms:
Inferred - from inferred types (e.g. no pattern type signature)
- or from inferred kind polymorphism
In type declarations:
* Inferred (k)
data T1 a b = MkT1 (a b)
Here T1's kind is T1 :: forall {k:*}. (k->*) -> k -> *
The kind variable 'k' is Inferred, since it is not mentioned
Note that 'a' and 'b' correspond to /Anon/ TyBinders in T1's kind,
and Anon binders don't have a visibility flag. (Or you could think
of Anon having an implicit Required flag.)
* Specified (k)
data T2 (a::k->*) b = MkT (a b)
Here T's kind is T :: forall (k:*). (k->*) -> k -> *
The kind variable 'k' is Specified, since it is mentioned in
the signature.
* Required (k)
data T k (a::k->*) b = MkT (a b)
Here T's kind is T :: forall k:* -> (k->*) -> k -> *
The kind is Required, since it bound in a positional way in T's declaration
Every use of T must be explicitly applied to a kind
* Inferred (k1), Specified (k)
data T a b (c :: k) = MkT (a b) (Proxy c)
Here T's kind is T :: forall {k1:*} (k:*). (k1->*) -> k1 -> k -> *
So 'k' is Specified, because it appears explicitly,
but 'k1' is Inferred, because it does not
---- Printing -----
We print forall types with enough syntax to tell you their visibility
flag. But this is not source Haskell, and these types may not all
be parsable.
Specified: a list of Specified binders is written between `forall` and `.`:
const :: forall a b. a -> b -> a
Inferred: with -fprint-explicit-foralls, Inferred binders are written
in braces:
f :: forall {k} (a:k). S k a -> Int
Otherwise, they are printed like Specified binders.
Required: binders are put between `forall` and `->`:
T :: forall k -> *
---- Other points -----
* In classic Haskell, all named binders (that is, the type variables in
a polymorphic function type f :: forall a. a -> a) have been Inferred.
* Inferred variables correspond to "generalized" variables from the
Visible Type Applications paper (ESOP'16).
Note [No Required TyBinder in terms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't allow Required foralls for term variables, including pattern
synonyms and data constructors. Why? Because then an application
would need a /compulsory/ type argument (possibly without an "@"?),
thus (f Int); and we don't have concrete syntax for that.
We could change this decision, but Required, Named TyBinders are rare
anyway. (Most are Anons.)
-}
{- **********************************************************************
* *
PredType
* *
********************************************************************** -}
-- | A type of the form @p@ of kind @Constraint@ represents a value whose type is
-- the Haskell predicate @p@, where a predicate is what occurs before
-- the @=>@ in a Haskell type.
--
-- We use 'PredType' as documentation to mark those types that we guarantee to have
-- this kind.
--
-- It can be expanded into its representation, but:
--
-- * The type checker must treat it as opaque
--
-- * The rest of the compiler treats it as transparent
--
-- Consider these examples:
--
-- > f :: (Eq a) => a -> Int
-- > g :: (?x :: Int -> Int) => a -> Int
-- > h :: (r\l) => {r} => {l::Int | r}
--
-- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
type PredType = Type
-- | A collection of 'PredType's
type ThetaType = [PredType]
{-
(We don't support TREX records yet, but the setup is designed
to expand to allow them.)
A Haskell qualified type, such as that for f,g,h above, is
represented using
* a FunTy for the double arrow
* with a type of kind Constraint as the function argument
The predicate really does turn into a real extra argument to the
function. If the argument has type (p :: Constraint) then the predicate p is
represented by evidence of type p.
%************************************************************************
%* *
Simple constructors
%* *
%************************************************************************
These functions are here so that they can be used by TysPrim,
which in turn is imported by Type
-}
-- named with "Only" to prevent naive use of mkTyVarTy
mkTyVarTy :: TyVar -> Type
mkTyVarTy v = ASSERT2( isTyVar v, ppr v <+> dcolon <+> ppr (tyVarKind v) )
TyVarTy v
mkTyVarTys :: [TyVar] -> [Type]
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
infixr 3 `mkFunTy` -- Associates to the right
-- | Make an arrow type
mkFunTy :: Type -> Type -> Type
mkFunTy arg res = FunTy arg res
-- | Make nested arrow types
mkFunTys :: [Type] -> Type -> Type
mkFunTys tys ty = foldr mkFunTy ty tys
mkForAllTy :: TyVar -> ArgFlag -> Type -> Type
mkForAllTy tv vis ty = ForAllTy (TvBndr tv vis) ty
-- | Wraps foralls over the type using the provided 'TyVar's from left to right
mkForAllTys :: [TyVarBinder] -> Type -> Type
mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
mkPiTy :: TyBinder -> Type -> Type
mkPiTy (Anon ty1) ty2 = FunTy ty1 ty2
mkPiTy (Named tvb) ty = ForAllTy tvb ty
mkPiTys :: [TyBinder] -> Type -> Type
mkPiTys tbs ty = foldr mkPiTy ty tbs
-- | Does this type classify a core (unlifted) Coercion?
-- At either role nominal or representational
-- (t1 ~# t2) or (t1 ~R# t2)
isCoercionType :: Type -> Bool
isCoercionType (TyConApp tc tys)
| (tc `hasKey` eqPrimTyConKey) || (tc `hasKey` eqReprPrimTyConKey)
, tys `lengthIs` 4
= True
isCoercionType _ = False
-- | Create the plain type constructor type which has been applied to no type arguments at all.
mkTyConTy :: TyCon -> Type
mkTyConTy tycon = TyConApp tycon []
{-
Some basic functions, put here to break loops eg with the pretty printer
-}
-- | If a type is @'TYPE' r@ for some @r@, run the predicate argument on @r@.
-- Otherwise, return 'False'.
--
-- This function does not distinguish between 'Constraint' and 'Type'. For a
-- version which does distinguish between the two, see 'tcIsTYPE'.
isTYPE :: ( Type -- the single argument to TYPE; not a synonym
-> Bool ) -- what to return
-> Kind -> Bool
isTYPE f ki | Just ki' <- coreView ki = isTYPE f ki'
isTYPE f (TyConApp tc [arg])
| tc `hasKey` tYPETyConKey
= go arg
where
go ty | Just ty' <- coreView ty = go ty'
go ty = f ty
isTYPE _ _ = False
-- | If a type is @'TYPE' r@ for some @r@, run the predicate argument on @r@.
-- Otherwise, return 'False'.
--
-- This function distinguishes between 'Constraint' and 'Type' (and will return
-- 'False' for 'Constraint'). For a version which does not distinguish between
-- the two, see 'isTYPE'.
tcIsTYPE :: ( Type -- the single argument to TYPE; not a synonym
-> Bool ) -- what to return
-> Kind -> Bool
tcIsTYPE f ki | Just ki' <- tcView ki = tcIsTYPE f ki'
tcIsTYPE f (TyConApp tc [arg])
| tc `hasKey` tYPETyConKey
= go arg
where
go ty | Just ty' <- tcView ty = go ty'
go ty = f ty
tcIsTYPE _ _ = False
-- | This version considers Constraint to be the same as *. Returns True
-- if the argument is equivalent to Type/Constraint and False otherwise.
isLiftedTypeKind :: Kind -> Bool
isLiftedTypeKind = isTYPE is_lifted
where
is_lifted (TyConApp lifted_rep []) = lifted_rep `hasKey` liftedRepDataConKey
is_lifted _ = False
-- | Returns True if the kind classifies unlifted types and False otherwise.
-- Note that this returns False for levity-polymorphic kinds, which may
-- be specialized to a kind that classifies unlifted types.
isUnliftedTypeKind :: Kind -> Bool
isUnliftedTypeKind = isTYPE is_unlifted
where
is_unlifted (TyConApp rr _args) = elem (getUnique rr) unliftedRepDataConKeys
is_unlifted _ = False
-- | Is this the type 'RuntimeRep'?
isRuntimeRepTy :: Type -> Bool
isRuntimeRepTy ty | Just ty' <- coreView ty = isRuntimeRepTy ty'
isRuntimeRepTy (TyConApp tc []) = tc `hasKey` runtimeRepTyConKey
isRuntimeRepTy _ = False
-- | Is a tyvar of type 'RuntimeRep'?
isRuntimeRepVar :: TyVar -> Bool
isRuntimeRepVar = isRuntimeRepTy . tyVarKind
{-
%************************************************************************
%* *
Coercions
%* *
%************************************************************************
-}
-- | A 'Coercion' is concrete evidence of the equality/convertibility
-- of two types.
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Coercion
-- Each constructor has a "role signature", indicating the way roles are
-- propagated through coercions.
-- - P, N, and R stand for coercions of the given role
-- - e stands for a coercion of a specific unknown role
-- (think "role polymorphism")
-- - "e" stands for an explicit role parameter indicating role e.
-- - _ stands for a parameter that is not a Role or Coercion.
-- These ones mirror the shape of types
= -- Refl :: "e" -> _ -> e
Refl Role Type -- See Note [Refl invariant]
-- Invariant: applications of (Refl T) to a bunch of identity coercions
-- always show up as Refl.
-- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)).
-- Applications of (Refl T) to some coercions, at least one of
-- which is NOT the identity, show up as TyConAppCo.
-- (They may not be fully saturated however.)
-- ConAppCo coercions (like all coercions other than Refl)
-- are NEVER the identity.
-- Use (Refl Representational _), not (SubCo (Refl Nominal _))
-- These ones simply lift the correspondingly-named
-- Type constructors into Coercions
-- TyConAppCo :: "e" -> _ -> ?? -> e
-- See Note [TyConAppCo roles]
| TyConAppCo Role TyCon [Coercion] -- lift TyConApp
-- The TyCon is never a synonym;
-- we expand synonyms eagerly
-- But it can be a type function
| AppCo Coercion CoercionN -- lift AppTy
-- AppCo :: e -> N -> e
-- See Note [Forall coercions]
| ForAllCo TyVar KindCoercion Coercion
-- ForAllCo :: _ -> N -> e -> e
| FunCo Role Coercion Coercion -- lift FunTy
-- FunCo :: "e" -> e -> e -> e
-- These are special
| CoVarCo CoVar -- :: _ -> (N or R)
-- result role depends on the tycon of the variable's type
-- AxiomInstCo :: e -> _ -> [N] -> e
| AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion]
-- See also [CoAxiom index]
-- The coercion arguments always *precisely* saturate
-- arity of (that branch of) the CoAxiom. If there are
-- any left over, we use AppCo.
-- See [Coercion axioms applied to coercions]
| AxiomRuleCo CoAxiomRule [Coercion]
-- AxiomRuleCo is very like AxiomInstCo, but for a CoAxiomRule
-- The number coercions should match exactly the expectations
-- of the CoAxiomRule (i.e., the rule is fully saturated).
| UnivCo UnivCoProvenance Role Type Type
-- :: _ -> "e" -> _ -> _ -> e
| SymCo Coercion -- :: e -> e
| TransCo Coercion Coercion -- :: e -> e -> e
| NthCo Role Int Coercion -- Zero-indexed; decomposes (T t0 ... tn)
-- :: "e" -> _ -> e0 -> e (inverse of TyConAppCo, see Note [TyConAppCo roles])
-- Using NthCo on a ForAllCo gives an N coercion always
-- See Note [NthCo and newtypes]
--
-- Invariant: (NthCo r i co), it is always the case that r = role of (Nth i co)
-- That is: the role of the entire coercion is redundantly cached here.
-- See Note [NthCo Cached Roles]
| LRCo LeftOrRight CoercionN -- Decomposes (t_left t_right)
-- :: _ -> N -> N
| InstCo Coercion CoercionN
-- :: e -> N -> e
-- See Note [InstCo roles]
-- Coherence applies a coercion to the left-hand type of another coercion
-- See Note [Coherence]
| CoherenceCo Coercion KindCoercion
-- :: e -> N -> e
-- Extract a kind coercion from a (heterogeneous) type coercion
-- NB: all kind coercions are Nominal
| KindCo Coercion
-- :: e -> N
| SubCo CoercionN -- Turns a ~N into a ~R
-- :: N -> R
| HoleCo CoercionHole -- ^ See Note [Coercion holes]
-- Only present during typechecking
deriving Data.Data
type CoercionN = Coercion -- always nominal
type CoercionR = Coercion -- always representational
type CoercionP = Coercion -- always phantom
type KindCoercion = CoercionN -- always nominal
{-
Note [Refl invariant]
~~~~~~~~~~~~~~~~~~~~~
Invariant 1:
Coercions have the following invariant
Refl is always lifted as far as possible.
You might think that a consequencs is:
Every identity coercions has Refl at the root
But that's not quite true because of coercion variables. Consider
g where g :: Int~Int
Left h where h :: Maybe Int ~ Maybe Int
etc. So the consequence is only true of coercions that
have no coercion variables.
Note [Coercion axioms applied to coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reason coercion axioms can be applied to coercions and not just
types is to allow for better optimization. There are some cases where
we need to be able to "push transitivity inside" an axiom in order to
expose further opportunities for optimization.
For example, suppose we have
C a : t[a] ~ F a
g : b ~ c
and we want to optimize
sym (C b) ; t[g] ; C c
which has the kind
F b ~ F c
(stopping through t[b] and t[c] along the way).
We'd like to optimize this to just F g -- but how? The key is
that we need to allow axioms to be instantiated by *coercions*,
not just by types. Then we can (in certain cases) push
transitivity inside the axiom instantiations, and then react
opposite-polarity instantiations of the same axiom. In this
case, e.g., we match t[g] against the LHS of (C c)'s kind, to
obtain the substitution a |-> g (note this operation is sort
of the dual of lifting!) and hence end up with
C g : t[b] ~ F c
which indeed has the same kind as t[g] ; C c.
Now we have
sym (C b) ; C g