94314d122fb99aa43a44cdb1e199b74f313dda9f
[ghc.git] / compiler / types / TyCoRep.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1998
4 \section[TyCoRep]{Type and Coercion - friends' interface}
5
6 Note [The Type-related module hierarchy]
7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8 Class
9 CoAxiom
10 TyCon imports Class, CoAxiom
11 TyCoRep imports Class, CoAxiom, TyCon
12 TysPrim imports TyCoRep ( including mkTyConTy )
13 Kind imports TysPrim ( mainly for primitive kinds )
14 Type imports Kind
15 Coercion imports Type
16 -}
17
18 -- We expose the relevant stuff from this module via the Type module
19 {-# OPTIONS_HADDOCK hide #-}
20 {-# LANGUAGE CPP, DeriveDataTypeable, MultiWayIf #-}
21
22 module TyCoRep (
23 TyThing(..), tyThingCategory, pprTyThingCategory, pprShortTyThing,
24
25 -- * Types
26 Type(..),
27 TyLit(..),
28 KindOrType, Kind,
29 PredType, ThetaType, -- Synonyms
30 ArgFlag(..),
31
32 -- * Coercions
33 Coercion(..),
34 UnivCoProvenance(..),
35 CoercionHole(..), coHoleCoVar, setCoHoleCoVar,
36 CoercionN, CoercionR, CoercionP, KindCoercion,
37
38 -- * Functions over types
39 mkTyConTy, mkTyVarTy, mkTyVarTys,
40 mkFunTy, mkFunTys, mkForAllTy, mkForAllTys,
41 mkPiTy, mkPiTys,
42 isTYPE, tcIsTYPE,
43 isLiftedTypeKind, isUnliftedTypeKind,
44 isCoercionType, isRuntimeRepTy, isRuntimeRepVar,
45 sameVis,
46
47 -- * Functions over binders
48 TyBinder(..), TyVarBinder,
49 binderVar, binderVars, binderKind, binderArgFlag,
50 delBinderVar,
51 isInvisibleArgFlag, isVisibleArgFlag,
52 isInvisibleBinder, isVisibleBinder,
53
54 -- * Functions over coercions
55 pickLR,
56
57 -- * Pretty-printing
58 pprType, pprParendType, pprPrecType,
59 pprTypeApp, pprTvBndr, pprTvBndrs,
60 pprSigmaType,
61 pprTheta, pprParendTheta, pprForAll, pprUserForAll,
62 pprTyVar, pprTyVars,
63 pprThetaArrowTy, pprClassPred,
64 pprKind, pprParendKind, pprTyLit,
65 TyPrec(..), maybeParen,
66 pprDataCons, ppSuggestExplicitKinds,
67
68 pprCo, pprParendCo,
69
70 debugPprType,
71
72 -- * Free variables
73 tyCoVarsOfType, tyCoVarsOfTypeDSet, tyCoVarsOfTypes, tyCoVarsOfTypesDSet,
74 tyCoFVsBndr, tyCoFVsOfType, tyCoVarsOfTypeList,
75 tyCoFVsOfTypes, tyCoVarsOfTypesList,
76 closeOverKindsDSet, closeOverKindsFV, closeOverKindsList,
77 coVarsOfType, coVarsOfTypes,
78 coVarsOfCo, coVarsOfCos,
79 tyCoVarsOfCo, tyCoVarsOfCos,
80 tyCoVarsOfCoDSet,
81 tyCoFVsOfCo, tyCoFVsOfCos,
82 tyCoVarsOfCoList, tyCoVarsOfProv,
83 closeOverKinds,
84 injectiveVarsOfBinder, injectiveVarsOfType,
85
86 noFreeVarsOfType, noFreeVarsOfCo,
87
88 -- * Substitutions
89 TCvSubst(..), TvSubstEnv, CvSubstEnv,
90 emptyTvSubstEnv, emptyCvSubstEnv, composeTCvSubstEnv, composeTCvSubst,
91 emptyTCvSubst, mkEmptyTCvSubst, isEmptyTCvSubst,
92 mkTCvSubst, mkTvSubst,
93 getTvSubstEnv,
94 getCvSubstEnv, getTCvInScope, getTCvSubstRangeFVs,
95 isInScope, notElemTCvSubst,
96 setTvSubstEnv, setCvSubstEnv, zapTCvSubst,
97 extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
98 extendTCvSubst,
99 extendCvSubst, extendCvSubstWithClone,
100 extendTvSubst, extendTvSubstBinderAndInScope, extendTvSubstWithClone,
101 extendTvSubstList, extendTvSubstAndInScope,
102 unionTCvSubst, zipTyEnv, zipCoEnv, mkTyCoInScopeSet,
103 zipTvSubst, zipCvSubst,
104 mkTvSubstPrs,
105
106 substTyWith, substTyWithCoVars, substTysWith, substTysWithCoVars,
107 substCoWith,
108 substTy, substTyAddInScope,
109 substTyUnchecked, substTysUnchecked, substThetaUnchecked,
110 substTyWithUnchecked,
111 substCoUnchecked, substCoWithUnchecked,
112 substTyWithInScope,
113 substTys, substTheta,
114 lookupTyVar, substTyVarBndr,
115 substCo, substCos, substCoVar, substCoVars, lookupCoVar,
116 substCoVarBndr, cloneTyVarBndr, cloneTyVarBndrs,
117 substTyVar, substTyVars,
118 substForAllCoBndr,
119 substTyVarBndrCallback, substForAllCoBndrCallback,
120 checkValidSubst, isValidTCvSubst,
121
122 -- * Tidying type related things up for printing
123 tidyType, tidyTypes,
124 tidyOpenType, tidyOpenTypes,
125 tidyOpenKind,
126 tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
127 tidyOpenTyCoVar, tidyOpenTyCoVars,
128 tidyTyVarOcc,
129 tidyTopType,
130 tidyKind,
131 tidyCo, tidyCos,
132 tidyTyVarBinder, tidyTyVarBinders,
133
134 -- * Sizes
135 typeSize, coercionSize, provSize
136 ) where
137
138 #include "HsVersions.h"
139
140 import GhcPrelude
141
142 import {-# SOURCE #-} DataCon( dataConFullSig
143 , dataConUserTyVarBinders
144 , DataCon )
145 import {-# SOURCE #-} Type( isPredTy, isCoercionTy, mkAppTy, mkCastTy
146 , tyCoVarsOfTypeWellScoped
147 , tyCoVarsOfTypesWellScoped
148 , toposortTyVars
149 , coreView, tcView )
150 -- Transitively pulls in a LOT of stuff, better to break the loop
151
152 import {-# SOURCE #-} Coercion
153 import {-# SOURCE #-} ConLike ( ConLike(..), conLikeName )
154 import {-# SOURCE #-} ToIface( toIfaceTypeX, toIfaceTyLit, toIfaceForAllBndr
155 , toIfaceTyCon, toIfaceTcArgs, toIfaceCoercionX )
156
157 -- friends:
158 import IfaceType
159 import Var
160 import VarEnv
161 import VarSet
162 import Name hiding ( varName )
163 import TyCon
164 import Class
165 import CoAxiom
166 import FV
167
168 -- others
169 import BasicTypes ( LeftOrRight(..), TyPrec(..), maybeParen, pickLR )
170 import PrelNames
171 import Outputable
172 import DynFlags
173 import FastString
174 import Pair
175 import UniqSupply
176 import Util
177 import UniqFM
178 import UniqSet
179
180 -- libraries
181 import qualified Data.Data as Data hiding ( TyCon )
182 import Data.List
183 import Data.IORef ( IORef ) -- for CoercionHole
184
185 {-
186 %************************************************************************
187 %* *
188 TyThing
189 %* *
190 %************************************************************************
191
192 Despite the fact that DataCon has to be imported via a hi-boot route,
193 this module seems the right place for TyThing, because it's needed for
194 funTyCon and all the types in TysPrim.
195
196 It is also SOURCE-imported into Name.hs
197
198
199 Note [ATyCon for classes]
200 ~~~~~~~~~~~~~~~~~~~~~~~~~
201 Both classes and type constructors are represented in the type environment
202 as ATyCon. You can tell the difference, and get to the class, with
203 isClassTyCon :: TyCon -> Bool
204 tyConClass_maybe :: TyCon -> Maybe Class
205 The Class and its associated TyCon have the same Name.
206 -}
207
208 -- | A global typecheckable-thing, essentially anything that has a name.
209 -- Not to be confused with a 'TcTyThing', which is also a typecheckable
210 -- thing but in the *local* context. See 'TcEnv' for how to retrieve
211 -- a 'TyThing' given a 'Name'.
212 data TyThing
213 = AnId Id
214 | AConLike ConLike
215 | ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes]
216 | ACoAxiom (CoAxiom Branched)
217
218 instance Outputable TyThing where
219 ppr = pprShortTyThing
220
221 instance NamedThing TyThing where -- Can't put this with the type
222 getName (AnId id) = getName id -- decl, because the DataCon instance
223 getName (ATyCon tc) = getName tc -- isn't visible there
224 getName (ACoAxiom cc) = getName cc
225 getName (AConLike cl) = conLikeName cl
226
227 pprShortTyThing :: TyThing -> SDoc
228 -- c.f. PprTyThing.pprTyThing, which prints all the details
229 pprShortTyThing thing
230 = pprTyThingCategory thing <+> quotes (ppr (getName thing))
231
232 pprTyThingCategory :: TyThing -> SDoc
233 pprTyThingCategory = text . capitalise . tyThingCategory
234
235 tyThingCategory :: TyThing -> String
236 tyThingCategory (ATyCon tc)
237 | isClassTyCon tc = "class"
238 | otherwise = "type constructor"
239 tyThingCategory (ACoAxiom _) = "coercion axiom"
240 tyThingCategory (AnId _) = "identifier"
241 tyThingCategory (AConLike (RealDataCon _)) = "data constructor"
242 tyThingCategory (AConLike (PatSynCon _)) = "pattern synonym"
243
244
245 {- **********************************************************************
246 * *
247 Type
248 * *
249 ********************************************************************** -}
250
251 -- | The key representation of types within the compiler
252
253 type KindOrType = Type -- See Note [Arguments to type constructors]
254
255 -- | The key type representing kinds in the compiler.
256 type Kind = Type
257
258 -- If you edit this type, you may need to update the GHC formalism
259 -- See Note [GHC Formalism] in coreSyn/CoreLint.hs
260 data Type
261 -- See Note [Non-trivial definitional equality]
262 = TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
263
264 | AppTy
265 Type
266 Type -- ^ Type application to something other than a 'TyCon'. Parameters:
267 --
268 -- 1) Function: must /not/ be a 'TyConApp' or 'CastTy',
269 -- must be another 'AppTy', or 'TyVarTy'
270 -- See Note [Respecting definitional equality] (EQ1) about the
271 -- no 'CastTy' requirement
272 --
273 -- 2) Argument type
274
275 | TyConApp
276 TyCon
277 [KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
278 -- Invariant: saturated applications of 'FunTyCon' must
279 -- use 'FunTy' and saturated synonyms must use their own
280 -- constructors. However, /unsaturated/ 'FunTyCon's
281 -- do appear as 'TyConApp's.
282 -- Parameters:
283 --
284 -- 1) Type constructor being applied to.
285 --
286 -- 2) Type arguments. Might not have enough type arguments
287 -- here to saturate the constructor.
288 -- Even type synonyms are not necessarily saturated;
289 -- for example unsaturated type synonyms
290 -- can appear as the right hand side of a type synonym.
291
292 | ForAllTy
293 {-# UNPACK #-} !TyVarBinder
294 Type -- ^ A Π type.
295
296 | FunTy Type Type -- ^ t1 -> t2 Very common, so an important special case
297
298 | LitTy TyLit -- ^ Type literals are similar to type constructors.
299
300 | CastTy
301 Type
302 KindCoercion -- ^ A kind cast. The coercion is always nominal.
303 -- INVARIANT: The cast is never refl.
304 -- INVARIANT: The Type is not a CastTy (use TransCo instead)
305 -- See Note [Respecting definitional equality] (EQ2) and (EQ3)
306
307 | CoercionTy
308 Coercion -- ^ Injection of a Coercion into a type
309 -- This should only ever be used in the RHS of an AppTy,
310 -- in the list of a TyConApp, when applying a promoted
311 -- GADT data constructor
312
313 deriving Data.Data
314
315
316 -- NOTE: Other parts of the code assume that type literals do not contain
317 -- types or type variables.
318 data TyLit
319 = NumTyLit Integer
320 | StrTyLit FastString
321 deriving (Eq, Ord, Data.Data)
322
323 {- Note [Arguments to type constructors]
324 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
325 Because of kind polymorphism, in addition to type application we now
326 have kind instantiation. We reuse the same notations to do so.
327
328 For example:
329
330 Just (* -> *) Maybe
331 Right * Nat Zero
332
333 are represented by:
334
335 TyConApp (PromotedDataCon Just) [* -> *, Maybe]
336 TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)]
337
338 Important note: Nat is used as a *kind* and not as a type. This can be
339 confusing, since type-level Nat and kind-level Nat are identical. We
340 use the kind of (PromotedDataCon Right) to know if its arguments are
341 kinds or types.
342
343 This kind instantiation only happens in TyConApp currently.
344
345 Note [Non-trivial definitional equality]
346 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
347 Is Int |> <*> the same as Int? YES! In order to reduce headaches,
348 we decide that any reflexive casts in types are just ignored.
349 (Indeed they must be. See Note [Respecting definitional equality].)
350 More generally, the `eqType` function, which defines Core's type equality
351 relation, ignores casts and coercion arguments, as long as the
352 two types have the same kind. This allows us to be a little sloppier
353 in keeping track of coercions, which is a good thing. It also means
354 that eqType does not depend on eqCoercion, which is also a good thing.
355
356 Why is this sensible? That is, why is something different than α-equivalence
357 appropriate for the implementation of eqType?
358
359 Anything smaller than ~ and homogeneous is an appropriate definition for
360 equality. The type safety of FC depends only on ~. Let's say η : τ ~ σ. Any
361 expression of type τ can be transmuted to one of type σ at any point by
362 casting. The same is true of types of type τ. So in some sense, τ and σ are
363 interchangeable.
364
365 But let's be more precise. If we examine the typing rules of FC (say, those in
366 http://www.cis.upenn.edu/~eir/papers/2015/equalities/equalities-extended.pdf)
367 there are several places where the same metavariable is used in two different
368 premises to a rule. (For example, see Ty_App.) There is an implicit equality
369 check here. What definition of equality should we use? By convention, we use
370 α-equivalence. Take any rule with one (or more) of these implicit equality
371 checks. Then there is an admissible rule that uses ~ instead of the implicit
372 check, adding in casts as appropriate.
373
374 The only problem here is that ~ is heterogeneous. To make the kinds work out
375 in the admissible rule that uses ~, it is necessary to homogenize the
376 coercions. That is, if we have η : (τ : κ1) ~ (σ : κ2), then we don't use η;
377 we use η |> kind η, which is homogeneous.
378
379 The effect of this all is that eqType, the implementation of the implicit
380 equality check, can use any homogeneous relation that is smaller than ~, as
381 those rules must also be admissible.
382
383 A more drawn out argument around all of this is presented in Section 7.2 of
384 Richard E's thesis (http://cs.brynmawr.edu/~rae/papers/2016/thesis/eisenberg-thesis.pdf).
385
386 What would go wrong if we insisted on the casts matching? See the beginning of
387 Section 8 in the unpublished paper above. Theoretically, nothing at all goes
388 wrong. But in practical terms, getting the coercions right proved to be
389 nightmarish. And types would explode: during kind-checking, we often produce
390 reflexive kind coercions. When we try to cast by these, mkCastTy just discards
391 them. But if we used an eqType that distinguished between Int and Int |> <*>,
392 then we couldn't discard -- the output of kind-checking would be enormous,
393 and we would need enormous casts with lots of CoherenceCo's to straighten
394 them out.
395
396 Would anything go wrong if eqType respected type families? No, not at all. But
397 that makes eqType rather hard to implement.
398
399 Thus, the guideline for eqType is that it should be the largest
400 easy-to-implement relation that is still smaller than ~ and homogeneous. The
401 precise choice of relation is somewhat incidental, as long as the smart
402 constructors and destructors in Type respect whatever relation is chosen.
403
404 Another helpful principle with eqType is this:
405
406 (EQ) If (t1 `eqType` t2) then I can replace t1 by t2 anywhere.
407
408 This principle also tells us that eqType must relate only types with the
409 same kinds.
410
411 Note [Respecting definitional equality]
412 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413 Note [Non-trivial definitional equality] introduces the property (EQ).
414 How is this upheld?
415
416 Any function that pattern matches on all the constructors will have to
417 consider the possibility of CastTy. Presumably, those functions will handle
418 CastTy appropriately and we'll be OK.
419
420 More dangerous are the splitXXX functions. Let's focus on splitTyConApp.
421 We don't want it to fail on (T a b c |> co). Happily, if we have
422 (T a b c |> co) `eqType` (T d e f)
423 then co must be reflexive. Why? eqType checks that the kinds are equal, as
424 well as checking that (a `eqType` d), (b `eqType` e), and (c `eqType` f).
425 By the kind check, we know that (T a b c |> co) and (T d e f) have the same
426 kind. So the only way that co could be non-reflexive is for (T a b c) to have
427 a different kind than (T d e f). But because T's kind is closed (all tycon kinds
428 are closed), the only way for this to happen is that one of the arguments has
429 to differ, leading to a contradiction. Thus, co is reflexive.
430
431 Accordingly, by eliminating reflexive casts, splitTyConApp need not worry
432 about outermost casts to uphold (EQ). Eliminating reflexive casts is done
433 in mkCastTy.
434
435 Unforunately, that's not the end of the story. Consider comparing
436 (T a b c) =? (T a b |> (co -> <Type>)) (c |> co)
437 These two types have the same kind (Type), but the left type is a TyConApp
438 while the right type is not. To handle this case, we say that the right-hand
439 type is ill-formed, requiring an AppTy never to have a casted TyConApp
440 on its left. It is easy enough to pull around the coercions to maintain
441 this invariant, as done in Type.mkAppTy. In the example above, trying to
442 form the right-hand type will instead yield (T a b (c |> co |> sym co) |> <Type>).
443 Both the casts there are reflexive and will be dropped. Huzzah.
444
445 This idea of pulling coercions to the right works for splitAppTy as well.
446
447 However, there is one hiccup: it's possible that a coercion doesn't relate two
448 Pi-types. For example, if we have @type family Fun a b where Fun a b = a -> b@,
449 then we might have (T :: Fun Type Type) and (T |> axFun) Int. That axFun can't
450 be pulled to the right. But we don't need to pull it: (T |> axFun) Int is not
451 `eqType` to any proper TyConApp -- thus, leaving it where it is doesn't violate
452 our (EQ) property.
453
454 Lastly, in order to detect reflexive casts reliably, we must make sure not
455 to have nested casts: we update (t |> co1 |> co2) to (t |> (co1 `TransCo` co2)).
456
457 In sum, in order to uphold (EQ), we need the following three invariants:
458
459 (EQ1) No decomposable CastTy to the left of an AppTy, where a decomposable
460 cast is one that relates either a FunTy to a FunTy or a
461 ForAllTy to a ForAllTy.
462 (EQ2) No reflexive casts in CastTy.
463 (EQ3) No nested CastTys.
464
465 These invariants are all documented above, in the declaration for Type.
466
467 -}
468
469 {- **********************************************************************
470 * *
471 TyBinder and ArgFlag
472 * *
473 ********************************************************************** -}
474
475 -- | A 'TyBinder' represents an argument to a function. TyBinders can be dependent
476 -- ('Named') or nondependent ('Anon'). They may also be visible or not.
477 -- See Note [TyBinders]
478 data TyBinder
479 = Named TyVarBinder -- A type-lambda binder
480 | Anon Type -- A term-lambda binder
481 -- Visibility is determined by the type (Constraint vs. *)
482 deriving Data.Data
483
484 -- | Remove the binder's variable from the set, if the binder has
485 -- a variable.
486 delBinderVar :: VarSet -> TyVarBinder -> VarSet
487 delBinderVar vars (TvBndr tv _) = vars `delVarSet` tv
488
489 -- | Does this binder bind an invisible argument?
490 isInvisibleBinder :: TyBinder -> Bool
491 isInvisibleBinder (Named (TvBndr _ vis)) = isInvisibleArgFlag vis
492 isInvisibleBinder (Anon ty) = isPredTy ty
493
494 -- | Does this binder bind a visible argument?
495 isVisibleBinder :: TyBinder -> Bool
496 isVisibleBinder = not . isInvisibleBinder
497
498
499 {- Note [TyBinders]
500 ~~~~~~~~~~~~~~~~~~~
501 A ForAllTy contains a TyVarBinder. But a type can be decomposed
502 to a telescope consisting of a [TyBinder]
503
504 A TyBinder represents the type of binders -- that is, the type of an
505 argument to a Pi-type. GHC Core currently supports two different
506 Pi-types:
507
508 * A non-dependent function type,
509 written with ->, e.g. ty1 -> ty2
510 represented as FunTy ty1 ty2. These are
511 lifted to Coercions with the corresponding FunCo.
512
513 * A dependent compile-time-only polytype,
514 written with forall, e.g. forall (a:*). ty
515 represented as ForAllTy (TvBndr a v) ty
516
517 Both Pi-types classify terms/types that take an argument. In other
518 words, if `x` is either a function or a polytype, `x arg` makes sense
519 (for an appropriate `arg`).
520
521
522 Note [TyVarBndrs, TyVarBinders, TyConBinders, and visibility]
523 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
524 * A ForAllTy (used for both types and kinds) contains a TyVarBinder.
525 Each TyVarBinder
526 TvBndr a tvis
527 is equipped with tvis::ArgFlag, which says whether or not arguments
528 for this binder should be visible (explicit) in source Haskell.
529
530 * A TyCon contains a list of TyConBinders. Each TyConBinder
531 TvBndr a cvis
532 is equipped with cvis::TyConBndrVis, which says whether or not type
533 and kind arguments for this TyCon should be visible (explicit) in
534 source Haskell.
535
536 This table summarises the visibility rules:
537 ---------------------------------------------------------------------------------------
538 | Occurrences look like this
539 | GHC displays type as in Haskell source code
540 |-----------------------------------------------------------------------
541 | TvBndr a tvis :: TyVarBinder, in the binder of ForAllTy for a term
542 | tvis :: ArgFlag
543 | tvis = Inferred: f :: forall {a}. type Arg not allowed: f
544 | tvis = Specified: f :: forall a. type Arg optional: f or f @Int
545 | tvis = Required: T :: forall k -> type Arg required: T *
546 | This last form is illegal in terms: See Note [No Required TyBinder in terms]
547 |
548 | TvBndr k cvis :: TyConBinder, in the TyConBinders of a TyCon
549 | cvis :: TyConBndrVis
550 | cvis = AnonTCB: T :: kind -> kind Required: T *
551 | cvis = NamedTCB Inferred: T :: forall {k}. kind Arg not allowed: T
552 | cvis = NamedTCB Specified: T :: forall k. kind Arg not allowed[1]: T
553 | cvis = NamedTCB Required: T :: forall k -> kind Required: T *
554 ---------------------------------------------------------------------------------------
555
556 [1] In types, in the Specified case, it would make sense to allow
557 optional kind applications, thus (T @*), but we have not
558 yet implemented that
559
560 ---- Examples of where the different visibilities come from -----
561
562 In term declarations:
563
564 * Inferred. Function defn, with no signature: f1 x = x
565 We infer f1 :: forall {a}. a -> a, with 'a' Inferred
566 It's Inferred because it doesn't appear in any
567 user-written signature for f1
568
569 * Specified. Function defn, with signature (implicit forall):
570 f2 :: a -> a; f2 x = x
571 So f2 gets the type f2 :: forall a. a->a, with 'a' Specified
572 even though 'a' is not bound in the source code by an explicit forall
573
574 * Specified. Function defn, with signature (explicit forall):
575 f3 :: forall a. a -> a; f3 x = x
576 So f3 gets the type f3 :: forall a. a->a, with 'a' Specified
577
578 * Inferred/Specified. Function signature with inferred kind polymorphism.
579 f4 :: a b -> Int
580 So 'f4' gets the type f4 :: forall {k} (a:k->*) (b:k). a b -> Int
581 Here 'k' is Inferred (it's not mentioned in the type),
582 but 'a' and 'b' are Specified.
583
584 * Specified. Function signature with explicit kind polymorphism
585 f5 :: a (b :: k) -> Int
586 This time 'k' is Specified, because it is mentioned explicitly,
587 so we get f5 :: forall (k:*) (a:k->*) (b:k). a b -> Int
588
589 * Similarly pattern synonyms:
590 Inferred - from inferred types (e.g. no pattern type signature)
591 - or from inferred kind polymorphism
592
593 In type declarations:
594
595 * Inferred (k)
596 data T1 a b = MkT1 (a b)
597 Here T1's kind is T1 :: forall {k:*}. (k->*) -> k -> *
598 The kind variable 'k' is Inferred, since it is not mentioned
599
600 Note that 'a' and 'b' correspond to /Anon/ TyBinders in T1's kind,
601 and Anon binders don't have a visibility flag. (Or you could think
602 of Anon having an implicit Required flag.)
603
604 * Specified (k)
605 data T2 (a::k->*) b = MkT (a b)
606 Here T's kind is T :: forall (k:*). (k->*) -> k -> *
607 The kind variable 'k' is Specified, since it is mentioned in
608 the signature.
609
610 * Required (k)
611 data T k (a::k->*) b = MkT (a b)
612 Here T's kind is T :: forall k:* -> (k->*) -> k -> *
613 The kind is Required, since it bound in a positional way in T's declaration
614 Every use of T must be explicitly applied to a kind
615
616 * Inferred (k1), Specified (k)
617 data T a b (c :: k) = MkT (a b) (Proxy c)
618 Here T's kind is T :: forall {k1:*} (k:*). (k1->*) -> k1 -> k -> *
619 So 'k' is Specified, because it appears explicitly,
620 but 'k1' is Inferred, because it does not
621
622 ---- Printing -----
623
624 We print forall types with enough syntax to tell you their visibility
625 flag. But this is not source Haskell, and these types may not all
626 be parsable.
627
628 Specified: a list of Specified binders is written between `forall` and `.`:
629 const :: forall a b. a -> b -> a
630
631 Inferred: with -fprint-explicit-foralls, Inferred binders are written
632 in braces:
633 f :: forall {k} (a:k). S k a -> Int
634 Otherwise, they are printed like Specified binders.
635
636 Required: binders are put between `forall` and `->`:
637 T :: forall k -> *
638
639 ---- Other points -----
640
641 * In classic Haskell, all named binders (that is, the type variables in
642 a polymorphic function type f :: forall a. a -> a) have been Inferred.
643
644 * Inferred variables correspond to "generalized" variables from the
645 Visible Type Applications paper (ESOP'16).
646
647 Note [No Required TyBinder in terms]
648 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
649 We don't allow Required foralls for term variables, including pattern
650 synonyms and data constructors. Why? Because then an application
651 would need a /compulsory/ type argument (possibly without an "@"?),
652 thus (f Int); and we don't have concrete syntax for that.
653
654 We could change this decision, but Required, Named TyBinders are rare
655 anyway. (Most are Anons.)
656 -}
657
658
659 {- **********************************************************************
660 * *
661 PredType
662 * *
663 ********************************************************************** -}
664
665
666 -- | A type of the form @p@ of kind @Constraint@ represents a value whose type is
667 -- the Haskell predicate @p@, where a predicate is what occurs before
668 -- the @=>@ in a Haskell type.
669 --
670 -- We use 'PredType' as documentation to mark those types that we guarantee to have
671 -- this kind.
672 --
673 -- It can be expanded into its representation, but:
674 --
675 -- * The type checker must treat it as opaque
676 --
677 -- * The rest of the compiler treats it as transparent
678 --
679 -- Consider these examples:
680 --
681 -- > f :: (Eq a) => a -> Int
682 -- > g :: (?x :: Int -> Int) => a -> Int
683 -- > h :: (r\l) => {r} => {l::Int | r}
684 --
685 -- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
686 type PredType = Type
687
688 -- | A collection of 'PredType's
689 type ThetaType = [PredType]
690
691 {-
692 (We don't support TREX records yet, but the setup is designed
693 to expand to allow them.)
694
695 A Haskell qualified type, such as that for f,g,h above, is
696 represented using
697 * a FunTy for the double arrow
698 * with a type of kind Constraint as the function argument
699
700 The predicate really does turn into a real extra argument to the
701 function. If the argument has type (p :: Constraint) then the predicate p is
702 represented by evidence of type p.
703
704
705 %************************************************************************
706 %* *
707 Simple constructors
708 %* *
709 %************************************************************************
710
711 These functions are here so that they can be used by TysPrim,
712 which in turn is imported by Type
713 -}
714
715 -- named with "Only" to prevent naive use of mkTyVarTy
716 mkTyVarTy :: TyVar -> Type
717 mkTyVarTy v = ASSERT2( isTyVar v, ppr v <+> dcolon <+> ppr (tyVarKind v) )
718 TyVarTy v
719
720 mkTyVarTys :: [TyVar] -> [Type]
721 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
722
723 infixr 3 `mkFunTy` -- Associates to the right
724 -- | Make an arrow type
725 mkFunTy :: Type -> Type -> Type
726 mkFunTy arg res = FunTy arg res
727
728 -- | Make nested arrow types
729 mkFunTys :: [Type] -> Type -> Type
730 mkFunTys tys ty = foldr mkFunTy ty tys
731
732 mkForAllTy :: TyVar -> ArgFlag -> Type -> Type
733 mkForAllTy tv vis ty = ForAllTy (TvBndr tv vis) ty
734
735 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
736 mkForAllTys :: [TyVarBinder] -> Type -> Type
737 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
738
739 mkPiTy :: TyBinder -> Type -> Type
740 mkPiTy (Anon ty1) ty2 = FunTy ty1 ty2
741 mkPiTy (Named tvb) ty = ForAllTy tvb ty
742
743 mkPiTys :: [TyBinder] -> Type -> Type
744 mkPiTys tbs ty = foldr mkPiTy ty tbs
745
746 -- | Does this type classify a core (unlifted) Coercion?
747 -- At either role nominal or representational
748 -- (t1 ~# t2) or (t1 ~R# t2)
749 isCoercionType :: Type -> Bool
750 isCoercionType (TyConApp tc tys)
751 | (tc `hasKey` eqPrimTyConKey) || (tc `hasKey` eqReprPrimTyConKey)
752 , tys `lengthIs` 4
753 = True
754 isCoercionType _ = False
755
756
757 -- | Create the plain type constructor type which has been applied to no type arguments at all.
758 mkTyConTy :: TyCon -> Type
759 mkTyConTy tycon = TyConApp tycon []
760
761 {-
762 Some basic functions, put here to break loops eg with the pretty printer
763 -}
764
765 -- | If a type is @'TYPE' r@ for some @r@, run the predicate argument on @r@.
766 -- Otherwise, return 'False'.
767 --
768 -- This function does not distinguish between 'Constraint' and 'Type'. For a
769 -- version which does distinguish between the two, see 'tcIsTYPE'.
770 isTYPE :: ( Type -- the single argument to TYPE; not a synonym
771 -> Bool ) -- what to return
772 -> Kind -> Bool
773 isTYPE f ki | Just ki' <- coreView ki = isTYPE f ki'
774 isTYPE f (TyConApp tc [arg])
775 | tc `hasKey` tYPETyConKey
776 = go arg
777 where
778 go ty | Just ty' <- coreView ty = go ty'
779 go ty = f ty
780 isTYPE _ _ = False
781
782 -- | If a type is @'TYPE' r@ for some @r@, run the predicate argument on @r@.
783 -- Otherwise, return 'False'.
784 --
785 -- This function distinguishes between 'Constraint' and 'Type' (and will return
786 -- 'False' for 'Constraint'). For a version which does not distinguish between
787 -- the two, see 'isTYPE'.
788 tcIsTYPE :: ( Type -- the single argument to TYPE; not a synonym
789 -> Bool ) -- what to return
790 -> Kind -> Bool
791 tcIsTYPE f ki | Just ki' <- tcView ki = tcIsTYPE f ki'
792 tcIsTYPE f (TyConApp tc [arg])
793 | tc `hasKey` tYPETyConKey
794 = go arg
795 where
796 go ty | Just ty' <- tcView ty = go ty'
797 go ty = f ty
798 tcIsTYPE _ _ = False
799
800 -- | This version considers Constraint to be the same as *. Returns True
801 -- if the argument is equivalent to Type/Constraint and False otherwise.
802 isLiftedTypeKind :: Kind -> Bool
803 isLiftedTypeKind = isTYPE is_lifted
804 where
805 is_lifted (TyConApp lifted_rep []) = lifted_rep `hasKey` liftedRepDataConKey
806 is_lifted _ = False
807
808 -- | Returns True if the kind classifies unlifted types and False otherwise.
809 -- Note that this returns False for levity-polymorphic kinds, which may
810 -- be specialized to a kind that classifies unlifted types.
811 isUnliftedTypeKind :: Kind -> Bool
812 isUnliftedTypeKind = isTYPE is_unlifted
813 where
814 is_unlifted (TyConApp rr _args) = elem (getUnique rr) unliftedRepDataConKeys
815 is_unlifted _ = False
816
817 -- | Is this the type 'RuntimeRep'?
818 isRuntimeRepTy :: Type -> Bool
819 isRuntimeRepTy ty | Just ty' <- coreView ty = isRuntimeRepTy ty'
820 isRuntimeRepTy (TyConApp tc []) = tc `hasKey` runtimeRepTyConKey
821 isRuntimeRepTy _ = False
822
823 -- | Is a tyvar of type 'RuntimeRep'?
824 isRuntimeRepVar :: TyVar -> Bool
825 isRuntimeRepVar = isRuntimeRepTy . tyVarKind
826
827 {-
828 %************************************************************************
829 %* *
830 Coercions
831 %* *
832 %************************************************************************
833 -}
834
835 -- | A 'Coercion' is concrete evidence of the equality/convertibility
836 -- of two types.
837
838 -- If you edit this type, you may need to update the GHC formalism
839 -- See Note [GHC Formalism] in coreSyn/CoreLint.hs
840 data Coercion
841 -- Each constructor has a "role signature", indicating the way roles are
842 -- propagated through coercions.
843 -- - P, N, and R stand for coercions of the given role
844 -- - e stands for a coercion of a specific unknown role
845 -- (think "role polymorphism")
846 -- - "e" stands for an explicit role parameter indicating role e.
847 -- - _ stands for a parameter that is not a Role or Coercion.
848
849 -- These ones mirror the shape of types
850 = -- Refl :: "e" -> _ -> e
851 Refl Role Type -- See Note [Refl invariant]
852 -- Invariant: applications of (Refl T) to a bunch of identity coercions
853 -- always show up as Refl.
854 -- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)).
855
856 -- Applications of (Refl T) to some coercions, at least one of
857 -- which is NOT the identity, show up as TyConAppCo.
858 -- (They may not be fully saturated however.)
859 -- ConAppCo coercions (like all coercions other than Refl)
860 -- are NEVER the identity.
861
862 -- Use (Refl Representational _), not (SubCo (Refl Nominal _))
863
864 -- These ones simply lift the correspondingly-named
865 -- Type constructors into Coercions
866
867 -- TyConAppCo :: "e" -> _ -> ?? -> e
868 -- See Note [TyConAppCo roles]
869 | TyConAppCo Role TyCon [Coercion] -- lift TyConApp
870 -- The TyCon is never a synonym;
871 -- we expand synonyms eagerly
872 -- But it can be a type function
873
874 | AppCo Coercion CoercionN -- lift AppTy
875 -- AppCo :: e -> N -> e
876
877 -- See Note [Forall coercions]
878 | ForAllCo TyVar KindCoercion Coercion
879 -- ForAllCo :: _ -> N -> e -> e
880
881 | FunCo Role Coercion Coercion -- lift FunTy
882 -- FunCo :: "e" -> e -> e -> e
883
884 -- These are special
885 | CoVarCo CoVar -- :: _ -> (N or R)
886 -- result role depends on the tycon of the variable's type
887
888 -- AxiomInstCo :: e -> _ -> [N] -> e
889 | AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion]
890 -- See also [CoAxiom index]
891 -- The coercion arguments always *precisely* saturate
892 -- arity of (that branch of) the CoAxiom. If there are
893 -- any left over, we use AppCo.
894 -- See [Coercion axioms applied to coercions]
895
896 | AxiomRuleCo CoAxiomRule [Coercion]
897 -- AxiomRuleCo is very like AxiomInstCo, but for a CoAxiomRule
898 -- The number coercions should match exactly the expectations
899 -- of the CoAxiomRule (i.e., the rule is fully saturated).
900
901 | UnivCo UnivCoProvenance Role Type Type
902 -- :: _ -> "e" -> _ -> _ -> e
903
904 | SymCo Coercion -- :: e -> e
905 | TransCo Coercion Coercion -- :: e -> e -> e
906
907 | NthCo Int Coercion -- Zero-indexed; decomposes (T t0 ... tn)
908 -- :: _ -> e -> ?? (inverse of TyConAppCo, see Note [TyConAppCo roles])
909 -- Using NthCo on a ForAllCo gives an N coercion always
910 -- See Note [NthCo and newtypes]
911
912 | LRCo LeftOrRight CoercionN -- Decomposes (t_left t_right)
913 -- :: _ -> N -> N
914 | InstCo Coercion CoercionN
915 -- :: e -> N -> e
916 -- See Note [InstCo roles]
917
918 -- Coherence applies a coercion to the left-hand type of another coercion
919 -- See Note [Coherence]
920 | CoherenceCo Coercion KindCoercion
921 -- :: e -> N -> e
922
923 -- Extract a kind coercion from a (heterogeneous) type coercion
924 -- NB: all kind coercions are Nominal
925 | KindCo Coercion
926 -- :: e -> N
927
928 | SubCo CoercionN -- Turns a ~N into a ~R
929 -- :: N -> R
930
931 | HoleCo CoercionHole -- ^ See Note [Coercion holes]
932 -- Only present during typechecking
933 deriving Data.Data
934
935 type CoercionN = Coercion -- always nominal
936 type CoercionR = Coercion -- always representational
937 type CoercionP = Coercion -- always phantom
938 type KindCoercion = CoercionN -- always nominal
939
940 {-
941 Note [Refl invariant]
942 ~~~~~~~~~~~~~~~~~~~~~
943 Invariant 1:
944
945 Coercions have the following invariant
946 Refl is always lifted as far as possible.
947
948 You might think that a consequencs is:
949 Every identity coercions has Refl at the root
950
951 But that's not quite true because of coercion variables. Consider
952 g where g :: Int~Int
953 Left h where h :: Maybe Int ~ Maybe Int
954 etc. So the consequence is only true of coercions that
955 have no coercion variables.
956
957 Note [Coercion axioms applied to coercions]
958 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
959 The reason coercion axioms can be applied to coercions and not just
960 types is to allow for better optimization. There are some cases where
961 we need to be able to "push transitivity inside" an axiom in order to
962 expose further opportunities for optimization.
963
964 For example, suppose we have
965
966 C a : t[a] ~ F a
967 g : b ~ c
968
969 and we want to optimize
970
971 sym (C b) ; t[g] ; C c
972
973 which has the kind
974
975 F b ~ F c
976
977 (stopping through t[b] and t[c] along the way).
978
979 We'd like to optimize this to just F g -- but how? The key is
980 that we need to allow axioms to be instantiated by *coercions*,
981 not just by types. Then we can (in certain cases) push
982 transitivity inside the axiom instantiations, and then react
983 opposite-polarity instantiations of the same axiom. In this
984 case, e.g., we match t[g] against the LHS of (C c)'s kind, to
985 obtain the substitution a |-> g (note this operation is sort
986 of the dual of lifting!) and hence end up with
987
988 C g : t[b] ~ F c
989
990 which indeed has the same kind as t[g] ; C c.
991
992 Now we have
993
994 sym (C b) ; C g
995
996 which can be optimized to F g.
997
998 Note [CoAxiom index]
999 ~~~~~~~~~~~~~~~~~~~~
1000 A CoAxiom has 1 or more branches. Each branch has contains a list
1001 of the free type variables in that branch, the LHS type patterns,
1002 and the RHS type for that branch. When we apply an axiom to a list
1003 of coercions, we must choose which branch of the axiom we wish to
1004 use, as the different branches may have different numbers of free
1005 type variables. (The number of type patterns is always the same
1006 among branches, but that doesn't quite concern us here.)
1007
1008 The Int in the AxiomInstCo constructor is the 0-indexed number
1009 of the chosen branch.
1010
1011 Note [Forall coercions]
1012 ~~~~~~~~~~~~~~~~~~~~~~~
1013 Constructing coercions between forall-types can be a bit tricky,
1014 because the kinds of the bound tyvars can be different.
1015
1016 The typing rule is:
1017
1018
1019 kind_co : k1 ~ k2
1020 tv1:k1 |- co : t1 ~ t2
1021 -------------------------------------------------------------------
1022 ForAllCo tv1 kind_co co : all tv1:k1. t1 ~
1023 all tv1:k2. (t2[tv1 |-> tv1 |> sym kind_co])
1024
1025 First, the TyVar stored in a ForAllCo is really an optimisation: this field
1026 should be a Name, as its kind is redundant. Thinking of the field as a Name
1027 is helpful in understanding what a ForAllCo means.
1028
1029 The idea is that kind_co gives the two kinds of the tyvar. See how, in the
1030 conclusion, tv1 is assigned kind k1 on the left but kind k2 on the right.
1031
1032 Of course, a type variable can't have different kinds at the same time. So,
1033 we arbitrarily prefer the first kind when using tv1 in the inner coercion
1034 co, which shows that t1 equals t2.
1035
1036 The last wrinkle is that we need to fix the kinds in the conclusion. In
1037 t2, tv1 is assumed to have kind k1, but it has kind k2 in the conclusion of
1038 the rule. So we do a kind-fixing substitution, replacing (tv1:k1) with
1039 (tv1:k2) |> sym kind_co. This substitution is slightly bizarre, because it
1040 mentions the same name with different kinds, but it *is* well-kinded, noting
1041 that `(tv1:k2) |> sym kind_co` has kind k1.
1042
1043 This all really would work storing just a Name in the ForAllCo. But we can't
1044 add Names to, e.g., VarSets, and there generally is just an impedance mismatch
1045 in a bunch of places. So we use tv1. When we need tv2, we can use
1046 setTyVarKind.
1047
1048 Note [Coherence]
1049 ~~~~~~~~~~~~~~~~
1050 The Coherence typing rule is thus:
1051
1052 g1 : s ~ t s : k1 g2 : k1 ~ k2
1053 ------------------------------------
1054 CoherenceCo g1 g2 : (s |> g2) ~ t
1055
1056 While this looks (and is) unsymmetric, a combination of other coercion
1057 combinators can make the symmetric version.
1058
1059 For role information, see Note [Roles and kind coercions].
1060
1061 Note [Predicate coercions]
1062 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1063 Suppose we have
1064 g :: a~b
1065 How can we coerce between types
1066 ([c]~a) => [a] -> c
1067 and
1068 ([c]~b) => [b] -> c
1069 where the equality predicate *itself* differs?
1070
1071 Answer: we simply treat (~) as an ordinary type constructor, so these
1072 types really look like
1073
1074 ((~) [c] a) -> [a] -> c
1075 ((~) [c] b) -> [b] -> c
1076
1077 So the coercion between the two is obviously
1078
1079 ((~) [c] g) -> [g] -> c
1080
1081 Another way to see this to say that we simply collapse predicates to
1082 their representation type (see Type.coreView and Type.predTypeRep).
1083
1084 This collapse is done by mkPredCo; there is no PredCo constructor
1085 in Coercion. This is important because we need Nth to work on
1086 predicates too:
1087 Nth 1 ((~) [c] g) = g
1088 See Simplify.simplCoercionF, which generates such selections.
1089
1090 Note [Roles]
1091 ~~~~~~~~~~~~
1092 Roles are a solution to the GeneralizedNewtypeDeriving problem, articulated
1093 in Trac #1496. The full story is in docs/core-spec/core-spec.pdf. Also, see
1094 http://ghc.haskell.org/trac/ghc/wiki/RolesImplementation
1095
1096 Here is one way to phrase the problem:
1097
1098 Given:
1099 newtype Age = MkAge Int
1100 type family F x
1101 type instance F Age = Bool
1102 type instance F Int = Char
1103
1104 This compiles down to:
1105 axAge :: Age ~ Int
1106 axF1 :: F Age ~ Bool
1107 axF2 :: F Int ~ Char
1108
1109 Then, we can make:
1110 (sym (axF1) ; F axAge ; axF2) :: Bool ~ Char
1111
1112 Yikes!
1113
1114 The solution is _roles_, as articulated in "Generative Type Abstraction and
1115 Type-level Computation" (POPL 2010), available at
1116 http://www.seas.upenn.edu/~sweirich/papers/popl163af-weirich.pdf
1117
1118 The specification for roles has evolved somewhat since that paper. For the
1119 current full details, see the documentation in docs/core-spec. Here are some
1120 highlights.
1121
1122 We label every equality with a notion of type equivalence, of which there are
1123 three options: Nominal, Representational, and Phantom. A ground type is
1124 nominally equivalent only with itself. A newtype (which is considered a ground
1125 type in Haskell) is representationally equivalent to its representation.
1126 Anything is "phantomly" equivalent to anything else. We use "N", "R", and "P"
1127 to denote the equivalences.
1128
1129 The axioms above would be:
1130 axAge :: Age ~R Int
1131 axF1 :: F Age ~N Bool
1132 axF2 :: F Age ~N Char
1133
1134 Then, because transitivity applies only to coercions proving the same notion
1135 of equivalence, the above construction is impossible.
1136
1137 However, there is still an escape hatch: we know that any two types that are
1138 nominally equivalent are representationally equivalent as well. This is what
1139 the form SubCo proves -- it "demotes" a nominal equivalence into a
1140 representational equivalence. So, it would seem the following is possible:
1141
1142 sub (sym axF1) ; F axAge ; sub axF2 :: Bool ~R Char -- WRONG
1143
1144 What saves us here is that the arguments to a type function F, lifted into a
1145 coercion, *must* prove nominal equivalence. So, (F axAge) is ill-formed, and
1146 we are safe.
1147
1148 Roles are attached to parameters to TyCons. When lifting a TyCon into a
1149 coercion (through TyConAppCo), we need to ensure that the arguments to the
1150 TyCon respect their roles. For example:
1151
1152 data T a b = MkT a (F b)
1153
1154 If we know that a1 ~R a2, then we know (T a1 b) ~R (T a2 b). But, if we know
1155 that b1 ~R b2, we know nothing about (T a b1) and (T a b2)! This is because
1156 the type function F branches on b's *name*, not representation. So, we say
1157 that 'a' has role Representational and 'b' has role Nominal. The third role,
1158 Phantom, is for parameters not used in the type's definition. Given the
1159 following definition
1160
1161 data Q a = MkQ Int
1162
1163 the Phantom role allows us to say that (Q Bool) ~R (Q Char), because we
1164 can construct the coercion Bool ~P Char (using UnivCo).
1165
1166 See the paper cited above for more examples and information.
1167
1168 Note [TyConAppCo roles]
1169 ~~~~~~~~~~~~~~~~~~~~~~~
1170 The TyConAppCo constructor has a role parameter, indicating the role at
1171 which the coercion proves equality. The choice of this parameter affects
1172 the required roles of the arguments of the TyConAppCo. To help explain
1173 it, assume the following definition:
1174
1175 type instance F Int = Bool -- Axiom axF : F Int ~N Bool
1176 newtype Age = MkAge Int -- Axiom axAge : Age ~R Int
1177 data Foo a = MkFoo a -- Role on Foo's parameter is Representational
1178
1179 TyConAppCo Nominal Foo axF : Foo (F Int) ~N Foo Bool
1180 For (TyConAppCo Nominal) all arguments must have role Nominal. Why?
1181 So that Foo Age ~N Foo Int does *not* hold.
1182
1183 TyConAppCo Representational Foo (SubCo axF) : Foo (F Int) ~R Foo Bool
1184 TyConAppCo Representational Foo axAge : Foo Age ~R Foo Int
1185 For (TyConAppCo Representational), all arguments must have the roles
1186 corresponding to the result of tyConRoles on the TyCon. This is the
1187 whole point of having roles on the TyCon to begin with. So, we can
1188 have Foo Age ~R Foo Int, if Foo's parameter has role R.
1189
1190 If a Representational TyConAppCo is over-saturated (which is otherwise fine),
1191 the spill-over arguments must all be at Nominal. This corresponds to the
1192 behavior for AppCo.
1193
1194 TyConAppCo Phantom Foo (UnivCo Phantom Int Bool) : Foo Int ~P Foo Bool
1195 All arguments must have role Phantom. This one isn't strictly
1196 necessary for soundness, but this choice removes ambiguity.
1197
1198 The rules here dictate the roles of the parameters to mkTyConAppCo
1199 (should be checked by Lint).
1200
1201 Note [NthCo and newtypes]
1202 ~~~~~~~~~~~~~~~~~~~~~~~~~
1203 Suppose we have
1204
1205 newtype N a = MkN Int
1206 type role N representational
1207
1208 This yields axiom
1209
1210 NTCo:N :: forall a. N a ~R Int
1211
1212 We can then build
1213
1214 co :: forall a b. N a ~R N b
1215 co = NTCo:N a ; sym (NTCo:N b)
1216
1217 for any `a` and `b`. Because of the role annotation on N, if we use
1218 NthCo, we'll get out a representational coercion. That is:
1219
1220 NthCo 0 co :: forall a b. a ~R b
1221
1222 Yikes! Clearly, this is terrible. The solution is simple: forbid
1223 NthCo to be used on newtypes if the internal coercion is representational.
1224
1225 This is not just some corner case discovered by a segfault somewhere;
1226 it was discovered in the proof of soundness of roles and described
1227 in the "Safe Coercions" paper (ICFP '14).
1228
1229 Note [InstCo roles]
1230 ~~~~~~~~~~~~~~~~~~~
1231 Here is (essentially) the typing rule for InstCo:
1232
1233 g :: (forall a. t1) ~r (forall a. t2)
1234 w :: s1 ~N s2
1235 ------------------------------- InstCo
1236 InstCo g w :: (t1 [a |-> s1]) ~r (t2 [a |-> s2])
1237
1238 Note that the Coercion w *must* be nominal. This is necessary
1239 because the variable a might be used in a "nominal position"
1240 (that is, a place where role inference would require a nominal
1241 role) in t1 or t2. If we allowed w to be representational, we
1242 could get bogus equalities.
1243
1244 A more nuanced treatment might be able to relax this condition
1245 somewhat, by checking if t1 and/or t2 use their bound variables
1246 in nominal ways. If not, having w be representational is OK.
1247
1248
1249 %************************************************************************
1250 %* *
1251 UnivCoProvenance
1252 %* *
1253 %************************************************************************
1254
1255 A UnivCo is a coercion whose proof does not directly express its role
1256 and kind (indeed for some UnivCos, like UnsafeCoerceProv, there /is/
1257 no proof).
1258
1259 The different kinds of UnivCo are described by UnivCoProvenance. Really
1260 each is entirely separate, but they all share the need to represent their
1261 role and kind, which is done in the UnivCo constructor.
1262
1263 -}
1264
1265 -- | For simplicity, we have just one UnivCo that represents a coercion from
1266 -- some type to some other type, with (in general) no restrictions on the
1267 -- type. The UnivCoProvenance specifies more exactly what the coercion really
1268 -- is and why a program should (or shouldn't!) trust the coercion.
1269 -- It is reasonable to consider each constructor of 'UnivCoProvenance'
1270 -- as a totally independent coercion form; their only commonality is
1271 -- that they don't tell you what types they coercion between. (That info
1272 -- is in the 'UnivCo' constructor of 'Coercion'.
1273 data UnivCoProvenance
1274 = UnsafeCoerceProv -- ^ From @unsafeCoerce#@. These are unsound.
1275
1276 | PhantomProv KindCoercion -- ^ See Note [Phantom coercions]. Only in Phantom
1277 -- roled coercions
1278
1279 | ProofIrrelProv KindCoercion -- ^ From the fact that any two coercions are
1280 -- considered equivalent. See Note [ProofIrrelProv].
1281 -- Can be used in Nominal or Representational coercions
1282
1283 | PluginProv String -- ^ From a plugin, which asserts that this coercion
1284 -- is sound. The string is for the use of the plugin.
1285
1286 deriving Data.Data
1287
1288 instance Outputable UnivCoProvenance where
1289 ppr UnsafeCoerceProv = text "(unsafeCoerce#)"
1290 ppr (PhantomProv _) = text "(phantom)"
1291 ppr (ProofIrrelProv _) = text "(proof irrel.)"
1292 ppr (PluginProv str) = parens (text "plugin" <+> brackets (text str))
1293
1294 -- | A coercion to be filled in by the type-checker. See Note [Coercion holes]
1295 data CoercionHole
1296 = CoercionHole { ch_co_var :: CoVar
1297 -- See Note [CoercionHoles and coercion free variables]
1298
1299 , ch_ref :: IORef (Maybe Coercion)
1300 }
1301
1302 coHoleCoVar :: CoercionHole -> CoVar
1303 coHoleCoVar = ch_co_var
1304
1305 setCoHoleCoVar :: CoercionHole -> CoVar -> CoercionHole
1306 setCoHoleCoVar h cv = h { ch_co_var = cv }
1307
1308 instance Data.Data CoercionHole where
1309 -- don't traverse?
1310 toConstr _ = abstractConstr "CoercionHole"
1311 gunfold _ _ = error "gunfold"
1312 dataTypeOf _ = mkNoRepType "CoercionHole"
1313
1314 instance Outputable CoercionHole where
1315 ppr (CoercionHole { ch_co_var = cv }) = braces (ppr cv)
1316
1317
1318 {- Note [Phantom coercions]
1319 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1320 Consider
1321 data T a = T1 | T2
1322 Then we have
1323 T s ~R T t
1324 for any old s,t. The witness for this is (TyConAppCo T Rep co),
1325 where (co :: s ~P t) is a phantom coercion built with PhantomProv.
1326 The role of the UnivCo is always Phantom. The Coercion stored is the
1327 (nominal) kind coercion between the types
1328 kind(s) ~N kind (t)
1329
1330 Note [Coercion holes]
1331 ~~~~~~~~~~~~~~~~~~~~~~~~
1332 During typechecking, constraint solving for type classes works by
1333 - Generate an evidence Id, d7 :: Num a
1334 - Wrap it in a Wanted constraint, [W] d7 :: Num a
1335 - Use the evidence Id where the evidence is needed
1336 - Solve the constraint later
1337 - When solved, add an enclosing let-binding let d7 = .... in ....
1338 which actually binds d7 to the (Num a) evidence
1339
1340 For equality constraints we use a different strategy. See Note [The
1341 equality types story] in TysPrim for background on equality constraints.
1342 - For /boxed/ equality constraints, (t1 ~N t2) and (t1 ~R t2), it's just
1343 like type classes above. (Indeed, boxed equality constraints *are* classes.)
1344 - But for /unboxed/ equality constraints (t1 ~R# t2) and (t1 ~N# t2)
1345 we use a different plan
1346
1347 For unboxed equalities:
1348 - Generate a CoercionHole, a mutable variable just like a unification
1349 variable
1350 - Wrap the CoercionHole in a Wanted constraint; see TcRnTypes.TcEvDest
1351 - Use the CoercionHole in a Coercion, via HoleCo
1352 - Solve the constraint later
1353 - When solved, fill in the CoercionHole by side effect, instead of
1354 doing the let-binding thing
1355
1356 The main reason for all this is that there may be no good place to let-bind
1357 the evidence for unboxed equalities:
1358
1359 - We emit constraints for kind coercions, to be used to cast a
1360 type's kind. These coercions then must be used in types. Because
1361 they might appear in a top-level type, there is no place to bind
1362 these (unlifted) coercions in the usual way.
1363
1364 - A coercion for (forall a. t1) ~ (forall a. t2) will look like
1365 forall a. (coercion for t1~t2)
1366 But the coercion for (t1~t2) may mention 'a', and we don't have
1367 let-bindings within coercions. We could add them, but coercion
1368 holes are easier.
1369
1370 - Moreover, nothing is lost from the lack of let-bindings. For
1371 dicionaries want to achieve sharing to avoid recomoputing the
1372 dictionary. But coercions are entirely erased, so there's little
1373 benefit to sharing. Indeed, even if we had a let-binding, we
1374 always inline types and coercions at every use site and drop the
1375 binding.
1376
1377 Other notes about HoleCo:
1378
1379 * INVARIANT: CoercionHole and HoleCo are used only during type checking,
1380 and should never appear in Core. Just like unification variables; a Type
1381 can contain a TcTyVar, but only during type checking. If, one day, we
1382 use type-level information to separate out forms that can appear during
1383 type-checking vs forms that can appear in core proper, holes in Core will
1384 be ruled out.
1385
1386 * See Note [CoercionHoles and coercion free variables]
1387
1388 * Coercion holes can be compared for equality like other coercions:
1389 by looking at the types coerced.
1390
1391
1392 Note [CoercionHoles and coercion free variables]
1393 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1394 Why does a CoercionHole contain a CoVar, as well as reference to
1395 fill in? Because we want to treat that CoVar as a free variable of
1396 the coercion. See Trac #14584, and Note [What prevents a
1397 constraint from floating] in TcSimplify, item (4):
1398
1399 forall k. [W] co1 :: t1 ~# t2 |> co2
1400 [W] co2 :: k ~# *
1401
1402 Here co2 is a CoercionHole. But we /must/ know that it is free in
1403 co1, because that's all that stops it floating outside the
1404 implication.
1405
1406
1407 Note [ProofIrrelProv]
1408 ~~~~~~~~~~~~~~~~~~~~~
1409 A ProofIrrelProv is a coercion between coercions. For example:
1410
1411 data G a where
1412 MkG :: G Bool
1413
1414 In core, we get
1415
1416 G :: * -> *
1417 MkG :: forall (a :: *). (a ~ Bool) -> G a
1418
1419 Now, consider 'MkG -- that is, MkG used in a type -- and suppose we want
1420 a proof that ('MkG co1 a1) ~ ('MkG co2 a2). This will have to be
1421
1422 TyConAppCo Nominal MkG [co3, co4]
1423 where
1424 co3 :: co1 ~ co2
1425 co4 :: a1 ~ a2
1426
1427 Note that
1428 co1 :: a1 ~ Bool
1429 co2 :: a2 ~ Bool
1430
1431 Here,
1432 co3 = UnivCo (ProofIrrelProv co5) Nominal (CoercionTy co1) (CoercionTy co2)
1433 where
1434 co5 :: (a1 ~ Bool) ~ (a2 ~ Bool)
1435 co5 = TyConAppCo Nominal (~) [<*>, <*>, co4, <Bool>]
1436
1437
1438 %************************************************************************
1439 %* *
1440 Free variables of types and coercions
1441 %* *
1442 %************************************************************************
1443 -}
1444
1445 {- Note [Free variables of types]
1446 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1447 The family of functions tyCoVarsOfType, tyCoVarsOfTypes etc, returns
1448 a VarSet that is closed over the types of its variables. More precisely,
1449 if S = tyCoVarsOfType( t )
1450 and (a:k) is in S
1451 then tyCoVarsOftype( k ) is a subset of S
1452
1453 Example: The tyCoVars of this ((a:* -> k) Int) is {a, k}.
1454
1455 We could /not/ close over the kinds of the variable occurrences, and
1456 instead do so at call sites, but it seems that we always want to do
1457 so, so it's easiest to do it here.
1458 -}
1459
1460
1461 -- | Returns free variables of a type, including kind variables as
1462 -- a non-deterministic set. For type synonyms it does /not/ expand the
1463 -- synonym.
1464 tyCoVarsOfType :: Type -> TyCoVarSet
1465 -- See Note [Free variables of types]
1466 tyCoVarsOfType ty = fvVarSet $ tyCoFVsOfType ty
1467
1468 -- | `tyCoFVsOfType` that returns free variables of a type in a deterministic
1469 -- set. For explanation of why using `VarSet` is not deterministic see
1470 -- Note [Deterministic FV] in FV.
1471 tyCoVarsOfTypeDSet :: Type -> DTyCoVarSet
1472 -- See Note [Free variables of types]
1473 tyCoVarsOfTypeDSet ty = fvDVarSet $ tyCoFVsOfType ty
1474
1475 -- | `tyCoFVsOfType` that returns free variables of a type in deterministic
1476 -- order. For explanation of why using `VarSet` is not deterministic see
1477 -- Note [Deterministic FV] in FV.
1478 tyCoVarsOfTypeList :: Type -> [TyCoVar]
1479 -- See Note [Free variables of types]
1480 tyCoVarsOfTypeList ty = fvVarList $ tyCoFVsOfType ty
1481
1482 -- | The worker for `tyCoFVsOfType` and `tyCoFVsOfTypeList`.
1483 -- The previous implementation used `unionVarSet` which is O(n+m) and can
1484 -- make the function quadratic.
1485 -- It's exported, so that it can be composed with
1486 -- other functions that compute free variables.
1487 -- See Note [FV naming conventions] in FV.
1488 --
1489 -- Eta-expanded because that makes it run faster (apparently)
1490 -- See Note [FV eta expansion] in FV for explanation.
1491 tyCoFVsOfType :: Type -> FV
1492 -- See Note [Free variables of types]
1493 tyCoFVsOfType (TyVarTy v) a b c = (unitFV v `unionFV` tyCoFVsOfType (tyVarKind v)) a b c
1494 tyCoFVsOfType (TyConApp _ tys) a b c = tyCoFVsOfTypes tys a b c
1495 tyCoFVsOfType (LitTy {}) a b c = emptyFV a b c
1496 tyCoFVsOfType (AppTy fun arg) a b c = (tyCoFVsOfType fun `unionFV` tyCoFVsOfType arg) a b c
1497 tyCoFVsOfType (FunTy arg res) a b c = (tyCoFVsOfType arg `unionFV` tyCoFVsOfType res) a b c
1498 tyCoFVsOfType (ForAllTy bndr ty) a b c = tyCoFVsBndr bndr (tyCoFVsOfType ty) a b c
1499 tyCoFVsOfType (CastTy ty co) a b c = (tyCoFVsOfType ty `unionFV` tyCoFVsOfCo co) a b c
1500 tyCoFVsOfType (CoercionTy co) a b c = tyCoFVsOfCo co a b c
1501
1502 tyCoFVsBndr :: TyVarBinder -> FV -> FV
1503 -- Free vars of (forall b. <thing with fvs>)
1504 tyCoFVsBndr (TvBndr tv _) fvs = (delFV tv fvs)
1505 `unionFV` tyCoFVsOfType (tyVarKind tv)
1506
1507 -- | Returns free variables of types, including kind variables as
1508 -- a non-deterministic set. For type synonyms it does /not/ expand the
1509 -- synonym.
1510 tyCoVarsOfTypes :: [Type] -> TyCoVarSet
1511 -- See Note [Free variables of types]
1512 tyCoVarsOfTypes tys = fvVarSet $ tyCoFVsOfTypes tys
1513
1514 -- | Returns free variables of types, including kind variables as
1515 -- a non-deterministic set. For type synonyms it does /not/ expand the
1516 -- synonym.
1517 tyCoVarsOfTypesSet :: TyVarEnv Type -> TyCoVarSet
1518 -- See Note [Free variables of types]
1519 tyCoVarsOfTypesSet tys = fvVarSet $ tyCoFVsOfTypes $ nonDetEltsUFM tys
1520 -- It's OK to use nonDetEltsUFM here because we immediately forget the
1521 -- ordering by returning a set
1522
1523 -- | Returns free variables of types, including kind variables as
1524 -- a deterministic set. For type synonyms it does /not/ expand the
1525 -- synonym.
1526 tyCoVarsOfTypesDSet :: [Type] -> DTyCoVarSet
1527 -- See Note [Free variables of types]
1528 tyCoVarsOfTypesDSet tys = fvDVarSet $ tyCoFVsOfTypes tys
1529
1530 -- | Returns free variables of types, including kind variables as
1531 -- a deterministically ordered list. For type synonyms it does /not/ expand the
1532 -- synonym.
1533 tyCoVarsOfTypesList :: [Type] -> [TyCoVar]
1534 -- See Note [Free variables of types]
1535 tyCoVarsOfTypesList tys = fvVarList $ tyCoFVsOfTypes tys
1536
1537 tyCoFVsOfTypes :: [Type] -> FV
1538 -- See Note [Free variables of types]
1539 tyCoFVsOfTypes (ty:tys) fv_cand in_scope acc = (tyCoFVsOfType ty `unionFV` tyCoFVsOfTypes tys) fv_cand in_scope acc
1540 tyCoFVsOfTypes [] fv_cand in_scope acc = emptyFV fv_cand in_scope acc
1541
1542 tyCoVarsOfCo :: Coercion -> TyCoVarSet
1543 -- See Note [Free variables of types]
1544 tyCoVarsOfCo co = fvVarSet $ tyCoFVsOfCo co
1545
1546 -- | Get a deterministic set of the vars free in a coercion
1547 tyCoVarsOfCoDSet :: Coercion -> DTyCoVarSet
1548 -- See Note [Free variables of types]
1549 tyCoVarsOfCoDSet co = fvDVarSet $ tyCoFVsOfCo co
1550
1551 tyCoVarsOfCoList :: Coercion -> [TyCoVar]
1552 -- See Note [Free variables of types]
1553 tyCoVarsOfCoList co = fvVarList $ tyCoFVsOfCo co
1554
1555 tyCoFVsOfCo :: Coercion -> FV
1556 -- Extracts type and coercion variables from a coercion
1557 -- See Note [Free variables of types]
1558 tyCoFVsOfCo (Refl _ ty) fv_cand in_scope acc = tyCoFVsOfType ty fv_cand in_scope acc
1559 tyCoFVsOfCo (TyConAppCo _ _ cos) fv_cand in_scope acc = tyCoFVsOfCos cos fv_cand in_scope acc
1560 tyCoFVsOfCo (AppCo co arg) fv_cand in_scope acc
1561 = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCo arg) fv_cand in_scope acc
1562 tyCoFVsOfCo (ForAllCo tv kind_co co) fv_cand in_scope acc
1563 = (delFV tv (tyCoFVsOfCo co) `unionFV` tyCoFVsOfCo kind_co) fv_cand in_scope acc
1564 tyCoFVsOfCo (FunCo _ co1 co2) fv_cand in_scope acc
1565 = (tyCoFVsOfCo co1 `unionFV` tyCoFVsOfCo co2) fv_cand in_scope acc
1566 tyCoFVsOfCo (CoVarCo v) fv_cand in_scope acc
1567 = tyCoFVsOfCoVar v fv_cand in_scope acc
1568 tyCoFVsOfCo (HoleCo h) fv_cand in_scope acc
1569 = tyCoFVsOfCoVar (coHoleCoVar h) fv_cand in_scope acc
1570 -- See Note [CoercionHoles and coercion free variables]
1571 tyCoFVsOfCo (AxiomInstCo _ _ cos) fv_cand in_scope acc = tyCoFVsOfCos cos fv_cand in_scope acc
1572 tyCoFVsOfCo (UnivCo p _ t1 t2) fv_cand in_scope acc
1573 = (tyCoFVsOfProv p `unionFV` tyCoFVsOfType t1
1574 `unionFV` tyCoFVsOfType t2) fv_cand in_scope acc
1575 tyCoFVsOfCo (SymCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1576 tyCoFVsOfCo (TransCo co1 co2) fv_cand in_scope acc = (tyCoFVsOfCo co1 `unionFV` tyCoFVsOfCo co2) fv_cand in_scope acc
1577 tyCoFVsOfCo (NthCo _ co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1578 tyCoFVsOfCo (LRCo _ co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1579 tyCoFVsOfCo (InstCo co arg) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCo arg) fv_cand in_scope acc
1580 tyCoFVsOfCo (CoherenceCo c1 c2) fv_cand in_scope acc = (tyCoFVsOfCo c1 `unionFV` tyCoFVsOfCo c2) fv_cand in_scope acc
1581 tyCoFVsOfCo (KindCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1582 tyCoFVsOfCo (SubCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1583 tyCoFVsOfCo (AxiomRuleCo _ cs) fv_cand in_scope acc = tyCoFVsOfCos cs fv_cand in_scope acc
1584
1585 tyCoFVsOfCoVar :: CoVar -> FV
1586 tyCoFVsOfCoVar v fv_cand in_scope acc
1587 = (unitFV v `unionFV` tyCoFVsOfType (varType v)) fv_cand in_scope acc
1588
1589 tyCoVarsOfProv :: UnivCoProvenance -> TyCoVarSet
1590 tyCoVarsOfProv prov = fvVarSet $ tyCoFVsOfProv prov
1591
1592 tyCoFVsOfProv :: UnivCoProvenance -> FV
1593 tyCoFVsOfProv UnsafeCoerceProv fv_cand in_scope acc = emptyFV fv_cand in_scope acc
1594 tyCoFVsOfProv (PhantomProv co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1595 tyCoFVsOfProv (ProofIrrelProv co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc
1596 tyCoFVsOfProv (PluginProv _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc
1597
1598 tyCoVarsOfCos :: [Coercion] -> TyCoVarSet
1599 tyCoVarsOfCos cos = fvVarSet $ tyCoFVsOfCos cos
1600
1601 tyCoVarsOfCosSet :: CoVarEnv Coercion -> TyCoVarSet
1602 tyCoVarsOfCosSet cos = fvVarSet $ tyCoFVsOfCos $ nonDetEltsUFM cos
1603 -- It's OK to use nonDetEltsUFM here because we immediately forget the
1604 -- ordering by returning a set
1605
1606 tyCoFVsOfCos :: [Coercion] -> FV
1607 tyCoFVsOfCos [] fv_cand in_scope acc = emptyFV fv_cand in_scope acc
1608 tyCoFVsOfCos (co:cos) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCos cos) fv_cand in_scope acc
1609
1610 coVarsOfType :: Type -> CoVarSet
1611 coVarsOfType (TyVarTy v) = coVarsOfType (tyVarKind v)
1612 coVarsOfType (TyConApp _ tys) = coVarsOfTypes tys
1613 coVarsOfType (LitTy {}) = emptyVarSet
1614 coVarsOfType (AppTy fun arg) = coVarsOfType fun `unionVarSet` coVarsOfType arg
1615 coVarsOfType (FunTy arg res) = coVarsOfType arg `unionVarSet` coVarsOfType res
1616 coVarsOfType (ForAllTy (TvBndr tv _) ty)
1617 = (coVarsOfType ty `delVarSet` tv)
1618 `unionVarSet` coVarsOfType (tyVarKind tv)
1619 coVarsOfType (CastTy ty co) = coVarsOfType ty `unionVarSet` coVarsOfCo co
1620 coVarsOfType (CoercionTy co) = coVarsOfCo co
1621
1622 coVarsOfTypes :: [Type] -> TyCoVarSet
1623 coVarsOfTypes tys = mapUnionVarSet coVarsOfType tys
1624
1625 coVarsOfCo :: Coercion -> CoVarSet
1626 -- Extract *coercion* variables only. Tiresome to repeat the code, but easy.
1627 coVarsOfCo (Refl _ ty) = coVarsOfType ty
1628 coVarsOfCo (TyConAppCo _ _ args) = coVarsOfCos args
1629 coVarsOfCo (AppCo co arg) = coVarsOfCo co `unionVarSet` coVarsOfCo arg
1630 coVarsOfCo (ForAllCo tv kind_co co)
1631 = coVarsOfCo co `delVarSet` tv `unionVarSet` coVarsOfCo kind_co
1632 coVarsOfCo (FunCo _ co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2
1633 coVarsOfCo (CoVarCo v) = coVarsOfCoVar v
1634 coVarsOfCo (HoleCo h) = coVarsOfCoVar (coHoleCoVar h)
1635 -- See Note [CoercionHoles and coercion free variables]
1636 coVarsOfCo (AxiomInstCo _ _ as) = coVarsOfCos as
1637 coVarsOfCo (UnivCo p _ t1 t2) = coVarsOfProv p `unionVarSet` coVarsOfTypes [t1, t2]
1638 coVarsOfCo (SymCo co) = coVarsOfCo co
1639 coVarsOfCo (TransCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2
1640 coVarsOfCo (NthCo _ co) = coVarsOfCo co
1641 coVarsOfCo (LRCo _ co) = coVarsOfCo co
1642 coVarsOfCo (InstCo co arg) = coVarsOfCo co `unionVarSet` coVarsOfCo arg
1643 coVarsOfCo (CoherenceCo c1 c2) = coVarsOfCos [c1, c2]
1644 coVarsOfCo (KindCo co) = coVarsOfCo co
1645 coVarsOfCo (SubCo co) = coVarsOfCo co
1646 coVarsOfCo (AxiomRuleCo _ cs) = coVarsOfCos cs
1647
1648 coVarsOfCoVar :: CoVar -> CoVarSet
1649 coVarsOfCoVar v = unitVarSet v `unionVarSet` coVarsOfType (varType v)
1650
1651 coVarsOfProv :: UnivCoProvenance -> CoVarSet
1652 coVarsOfProv UnsafeCoerceProv = emptyVarSet
1653 coVarsOfProv (PhantomProv co) = coVarsOfCo co
1654 coVarsOfProv (ProofIrrelProv co) = coVarsOfCo co
1655 coVarsOfProv (PluginProv _) = emptyVarSet
1656
1657 coVarsOfCos :: [Coercion] -> CoVarSet
1658 coVarsOfCos cos = mapUnionVarSet coVarsOfCo cos
1659
1660 -- | Add the kind variables free in the kinds of the tyvars in the given set.
1661 -- Returns a non-deterministic set.
1662 closeOverKinds :: TyVarSet -> TyVarSet
1663 closeOverKinds = fvVarSet . closeOverKindsFV . nonDetEltsUniqSet
1664 -- It's OK to use nonDetEltsUniqSet here because we immediately forget
1665 -- about the ordering by returning a set.
1666
1667 -- | Given a list of tyvars returns a deterministic FV computation that
1668 -- returns the given tyvars with the kind variables free in the kinds of the
1669 -- given tyvars.
1670 closeOverKindsFV :: [TyVar] -> FV
1671 closeOverKindsFV tvs =
1672 mapUnionFV (tyCoFVsOfType . tyVarKind) tvs `unionFV` mkFVs tvs
1673
1674 -- | Add the kind variables free in the kinds of the tyvars in the given set.
1675 -- Returns a deterministically ordered list.
1676 closeOverKindsList :: [TyVar] -> [TyVar]
1677 closeOverKindsList tvs = fvVarList $ closeOverKindsFV tvs
1678
1679 -- | Add the kind variables free in the kinds of the tyvars in the given set.
1680 -- Returns a deterministic set.
1681 closeOverKindsDSet :: DTyVarSet -> DTyVarSet
1682 closeOverKindsDSet = fvDVarSet . closeOverKindsFV . dVarSetElems
1683
1684 -- | Returns the free variables of a 'TyConBinder' that are in injective
1685 -- positions. (See @Note [Kind annotations on TyConApps]@ in "TcSplice" for an
1686 -- explanation of what an injective position is.)
1687 injectiveVarsOfBinder :: TyConBinder -> FV
1688 injectiveVarsOfBinder (TvBndr tv vis) =
1689 case vis of
1690 AnonTCB -> injectiveVarsOfType (tyVarKind tv)
1691 NamedTCB Required -> unitFV tv `unionFV`
1692 injectiveVarsOfType (tyVarKind tv)
1693 NamedTCB _ -> emptyFV
1694
1695 -- | Returns the free variables of a 'Type' that are in injective positions.
1696 -- (See @Note [Kind annotations on TyConApps]@ in "TcSplice" for an explanation
1697 -- of what an injective position is.)
1698 injectiveVarsOfType :: Type -> FV
1699 injectiveVarsOfType = go
1700 where
1701 go ty | Just ty' <- coreView ty
1702 = go ty'
1703 go (TyVarTy v) = unitFV v `unionFV` go (tyVarKind v)
1704 go (AppTy f a) = go f `unionFV` go a
1705 go (FunTy ty1 ty2) = go ty1 `unionFV` go ty2
1706 go (TyConApp tc tys) =
1707 case tyConInjectivityInfo tc of
1708 NotInjective -> emptyFV
1709 Injective inj -> mapUnionFV go $
1710 filterByList (inj ++ repeat True) tys
1711 -- Oversaturated arguments to a tycon are
1712 -- always injective, hence the repeat True
1713 go (ForAllTy tvb ty) = tyCoFVsBndr tvb $ go (tyVarKind (binderVar tvb))
1714 `unionFV` go ty
1715 go LitTy{} = emptyFV
1716 go (CastTy ty _) = go ty
1717 go CoercionTy{} = emptyFV
1718
1719 -- | Returns True if this type has no free variables. Should be the same as
1720 -- isEmptyVarSet . tyCoVarsOfType, but faster in the non-forall case.
1721 noFreeVarsOfType :: Type -> Bool
1722 noFreeVarsOfType (TyVarTy _) = False
1723 noFreeVarsOfType (AppTy t1 t2) = noFreeVarsOfType t1 && noFreeVarsOfType t2
1724 noFreeVarsOfType (TyConApp _ tys) = all noFreeVarsOfType tys
1725 noFreeVarsOfType ty@(ForAllTy {}) = isEmptyVarSet (tyCoVarsOfType ty)
1726 noFreeVarsOfType (FunTy t1 t2) = noFreeVarsOfType t1 && noFreeVarsOfType t2
1727 noFreeVarsOfType (LitTy _) = True
1728 noFreeVarsOfType (CastTy ty co) = noFreeVarsOfType ty && noFreeVarsOfCo co
1729 noFreeVarsOfType (CoercionTy co) = noFreeVarsOfCo co
1730
1731 -- | Returns True if this coercion has no free variables. Should be the same as
1732 -- isEmptyVarSet . tyCoVarsOfCo, but faster in the non-forall case.
1733 noFreeVarsOfCo :: Coercion -> Bool
1734 noFreeVarsOfCo (Refl _ ty) = noFreeVarsOfType ty
1735 noFreeVarsOfCo (TyConAppCo _ _ args) = all noFreeVarsOfCo args
1736 noFreeVarsOfCo (AppCo c1 c2) = noFreeVarsOfCo c1 && noFreeVarsOfCo c2
1737 noFreeVarsOfCo co@(ForAllCo {}) = isEmptyVarSet (tyCoVarsOfCo co)
1738 noFreeVarsOfCo (FunCo _ c1 c2) = noFreeVarsOfCo c1 && noFreeVarsOfCo c2
1739 noFreeVarsOfCo (CoVarCo _) = False
1740 noFreeVarsOfCo (HoleCo {}) = True -- I'm unsure; probably never happens
1741 noFreeVarsOfCo (AxiomInstCo _ _ args) = all noFreeVarsOfCo args
1742 noFreeVarsOfCo (UnivCo p _ t1 t2) = noFreeVarsOfProv p &&
1743 noFreeVarsOfType t1 &&
1744 noFreeVarsOfType t2
1745 noFreeVarsOfCo (SymCo co) = noFreeVarsOfCo co
1746 noFreeVarsOfCo (TransCo co1 co2) = noFreeVarsOfCo co1 && noFreeVarsOfCo co2
1747 noFreeVarsOfCo (NthCo _ co) = noFreeVarsOfCo co
1748 noFreeVarsOfCo (LRCo _ co) = noFreeVarsOfCo co
1749 noFreeVarsOfCo (InstCo co1 co2) = noFreeVarsOfCo co1 && noFreeVarsOfCo co2
1750 noFreeVarsOfCo (CoherenceCo co1 co2) = noFreeVarsOfCo co1 && noFreeVarsOfCo co2
1751 noFreeVarsOfCo (KindCo co) = noFreeVarsOfCo co
1752 noFreeVarsOfCo (SubCo co) = noFreeVarsOfCo co
1753 noFreeVarsOfCo (AxiomRuleCo _ cs) = all noFreeVarsOfCo cs
1754
1755 -- | Returns True if this UnivCoProv has no free variables. Should be the same as
1756 -- isEmptyVarSet . tyCoVarsOfProv, but faster in the non-forall case.
1757 noFreeVarsOfProv :: UnivCoProvenance -> Bool
1758 noFreeVarsOfProv UnsafeCoerceProv = True
1759 noFreeVarsOfProv (PhantomProv co) = noFreeVarsOfCo co
1760 noFreeVarsOfProv (ProofIrrelProv co) = noFreeVarsOfCo co
1761 noFreeVarsOfProv (PluginProv {}) = True
1762
1763 {-
1764 %************************************************************************
1765 %* *
1766 Substitutions
1767 Data type defined here to avoid unnecessary mutual recursion
1768 %* *
1769 %************************************************************************
1770 -}
1771
1772 -- | Type & coercion substitution
1773 --
1774 -- #tcvsubst_invariant#
1775 -- The following invariants must hold of a 'TCvSubst':
1776 --
1777 -- 1. The in-scope set is needed /only/ to
1778 -- guide the generation of fresh uniques
1779 --
1780 -- 2. In particular, the /kind/ of the type variables in
1781 -- the in-scope set is not relevant
1782 --
1783 -- 3. The substitution is only applied ONCE! This is because
1784 -- in general such application will not reach a fixed point.
1785 data TCvSubst
1786 = TCvSubst InScopeSet -- The in-scope type and kind variables
1787 TvSubstEnv -- Substitutes both type and kind variables
1788 CvSubstEnv -- Substitutes coercion variables
1789 -- See Note [Apply Once]
1790 -- and Note [Extending the TvSubstEnv]
1791 -- and Note [Substituting types and coercions]
1792 -- and Note [The substitution invariant]
1793
1794 -- | A substitution of 'Type's for 'TyVar's
1795 -- and 'Kind's for 'KindVar's
1796 type TvSubstEnv = TyVarEnv Type
1797 -- A TvSubstEnv is used both inside a TCvSubst (with the apply-once
1798 -- invariant discussed in Note [Apply Once]), and also independently
1799 -- in the middle of matching, and unification (see Types.Unify)
1800 -- So you have to look at the context to know if it's idempotent or
1801 -- apply-once or whatever
1802
1803 -- | A substitution of 'Coercion's for 'CoVar's
1804 type CvSubstEnv = CoVarEnv Coercion
1805
1806 {-
1807 Note [Apply Once]
1808 ~~~~~~~~~~~~~~~~~
1809 We use TCvSubsts to instantiate things, and we might instantiate
1810 forall a b. ty
1811 \with the types
1812 [a, b], or [b, a].
1813 So the substitution might go [a->b, b->a]. A similar situation arises in Core
1814 when we find a beta redex like
1815 (/\ a /\ b -> e) b a
1816 Then we also end up with a substitution that permutes type variables. Other
1817 variations happen to; for example [a -> (a, b)].
1818
1819 ****************************************************
1820 *** So a TCvSubst must be applied precisely once ***
1821 ****************************************************
1822
1823 A TCvSubst is not idempotent, but, unlike the non-idempotent substitution
1824 we use during unifications, it must not be repeatedly applied.
1825
1826 Note [Extending the TvSubstEnv]
1827 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1828 See #tcvsubst_invariant# for the invariants that must hold.
1829
1830 This invariant allows a short-cut when the subst envs are empty:
1831 if the TvSubstEnv and CvSubstEnv are empty --- i.e. (isEmptyTCvSubst subst)
1832 holds --- then (substTy subst ty) does nothing.
1833
1834 For example, consider:
1835 (/\a. /\b:(a~Int). ...b..) Int
1836 We substitute Int for 'a'. The Unique of 'b' does not change, but
1837 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
1838
1839 This invariant has several crucial consequences:
1840
1841 * In substTyVarBndr, we need extend the TvSubstEnv
1842 - if the unique has changed
1843 - or if the kind has changed
1844
1845 * In substTyVar, we do not need to consult the in-scope set;
1846 the TvSubstEnv is enough
1847
1848 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1849
1850 Note [Substituting types and coercions]
1851 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1852 Types and coercions are mutually recursive, and either may have variables
1853 "belonging" to the other. Thus, every time we wish to substitute in a
1854 type, we may also need to substitute in a coercion, and vice versa.
1855 However, the constructor used to create type variables is distinct from
1856 that of coercion variables, so we carry two VarEnvs in a TCvSubst. Note
1857 that it would be possible to use the CoercionTy constructor to combine
1858 these environments, but that seems like a false economy.
1859
1860 Note that the TvSubstEnv should *never* map a CoVar (built with the Id
1861 constructor) and the CvSubstEnv should *never* map a TyVar. Furthermore,
1862 the range of the TvSubstEnv should *never* include a type headed with
1863 CoercionTy.
1864
1865 Note [The substitution invariant]
1866 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1867 When calling (substTy subst ty) it should be the case that
1868 the in-scope set in the substitution is a superset of both:
1869
1870 * The free vars of the range of the substitution
1871 * The free vars of ty minus the domain of the substitution
1872
1873 If we want to substitute [a -> ty1, b -> ty2] I used to
1874 think it was enough to generate an in-scope set that includes
1875 fv(ty1,ty2). But that's not enough; we really should also take the
1876 free vars of the type we are substituting into! Example:
1877 (forall b. (a,b,x)) [a -> List b]
1878 Then if we use the in-scope set {b}, there is a danger we will rename
1879 the forall'd variable to 'x' by mistake, getting this:
1880 (forall x. (List b, x, x))
1881
1882 Breaking this invariant caused the bug from #11371.
1883 -}
1884
1885 emptyTvSubstEnv :: TvSubstEnv
1886 emptyTvSubstEnv = emptyVarEnv
1887
1888 emptyCvSubstEnv :: CvSubstEnv
1889 emptyCvSubstEnv = emptyVarEnv
1890
1891 composeTCvSubstEnv :: InScopeSet
1892 -> (TvSubstEnv, CvSubstEnv)
1893 -> (TvSubstEnv, CvSubstEnv)
1894 -> (TvSubstEnv, CvSubstEnv)
1895 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1896 -- It assumes that both are idempotent.
1897 -- Typically, @env1@ is the refinement to a base substitution @env2@
1898 composeTCvSubstEnv in_scope (tenv1, cenv1) (tenv2, cenv2)
1899 = ( tenv1 `plusVarEnv` mapVarEnv (substTy subst1) tenv2
1900 , cenv1 `plusVarEnv` mapVarEnv (substCo subst1) cenv2 )
1901 -- First apply env1 to the range of env2
1902 -- Then combine the two, making sure that env1 loses if
1903 -- both bind the same variable; that's why env1 is the
1904 -- *left* argument to plusVarEnv, because the right arg wins
1905 where
1906 subst1 = TCvSubst in_scope tenv1 cenv1
1907
1908 -- | Composes two substitutions, applying the second one provided first,
1909 -- like in function composition.
1910 composeTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst
1911 composeTCvSubst (TCvSubst is1 tenv1 cenv1) (TCvSubst is2 tenv2 cenv2)
1912 = TCvSubst is3 tenv3 cenv3
1913 where
1914 is3 = is1 `unionInScope` is2
1915 (tenv3, cenv3) = composeTCvSubstEnv is3 (tenv1, cenv1) (tenv2, cenv2)
1916
1917 emptyTCvSubst :: TCvSubst
1918 emptyTCvSubst = TCvSubst emptyInScopeSet emptyTvSubstEnv emptyCvSubstEnv
1919
1920 mkEmptyTCvSubst :: InScopeSet -> TCvSubst
1921 mkEmptyTCvSubst is = TCvSubst is emptyTvSubstEnv emptyCvSubstEnv
1922
1923 isEmptyTCvSubst :: TCvSubst -> Bool
1924 -- See Note [Extending the TvSubstEnv]
1925 isEmptyTCvSubst (TCvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv
1926
1927 mkTCvSubst :: InScopeSet -> (TvSubstEnv, CvSubstEnv) -> TCvSubst
1928 mkTCvSubst in_scope (tenv, cenv) = TCvSubst in_scope tenv cenv
1929
1930 mkTvSubst :: InScopeSet -> TvSubstEnv -> TCvSubst
1931 -- ^ Make a TCvSubst with specified tyvar subst and empty covar subst
1932 mkTvSubst in_scope tenv = TCvSubst in_scope tenv emptyCvSubstEnv
1933
1934 getTvSubstEnv :: TCvSubst -> TvSubstEnv
1935 getTvSubstEnv (TCvSubst _ env _) = env
1936
1937 getCvSubstEnv :: TCvSubst -> CvSubstEnv
1938 getCvSubstEnv (TCvSubst _ _ env) = env
1939
1940 getTCvInScope :: TCvSubst -> InScopeSet
1941 getTCvInScope (TCvSubst in_scope _ _) = in_scope
1942
1943 -- | Returns the free variables of the types in the range of a substitution as
1944 -- a non-deterministic set.
1945 getTCvSubstRangeFVs :: TCvSubst -> VarSet
1946 getTCvSubstRangeFVs (TCvSubst _ tenv cenv)
1947 = unionVarSet tenvFVs cenvFVs
1948 where
1949 tenvFVs = tyCoVarsOfTypesSet tenv
1950 cenvFVs = tyCoVarsOfCosSet cenv
1951
1952 isInScope :: Var -> TCvSubst -> Bool
1953 isInScope v (TCvSubst in_scope _ _) = v `elemInScopeSet` in_scope
1954
1955 notElemTCvSubst :: Var -> TCvSubst -> Bool
1956 notElemTCvSubst v (TCvSubst _ tenv cenv)
1957 | isTyVar v
1958 = not (v `elemVarEnv` tenv)
1959 | otherwise
1960 = not (v `elemVarEnv` cenv)
1961
1962 setTvSubstEnv :: TCvSubst -> TvSubstEnv -> TCvSubst
1963 setTvSubstEnv (TCvSubst in_scope _ cenv) tenv = TCvSubst in_scope tenv cenv
1964
1965 setCvSubstEnv :: TCvSubst -> CvSubstEnv -> TCvSubst
1966 setCvSubstEnv (TCvSubst in_scope tenv _) cenv = TCvSubst in_scope tenv cenv
1967
1968 zapTCvSubst :: TCvSubst -> TCvSubst
1969 zapTCvSubst (TCvSubst in_scope _ _) = TCvSubst in_scope emptyVarEnv emptyVarEnv
1970
1971 extendTCvInScope :: TCvSubst -> Var -> TCvSubst
1972 extendTCvInScope (TCvSubst in_scope tenv cenv) var
1973 = TCvSubst (extendInScopeSet in_scope var) tenv cenv
1974
1975 extendTCvInScopeList :: TCvSubst -> [Var] -> TCvSubst
1976 extendTCvInScopeList (TCvSubst in_scope tenv cenv) vars
1977 = TCvSubst (extendInScopeSetList in_scope vars) tenv cenv
1978
1979 extendTCvInScopeSet :: TCvSubst -> VarSet -> TCvSubst
1980 extendTCvInScopeSet (TCvSubst in_scope tenv cenv) vars
1981 = TCvSubst (extendInScopeSetSet in_scope vars) tenv cenv
1982
1983 extendTCvSubst :: TCvSubst -> TyCoVar -> Type -> TCvSubst
1984 extendTCvSubst subst v ty
1985 | isTyVar v
1986 = extendTvSubst subst v ty
1987 | CoercionTy co <- ty
1988 = extendCvSubst subst v co
1989 | otherwise
1990 = pprPanic "extendTCvSubst" (ppr v <+> text "|->" <+> ppr ty)
1991
1992 extendTvSubst :: TCvSubst -> TyVar -> Type -> TCvSubst
1993 extendTvSubst (TCvSubst in_scope tenv cenv) tv ty
1994 = TCvSubst in_scope (extendVarEnv tenv tv ty) cenv
1995
1996 extendTvSubstBinderAndInScope :: TCvSubst -> TyBinder -> Type -> TCvSubst
1997 extendTvSubstBinderAndInScope subst (Named bndr) ty
1998 = extendTvSubstAndInScope subst (binderVar bndr) ty
1999 extendTvSubstBinderAndInScope subst (Anon _) _
2000 = subst
2001
2002 extendTvSubstWithClone :: TCvSubst -> TyVar -> TyVar -> TCvSubst
2003 -- Adds a new tv -> tv mapping, /and/ extends the in-scope set
2004 extendTvSubstWithClone (TCvSubst in_scope tenv cenv) tv tv'
2005 = TCvSubst (extendInScopeSetSet in_scope new_in_scope)
2006 (extendVarEnv tenv tv (mkTyVarTy tv'))
2007 cenv
2008 where
2009 new_in_scope = tyCoVarsOfType (tyVarKind tv') `extendVarSet` tv'
2010
2011 extendCvSubst :: TCvSubst -> CoVar -> Coercion -> TCvSubst
2012 extendCvSubst (TCvSubst in_scope tenv cenv) v co
2013 = TCvSubst in_scope tenv (extendVarEnv cenv v co)
2014
2015 extendCvSubstWithClone :: TCvSubst -> CoVar -> CoVar -> TCvSubst
2016 extendCvSubstWithClone (TCvSubst in_scope tenv cenv) cv cv'
2017 = TCvSubst (extendInScopeSetSet in_scope new_in_scope)
2018 tenv
2019 (extendVarEnv cenv cv (mkCoVarCo cv'))
2020 where
2021 new_in_scope = tyCoVarsOfType (varType cv') `extendVarSet` cv'
2022
2023 extendTvSubstAndInScope :: TCvSubst -> TyVar -> Type -> TCvSubst
2024 -- Also extends the in-scope set
2025 extendTvSubstAndInScope (TCvSubst in_scope tenv cenv) tv ty
2026 = TCvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfType ty)
2027 (extendVarEnv tenv tv ty)
2028 cenv
2029
2030 extendTvSubstList :: TCvSubst -> [Var] -> [Type] -> TCvSubst
2031 extendTvSubstList subst tvs tys
2032 = foldl2 extendTvSubst subst tvs tys
2033
2034 unionTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst
2035 -- Works when the ranges are disjoint
2036 unionTCvSubst (TCvSubst in_scope1 tenv1 cenv1) (TCvSubst in_scope2 tenv2 cenv2)
2037 = ASSERT( not (tenv1 `intersectsVarEnv` tenv2)
2038 && not (cenv1 `intersectsVarEnv` cenv2) )
2039 TCvSubst (in_scope1 `unionInScope` in_scope2)
2040 (tenv1 `plusVarEnv` tenv2)
2041 (cenv1 `plusVarEnv` cenv2)
2042
2043 -- mkTvSubstPrs and zipTvSubst generate the in-scope set from
2044 -- the types given; but it's just a thunk so with a bit of luck
2045 -- it'll never be evaluated
2046
2047 -- | Generates an in-scope set from the free variables in a list of types
2048 -- and a list of coercions
2049 mkTyCoInScopeSet :: [Type] -> [Coercion] -> InScopeSet
2050 mkTyCoInScopeSet tys cos
2051 = mkInScopeSet (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos)
2052
2053 -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming
2054 -- environment. No CoVars, please!
2055 zipTvSubst :: [TyVar] -> [Type] -> TCvSubst
2056 zipTvSubst tvs tys
2057 | debugIsOn
2058 , not (all isTyVar tvs) || neLength tvs tys
2059 = pprTrace "zipTvSubst" (ppr tvs $$ ppr tys) emptyTCvSubst
2060 | otherwise
2061 = mkTvSubst (mkInScopeSet (tyCoVarsOfTypes tys)) tenv
2062 where
2063 tenv = zipTyEnv tvs tys
2064
2065 -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming
2066 -- environment. No TyVars, please!
2067 zipCvSubst :: [CoVar] -> [Coercion] -> TCvSubst
2068 zipCvSubst cvs cos
2069 | debugIsOn
2070 , not (all isCoVar cvs) || neLength cvs cos
2071 = pprTrace "zipCvSubst" (ppr cvs $$ ppr cos) emptyTCvSubst
2072 | otherwise
2073 = TCvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv cenv
2074 where
2075 cenv = zipCoEnv cvs cos
2076
2077 -- | Generates the in-scope set for the 'TCvSubst' from the types in the
2078 -- incoming environment. No CoVars, please!
2079 mkTvSubstPrs :: [(TyVar, Type)] -> TCvSubst
2080 mkTvSubstPrs prs =
2081 ASSERT2( onlyTyVarsAndNoCoercionTy, text "prs" <+> ppr prs )
2082 mkTvSubst in_scope tenv
2083 where tenv = mkVarEnv prs
2084 in_scope = mkInScopeSet $ tyCoVarsOfTypes $ map snd prs
2085 onlyTyVarsAndNoCoercionTy =
2086 and [ isTyVar tv && not (isCoercionTy ty)
2087 | (tv, ty) <- prs ]
2088
2089 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
2090 zipTyEnv tyvars tys
2091 = ASSERT( all (not . isCoercionTy) tys )
2092 mkVarEnv (zipEqual "zipTyEnv" tyvars tys)
2093 -- There used to be a special case for when
2094 -- ty == TyVarTy tv
2095 -- (a not-uncommon case) in which case the substitution was dropped.
2096 -- But the type-tidier changes the print-name of a type variable without
2097 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
2098 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
2099 -- And it happened that t was the type variable of the class. Post-tiding,
2100 -- it got turned into {Foo t2}. The ext-core printer expanded this using
2101 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
2102 -- and so generated a rep type mentioning t not t2.
2103 --
2104 -- Simplest fix is to nuke the "optimisation"
2105
2106 zipCoEnv :: [CoVar] -> [Coercion] -> CvSubstEnv
2107 zipCoEnv cvs cos = mkVarEnv (zipEqual "zipCoEnv" cvs cos)
2108
2109 instance Outputable TCvSubst where
2110 ppr (TCvSubst ins tenv cenv)
2111 = brackets $ sep[ text "TCvSubst",
2112 nest 2 (text "In scope:" <+> ppr ins),
2113 nest 2 (text "Type env:" <+> ppr tenv),
2114 nest 2 (text "Co env:" <+> ppr cenv) ]
2115
2116 {-
2117 %************************************************************************
2118 %* *
2119 Performing type or kind substitutions
2120 %* *
2121 %************************************************************************
2122
2123 Note [Sym and ForAllCo]
2124 ~~~~~~~~~~~~~~~~~~~~~~~
2125 In OptCoercion, we try to push "sym" out to the leaves of a coercion. But,
2126 how do we push sym into a ForAllCo? It's a little ugly.
2127
2128 Here is the typing rule:
2129
2130 h : k1 ~# k2
2131 (tv : k1) |- g : ty1 ~# ty2
2132 ----------------------------
2133 ForAllCo tv h g : (ForAllTy (tv : k1) ty1) ~#
2134 (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h]))
2135
2136 Here is what we want:
2137
2138 ForAllCo tv h' g' : (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h])) ~#
2139 (ForAllTy (tv : k1) ty1)
2140
2141
2142 Because the kinds of the type variables to the right of the colon are the kinds
2143 coerced by h', we know (h' : k2 ~# k1). Thus, (h' = sym h).
2144
2145 Now, we can rewrite ty1 to be (ty1[tv |-> tv |> sym h' |> h']). We thus want
2146
2147 ForAllCo tv h' g' :
2148 (ForAllTy (tv : k2) (ty2[tv |-> tv |> h'])) ~#
2149 (ForAllTy (tv : k1) (ty1[tv |-> tv |> h'][tv |-> tv |> sym h']))
2150
2151 We thus see that we want
2152
2153 g' : ty2[tv |-> tv |> h'] ~# ty1[tv |-> tv |> h']
2154
2155 and thus g' = sym (g[tv |-> tv |> h']).
2156
2157 Putting it all together, we get this:
2158
2159 sym (ForAllCo tv h g)
2160 ==>
2161 ForAllCo tv (sym h) (sym g[tv |-> tv |> sym h])
2162
2163 -}
2164
2165 -- | Type substitution, see 'zipTvSubst'
2166 substTyWith :: HasCallStack => [TyVar] -> [Type] -> Type -> Type
2167 -- Works only if the domain of the substitution is a
2168 -- superset of the type being substituted into
2169 substTyWith tvs tys = ASSERT( tvs `equalLength` tys )
2170 substTy (zipTvSubst tvs tys)
2171
2172 -- | Type substitution, see 'zipTvSubst'. Disables sanity checks.
2173 -- The problems that the sanity checks in substTy catch are described in
2174 -- Note [The substitution invariant].
2175 -- The goal of #11371 is to migrate all the calls of substTyUnchecked to
2176 -- substTy and remove this function. Please don't use in new code.
2177 substTyWithUnchecked :: [TyVar] -> [Type] -> Type -> Type
2178 substTyWithUnchecked tvs tys
2179 = ASSERT( tvs `equalLength` tys )
2180 substTyUnchecked (zipTvSubst tvs tys)
2181
2182 -- | Substitute tyvars within a type using a known 'InScopeSet'.
2183 -- Pre-condition: the 'in_scope' set should satisfy Note [The substitution
2184 -- invariant]; specifically it should include the free vars of 'tys',
2185 -- and of 'ty' minus the domain of the subst.
2186 substTyWithInScope :: InScopeSet -> [TyVar] -> [Type] -> Type -> Type
2187 substTyWithInScope in_scope tvs tys ty =
2188 ASSERT( tvs `equalLength` tys )
2189 substTy (mkTvSubst in_scope tenv) ty
2190 where tenv = zipTyEnv tvs tys
2191
2192 -- | Coercion substitution, see 'zipTvSubst'
2193 substCoWith :: HasCallStack => [TyVar] -> [Type] -> Coercion -> Coercion
2194 substCoWith tvs tys = ASSERT( tvs `equalLength` tys )
2195 substCo (zipTvSubst tvs tys)
2196
2197 -- | Coercion substitution, see 'zipTvSubst'. Disables sanity checks.
2198 -- The problems that the sanity checks in substCo catch are described in
2199 -- Note [The substitution invariant].
2200 -- The goal of #11371 is to migrate all the calls of substCoUnchecked to
2201 -- substCo and remove this function. Please don't use in new code.
2202 substCoWithUnchecked :: [TyVar] -> [Type] -> Coercion -> Coercion
2203 substCoWithUnchecked tvs tys
2204 = ASSERT( tvs `equalLength` tys )
2205 substCoUnchecked (zipTvSubst tvs tys)
2206
2207
2208
2209 -- | Substitute covars within a type
2210 substTyWithCoVars :: [CoVar] -> [Coercion] -> Type -> Type
2211 substTyWithCoVars cvs cos = substTy (zipCvSubst cvs cos)
2212
2213 -- | Type substitution, see 'zipTvSubst'
2214 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
2215 substTysWith tvs tys = ASSERT( tvs `equalLength` tys )
2216 substTys (zipTvSubst tvs tys)
2217
2218 -- | Type substitution, see 'zipTvSubst'
2219 substTysWithCoVars :: [CoVar] -> [Coercion] -> [Type] -> [Type]
2220 substTysWithCoVars cvs cos = ASSERT( cvs `equalLength` cos )
2221 substTys (zipCvSubst cvs cos)
2222
2223 -- | Substitute within a 'Type' after adding the free variables of the type
2224 -- to the in-scope set. This is useful for the case when the free variables
2225 -- aren't already in the in-scope set or easily available.
2226 -- See also Note [The substitution invariant].
2227 substTyAddInScope :: TCvSubst -> Type -> Type
2228 substTyAddInScope subst ty =
2229 substTy (extendTCvInScopeSet subst $ tyCoVarsOfType ty) ty
2230
2231 -- | When calling `substTy` it should be the case that the in-scope set in
2232 -- the substitution is a superset of the free vars of the range of the
2233 -- substitution.
2234 -- See also Note [The substitution invariant].
2235 isValidTCvSubst :: TCvSubst -> Bool
2236 isValidTCvSubst (TCvSubst in_scope tenv cenv) =
2237 (tenvFVs `varSetInScope` in_scope) &&
2238 (cenvFVs `varSetInScope` in_scope)
2239 where
2240 tenvFVs = tyCoVarsOfTypesSet tenv
2241 cenvFVs = tyCoVarsOfCosSet cenv
2242
2243 -- | This checks if the substitution satisfies the invariant from
2244 -- Note [The substitution invariant].
2245 checkValidSubst :: HasCallStack => TCvSubst -> [Type] -> [Coercion] -> a -> a
2246 checkValidSubst subst@(TCvSubst in_scope tenv cenv) tys cos a
2247 -- TODO (RAE): Change back to ASSERT
2248 = WARN( not (isValidTCvSubst subst),
2249 text "in_scope" <+> ppr in_scope $$
2250 text "tenv" <+> ppr tenv $$
2251 text "tenvFVs"
2252 <+> ppr (tyCoVarsOfTypesSet tenv) $$
2253 text "cenv" <+> ppr cenv $$
2254 text "cenvFVs"
2255 <+> ppr (tyCoVarsOfCosSet cenv) $$
2256 text "tys" <+> ppr tys $$
2257 text "cos" <+> ppr cos )
2258 WARN( not tysCosFVsInScope,
2259 text "in_scope" <+> ppr in_scope $$
2260 text "tenv" <+> ppr tenv $$
2261 text "cenv" <+> ppr cenv $$
2262 text "tys" <+> ppr tys $$
2263 text "cos" <+> ppr cos $$
2264 text "needInScope" <+> ppr needInScope )
2265 a
2266 where
2267 substDomain = nonDetKeysUFM tenv ++ nonDetKeysUFM cenv
2268 -- It's OK to use nonDetKeysUFM here, because we only use this list to
2269 -- remove some elements from a set
2270 needInScope = (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos)
2271 `delListFromUniqSet_Directly` substDomain
2272 tysCosFVsInScope = needInScope `varSetInScope` in_scope
2273
2274
2275 -- | Substitute within a 'Type'
2276 -- The substitution has to satisfy the invariants described in
2277 -- Note [The substitution invariant].
2278 substTy :: HasCallStack => TCvSubst -> Type -> Type
2279 substTy subst ty
2280 | isEmptyTCvSubst subst = ty
2281 | otherwise = checkValidSubst subst [ty] [] $
2282 subst_ty subst ty
2283
2284 -- | Substitute within a 'Type' disabling the sanity checks.
2285 -- The problems that the sanity checks in substTy catch are described in
2286 -- Note [The substitution invariant].
2287 -- The goal of #11371 is to migrate all the calls of substTyUnchecked to
2288 -- substTy and remove this function. Please don't use in new code.
2289 substTyUnchecked :: TCvSubst -> Type -> Type
2290 substTyUnchecked subst ty
2291 | isEmptyTCvSubst subst = ty
2292 | otherwise = subst_ty subst ty
2293
2294 -- | Substitute within several 'Type's
2295 -- The substitution has to satisfy the invariants described in
2296 -- Note [The substitution invariant].
2297 substTys :: HasCallStack => TCvSubst -> [Type] -> [Type]
2298 substTys subst tys
2299 | isEmptyTCvSubst subst = tys
2300 | otherwise = checkValidSubst subst tys [] $ map (subst_ty subst) tys
2301
2302 -- | Substitute within several 'Type's disabling the sanity checks.
2303 -- The problems that the sanity checks in substTys catch are described in
2304 -- Note [The substitution invariant].
2305 -- The goal of #11371 is to migrate all the calls of substTysUnchecked to
2306 -- substTys and remove this function. Please don't use in new code.
2307 substTysUnchecked :: TCvSubst -> [Type] -> [Type]
2308 substTysUnchecked subst tys
2309 | isEmptyTCvSubst subst = tys
2310 | otherwise = map (subst_ty subst) tys
2311
2312 -- | Substitute within a 'ThetaType'
2313 -- The substitution has to satisfy the invariants described in
2314 -- Note [The substitution invariant].
2315 substTheta :: HasCallStack => TCvSubst -> ThetaType -> ThetaType
2316 substTheta = substTys
2317
2318 -- | Substitute within a 'ThetaType' disabling the sanity checks.
2319 -- The problems that the sanity checks in substTys catch are described in
2320 -- Note [The substitution invariant].
2321 -- The goal of #11371 is to migrate all the calls of substThetaUnchecked to
2322 -- substTheta and remove this function. Please don't use in new code.
2323 substThetaUnchecked :: TCvSubst -> ThetaType -> ThetaType
2324 substThetaUnchecked = substTysUnchecked
2325
2326
2327 subst_ty :: TCvSubst -> Type -> Type
2328 -- subst_ty is the main workhorse for type substitution
2329 --
2330 -- Note that the in_scope set is poked only if we hit a forall
2331 -- so it may often never be fully computed
2332 subst_ty subst ty
2333 = go ty
2334 where
2335 go (TyVarTy tv) = substTyVar subst tv
2336 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
2337 -- The mkAppTy smart constructor is important
2338 -- we might be replacing (a Int), represented with App
2339 -- by [Int], represented with TyConApp
2340 go (TyConApp tc tys) = let args = map go tys
2341 in args `seqList` TyConApp tc args
2342 go (FunTy arg res) = (FunTy $! go arg) $! go res
2343 go (ForAllTy (TvBndr tv vis) ty)
2344 = case substTyVarBndrUnchecked subst tv of
2345 (subst', tv') ->
2346 (ForAllTy $! ((TvBndr $! tv') vis)) $!
2347 (subst_ty subst' ty)
2348 go (LitTy n) = LitTy $! n
2349 go (CastTy ty co) = (mkCastTy $! (go ty)) $! (subst_co subst co)
2350 go (CoercionTy co) = CoercionTy $! (subst_co subst co)
2351
2352 substTyVar :: TCvSubst -> TyVar -> Type
2353 substTyVar (TCvSubst _ tenv _) tv
2354 = ASSERT( isTyVar tv )
2355 case lookupVarEnv tenv tv of
2356 Just ty -> ty
2357 Nothing -> TyVarTy tv
2358
2359 substTyVars :: TCvSubst -> [TyVar] -> [Type]
2360 substTyVars subst = map $ substTyVar subst
2361
2362 lookupTyVar :: TCvSubst -> TyVar -> Maybe Type
2363 -- See Note [Extending the TCvSubst]
2364 lookupTyVar (TCvSubst _ tenv _) tv
2365 = ASSERT( isTyVar tv )
2366 lookupVarEnv tenv tv
2367
2368 -- | Substitute within a 'Coercion'
2369 -- The substitution has to satisfy the invariants described in
2370 -- Note [The substitution invariant].
2371 substCo :: HasCallStack => TCvSubst -> Coercion -> Coercion
2372 substCo subst co
2373 | isEmptyTCvSubst subst = co
2374 | otherwise = checkValidSubst subst [] [co] $ subst_co subst co
2375
2376 -- | Substitute within a 'Coercion' disabling sanity checks.
2377 -- The problems that the sanity checks in substCo catch are described in
2378 -- Note [The substitution invariant].
2379 -- The goal of #11371 is to migrate all the calls of substCoUnchecked to
2380 -- substCo and remove this function. Please don't use in new code.
2381 substCoUnchecked :: TCvSubst -> Coercion -> Coercion
2382 substCoUnchecked subst co
2383 | isEmptyTCvSubst subst = co
2384 | otherwise = subst_co subst co
2385
2386 -- | Substitute within several 'Coercion's
2387 -- The substitution has to satisfy the invariants described in
2388 -- Note [The substitution invariant].
2389 substCos :: HasCallStack => TCvSubst -> [Coercion] -> [Coercion]
2390 substCos subst cos
2391 | isEmptyTCvSubst subst = cos
2392 | otherwise = checkValidSubst subst [] cos $ map (subst_co subst) cos
2393
2394 subst_co :: TCvSubst -> Coercion -> Coercion
2395 subst_co subst co
2396 = go co
2397 where
2398 go_ty :: Type -> Type
2399 go_ty = subst_ty subst
2400
2401 go :: Coercion -> Coercion
2402 go (Refl r ty) = mkReflCo r $! go_ty ty
2403 go (TyConAppCo r tc args)= let args' = map go args
2404 in args' `seqList` mkTyConAppCo r tc args'
2405 go (AppCo co arg) = (mkAppCo $! go co) $! go arg
2406 go (ForAllCo tv kind_co co)
2407 = case substForAllCoBndrUnchecked subst tv kind_co of { (subst', tv', kind_co') ->
2408 ((mkForAllCo $! tv') $! kind_co') $! subst_co subst' co }
2409 go (FunCo r co1 co2) = (mkFunCo r $! go co1) $! go co2
2410 go (CoVarCo cv) = substCoVar subst cv
2411 go (AxiomInstCo con ind cos) = mkAxiomInstCo con ind $! map go cos
2412 go (UnivCo p r t1 t2) = (((mkUnivCo $! go_prov p) $! r) $!
2413 (go_ty t1)) $! (go_ty t2)
2414 go (SymCo co) = mkSymCo $! (go co)
2415 go (TransCo co1 co2) = (mkTransCo $! (go co1)) $! (go co2)
2416 go (NthCo d co) = mkNthCo d $! (go co)
2417 go (LRCo lr co) = mkLRCo lr $! (go co)
2418 go (InstCo co arg) = (mkInstCo $! (go co)) $! go arg
2419 go (CoherenceCo co1 co2) = (mkCoherenceCo $! (go co1)) $! (go co2)
2420 go (KindCo co) = mkKindCo $! (go co)
2421 go (SubCo co) = mkSubCo $! (go co)
2422 go (AxiomRuleCo c cs) = let cs1 = map go cs
2423 in cs1 `seqList` AxiomRuleCo c cs1
2424 go (HoleCo h) = HoleCo h
2425 -- NB: this last case is a little suspicious, but we need it. Originally,
2426 -- there was a panic here, but it triggered from deeplySkolemise. Because
2427 -- we only skolemise tyvars that are manually bound, this operation makes
2428 -- sense, even over a coercion with holes. We don't need to substitute
2429 -- in the type of the coHoleCoVar because it wouldn't makes sense to have
2430 -- forall a. ....(ty |> {hole_cv::a})....
2431
2432 go_prov UnsafeCoerceProv = UnsafeCoerceProv
2433 go_prov (PhantomProv kco) = PhantomProv (go kco)
2434 go_prov (ProofIrrelProv kco) = ProofIrrelProv (go kco)
2435 go_prov p@(PluginProv _) = p
2436
2437 substForAllCoBndr :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion)
2438 substForAllCoBndr subst
2439 = substForAllCoBndrCallback False (substCo subst) subst
2440
2441 -- | Like 'substForAllCoBndr', but disables sanity checks.
2442 -- The problems that the sanity checks in substCo catch are described in
2443 -- Note [The substitution invariant].
2444 -- The goal of #11371 is to migrate all the calls of substCoUnchecked to
2445 -- substCo and remove this function. Please don't use in new code.
2446 substForAllCoBndrUnchecked :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion)
2447 substForAllCoBndrUnchecked subst
2448 = substForAllCoBndrCallback False (substCoUnchecked subst) subst
2449
2450 -- See Note [Sym and ForAllCo]
2451 substForAllCoBndrCallback :: Bool -- apply sym to binder?
2452 -> (Coercion -> Coercion) -- transformation to kind co
2453 -> TCvSubst -> TyVar -> Coercion
2454 -> (TCvSubst, TyVar, Coercion)
2455 substForAllCoBndrCallback sym sco (TCvSubst in_scope tenv cenv)
2456 old_var old_kind_co
2457 = ( TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv
2458 , new_var, new_kind_co )
2459 where
2460 new_env | no_change && not sym = delVarEnv tenv old_var
2461 | sym = extendVarEnv tenv old_var $
2462 TyVarTy new_var `CastTy` new_kind_co
2463 | otherwise = extendVarEnv tenv old_var (TyVarTy new_var)
2464
2465 no_kind_change = noFreeVarsOfCo old_kind_co
2466 no_change = no_kind_change && (new_var == old_var)
2467
2468 new_kind_co | no_kind_change = old_kind_co
2469 | otherwise = sco old_kind_co
2470
2471 Pair new_ki1 _ = coercionKind new_kind_co
2472
2473 new_var = uniqAway in_scope (setTyVarKind old_var new_ki1)
2474
2475 substCoVar :: TCvSubst -> CoVar -> Coercion
2476 substCoVar (TCvSubst _ _ cenv) cv
2477 = case lookupVarEnv cenv cv of
2478 Just co -> co
2479 Nothing -> CoVarCo cv
2480
2481 substCoVars :: TCvSubst -> [CoVar] -> [Coercion]
2482 substCoVars subst cvs = map (substCoVar subst) cvs
2483
2484 lookupCoVar :: TCvSubst -> Var -> Maybe Coercion
2485 lookupCoVar (TCvSubst _ _ cenv) v = lookupVarEnv cenv v
2486
2487 substTyVarBndr :: HasCallStack => TCvSubst -> TyVar -> (TCvSubst, TyVar)
2488 substTyVarBndr = substTyVarBndrCallback substTy
2489
2490 -- | Like 'substTyVarBndr' but disables sanity checks.
2491 -- The problems that the sanity checks in substTy catch are described in
2492 -- Note [The substitution invariant].
2493 -- The goal of #11371 is to migrate all the calls of substTyUnchecked to
2494 -- substTy and remove this function. Please don't use in new code.
2495 substTyVarBndrUnchecked :: TCvSubst -> TyVar -> (TCvSubst, TyVar)
2496 substTyVarBndrUnchecked = substTyVarBndrCallback substTyUnchecked
2497
2498 -- | Substitute a tyvar in a binding position, returning an
2499 -- extended subst and a new tyvar.
2500 substTyVarBndrCallback :: (TCvSubst -> Type -> Type) -- ^ the subst function
2501 -> TCvSubst -> TyVar -> (TCvSubst, TyVar)
2502 substTyVarBndrCallback subst_fn subst@(TCvSubst in_scope tenv cenv) old_var
2503 = ASSERT2( _no_capture, pprTyVar old_var $$ pprTyVar new_var $$ ppr subst )
2504 ASSERT( isTyVar old_var )
2505 (TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv, new_var)
2506 where
2507 new_env | no_change = delVarEnv tenv old_var
2508 | otherwise = extendVarEnv tenv old_var (TyVarTy new_var)
2509
2510 _no_capture = not (new_var `elemVarSet` tyCoVarsOfTypesSet tenv)
2511 -- Assertion check that we are not capturing something in the substitution
2512
2513 old_ki = tyVarKind old_var
2514 no_kind_change = noFreeVarsOfType old_ki -- verify that kind is closed
2515 no_change = no_kind_change && (new_var == old_var)
2516 -- no_change means that the new_var is identical in
2517 -- all respects to the old_var (same unique, same kind)
2518 -- See Note [Extending the TCvSubst]
2519 --
2520 -- In that case we don't need to extend the substitution
2521 -- to map old to new. But instead we must zap any
2522 -- current substitution for the variable. For example:
2523 -- (\x.e) with id_subst = [x |-> e']
2524 -- Here we must simply zap the substitution for x
2525
2526 new_var | no_kind_change = uniqAway in_scope old_var
2527 | otherwise = uniqAway in_scope $
2528 setTyVarKind old_var (subst_fn subst old_ki)
2529 -- The uniqAway part makes sure the new variable is not already in scope
2530
2531 substCoVarBndr :: TCvSubst -> CoVar -> (TCvSubst, CoVar)
2532 substCoVarBndr subst@(TCvSubst in_scope tenv cenv) old_var
2533 = ASSERT( isCoVar old_var )
2534 (TCvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var)
2535 where
2536 new_co = mkCoVarCo new_var
2537 no_kind_change = all noFreeVarsOfType [t1, t2]
2538 no_change = new_var == old_var && no_kind_change
2539
2540 new_cenv | no_change = delVarEnv cenv old_var
2541 | otherwise = extendVarEnv cenv old_var new_co
2542
2543 new_var = uniqAway in_scope subst_old_var
2544 subst_old_var = mkCoVar (varName old_var) new_var_type
2545
2546 (_, _, t1, t2, role) = coVarKindsTypesRole old_var
2547 t1' = substTy subst t1
2548 t2' = substTy subst t2
2549 new_var_type = mkCoercionType role t1' t2'
2550 -- It's important to do the substitution for coercions,
2551 -- because they can have free type variables
2552
2553 cloneTyVarBndr :: TCvSubst -> TyVar -> Unique -> (TCvSubst, TyVar)
2554 cloneTyVarBndr subst@(TCvSubst in_scope tv_env cv_env) tv uniq
2555 = ASSERT2( isTyVar tv, ppr tv ) -- I think it's only called on TyVars
2556 (TCvSubst (extendInScopeSet in_scope tv')
2557 (extendVarEnv tv_env tv (mkTyVarTy tv')) cv_env, tv')
2558 where
2559 old_ki = tyVarKind tv
2560 no_kind_change = noFreeVarsOfType old_ki -- verify that kind is closed
2561
2562 tv1 | no_kind_change = tv
2563 | otherwise = setTyVarKind tv (substTy subst old_ki)
2564
2565 tv' = setVarUnique tv1 uniq
2566
2567 cloneTyVarBndrs :: TCvSubst -> [TyVar] -> UniqSupply -> (TCvSubst, [TyVar])
2568 cloneTyVarBndrs subst [] _usupply = (subst, [])
2569 cloneTyVarBndrs subst (t:ts) usupply = (subst'', tv:tvs)
2570 where
2571 (uniq, usupply') = takeUniqFromSupply usupply
2572 (subst' , tv ) = cloneTyVarBndr subst t uniq
2573 (subst'', tvs) = cloneTyVarBndrs subst' ts usupply'
2574
2575 {-
2576 %************************************************************************
2577 %* *
2578 Pretty-printing types
2579
2580 Defined very early because of debug printing in assertions
2581 %* *
2582 %************************************************************************
2583
2584 @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
2585 defined to use this. @pprParendType@ is the same, except it puts
2586 parens around the type, except for the atomic cases. @pprParendType@
2587 works just by setting the initial context precedence very high.
2588
2589 See Note [Precedence in types] in BasicTypes.
2590 -}
2591
2592 ------------------
2593
2594 pprType, pprParendType :: Type -> SDoc
2595 pprType = pprPrecType TopPrec
2596 pprParendType = pprPrecType TyConPrec
2597
2598 pprPrecType :: TyPrec -> Type -> SDoc
2599 pprPrecType prec ty
2600 = getPprStyle $ \sty ->
2601 if debugStyle sty -- Use pprDebugType when in
2602 then debug_ppr_ty prec ty -- when in debug-style
2603 else pprPrecIfaceType prec (tidyToIfaceTypeSty ty sty)
2604
2605 pprTyLit :: TyLit -> SDoc
2606 pprTyLit = pprIfaceTyLit . toIfaceTyLit
2607
2608 pprKind, pprParendKind :: Kind -> SDoc
2609 pprKind = pprType
2610 pprParendKind = pprParendType
2611
2612 tidyToIfaceTypeSty :: Type -> PprStyle -> IfaceType
2613 tidyToIfaceTypeSty ty sty
2614 | userStyle sty = tidyToIfaceType ty
2615 | otherwise = toIfaceTypeX (tyCoVarsOfType ty) ty
2616 -- in latter case, don't tidy, as we'll be printing uniques.
2617
2618 tidyToIfaceType :: Type -> IfaceType
2619 -- It's vital to tidy before converting to an IfaceType
2620 -- or nested binders will become indistinguishable!
2621 --
2622 -- Also for the free type variables, tell toIfaceTypeX to
2623 -- leave them as IfaceFreeTyVar. This is super-important
2624 -- for debug printing.
2625 tidyToIfaceType ty = toIfaceTypeX (mkVarSet free_tcvs) (tidyType env ty)
2626 where
2627 env = tidyFreeTyCoVars emptyTidyEnv free_tcvs
2628 free_tcvs = tyCoVarsOfTypeWellScoped ty
2629
2630 ------------
2631 pprCo, pprParendCo :: Coercion -> SDoc
2632 pprCo co = getPprStyle $ \ sty -> pprIfaceCoercion (tidyToIfaceCoSty co sty)
2633 pprParendCo co = getPprStyle $ \ sty -> pprParendIfaceCoercion (tidyToIfaceCoSty co sty)
2634
2635 tidyToIfaceCoSty :: Coercion -> PprStyle -> IfaceCoercion
2636 tidyToIfaceCoSty co sty
2637 | userStyle sty = tidyToIfaceCo co
2638 | otherwise = toIfaceCoercionX (tyCoVarsOfCo co) co
2639 -- in latter case, don't tidy, as we'll be printing uniques.
2640
2641 tidyToIfaceCo :: Coercion -> IfaceCoercion
2642 -- It's vital to tidy before converting to an IfaceType
2643 -- or nested binders will become indistinguishable!
2644 --
2645 -- Also for the free type variables, tell toIfaceCoercionX to
2646 -- leave them as IfaceFreeCoVar. This is super-important
2647 -- for debug printing.
2648 tidyToIfaceCo co = toIfaceCoercionX (mkVarSet free_tcvs) (tidyCo env co)
2649 where
2650 env = tidyFreeTyCoVars emptyTidyEnv free_tcvs
2651 free_tcvs = toposortTyVars $ tyCoVarsOfCoList co
2652
2653 ------------
2654 pprClassPred :: Class -> [Type] -> SDoc
2655 pprClassPred clas tys = pprTypeApp (classTyCon clas) tys
2656
2657 ------------
2658 pprTheta :: ThetaType -> SDoc
2659 pprTheta = pprIfaceContext TopPrec . map tidyToIfaceType
2660
2661 pprParendTheta :: ThetaType -> SDoc
2662 pprParendTheta = pprIfaceContext TyConPrec . map tidyToIfaceType
2663
2664 pprThetaArrowTy :: ThetaType -> SDoc
2665 pprThetaArrowTy = pprIfaceContextArr . map tidyToIfaceType
2666
2667 ------------------
2668 instance Outputable Type where
2669 ppr ty = pprType ty
2670
2671 instance Outputable TyLit where
2672 ppr = pprTyLit
2673
2674 ------------------
2675 pprSigmaType :: Type -> SDoc
2676 pprSigmaType = pprIfaceSigmaType ShowForAllWhen . tidyToIfaceType
2677
2678 pprForAll :: [TyVarBinder] -> SDoc
2679 pprForAll tvs = pprIfaceForAll (map toIfaceForAllBndr tvs)
2680
2681 -- | Print a user-level forall; see Note [When to print foralls]
2682 pprUserForAll :: [TyVarBinder] -> SDoc
2683 pprUserForAll = pprUserIfaceForAll . map toIfaceForAllBndr
2684
2685 pprTvBndrs :: [TyVarBinder] -> SDoc
2686 pprTvBndrs tvs = sep (map pprTvBndr tvs)
2687
2688 pprTvBndr :: TyVarBinder -> SDoc
2689 pprTvBndr = pprTyVar . binderVar
2690
2691 pprTyVars :: [TyVar] -> SDoc
2692 pprTyVars tvs = sep (map pprTyVar tvs)
2693
2694 pprTyVar :: TyVar -> SDoc
2695 -- Print a type variable binder with its kind (but not if *)
2696 -- Here we do not go via IfaceType, because the duplication with
2697 -- pprIfaceTvBndr is minimal, and the loss of uniques etc in
2698 -- debug printing is disastrous
2699 pprTyVar tv
2700 | isLiftedTypeKind kind = ppr tv
2701 | otherwise = parens (ppr tv <+> dcolon <+> ppr kind)
2702 where
2703 kind = tyVarKind tv
2704
2705 instance Outputable TyBinder where
2706 ppr (Anon ty) = text "[anon]" <+> ppr ty
2707 ppr (Named (TvBndr v Required)) = ppr v
2708 ppr (Named (TvBndr v Specified)) = char '@' <> ppr v
2709 ppr (Named (TvBndr v Inferred)) = braces (ppr v)
2710
2711 -----------------
2712 instance Outputable Coercion where -- defined here to avoid orphans
2713 ppr = pprCo
2714
2715 debugPprType :: Type -> SDoc
2716 -- ^ debugPprType is a simple pretty printer that prints a type
2717 -- without going through IfaceType. It does not format as prettily
2718 -- as the normal route, but it's much more direct, and that can
2719 -- be useful for debugging. E.g. with -dppr-debug it prints the
2720 -- kind on type-variable /occurrences/ which the normal route
2721 -- fundamentally cannot do.
2722 debugPprType ty = debug_ppr_ty TopPrec ty
2723
2724 debug_ppr_ty :: TyPrec -> Type -> SDoc
2725 debug_ppr_ty _ (LitTy l)
2726 = ppr l
2727
2728 debug_ppr_ty _ (TyVarTy tv)
2729 = ppr tv -- With -dppr-debug we get (tv :: kind)
2730
2731 debug_ppr_ty prec (FunTy arg res)
2732 = maybeParen prec FunPrec $
2733 sep [debug_ppr_ty FunPrec arg, arrow <+> debug_ppr_ty prec res]
2734
2735 debug_ppr_ty prec (TyConApp tc tys)
2736 | null tys = ppr tc
2737 | otherwise = maybeParen prec TyConPrec $
2738 hang (ppr tc) 2 (sep (map (debug_ppr_ty TyConPrec) tys))
2739
2740 debug_ppr_ty prec (AppTy t1 t2)
2741 = hang (debug_ppr_ty prec t1)
2742 2 (debug_ppr_ty TyConPrec t2)
2743
2744 debug_ppr_ty prec (CastTy ty co)
2745 = maybeParen prec TopPrec $
2746 hang (debug_ppr_ty TopPrec ty)
2747 2 (text "|>" <+> ppr co)
2748
2749 debug_ppr_ty _ (CoercionTy co)
2750 = parens (text "CO" <+> ppr co)
2751
2752 debug_ppr_ty prec ty@(ForAllTy {})
2753 | (tvs, body) <- split ty
2754 = maybeParen prec FunPrec $
2755 hang (text "forall" <+> fsep (map ppr tvs) <> dot)
2756 -- The (map ppr tvs) will print kind-annotated
2757 -- tvs, because we are (usually) in debug-style
2758 2 (ppr body)
2759 where
2760 split ty | ForAllTy tv ty' <- ty
2761 , (tvs, body) <- split ty'
2762 = (tv:tvs, body)
2763 | otherwise
2764 = ([], ty)
2765
2766 {-
2767 Note [When to print foralls]
2768 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2769 Mostly we want to print top-level foralls when (and only when) the user specifies
2770 -fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses
2771 too much information; see Trac #9018.
2772
2773 So I'm trying out this rule: print explicit foralls if
2774 a) User specifies -fprint-explicit-foralls, or
2775 b) Any of the quantified type variables has a kind
2776 that mentions a kind variable
2777
2778 This catches common situations, such as a type siguature
2779 f :: m a
2780 which means
2781 f :: forall k. forall (m :: k->*) (a :: k). m a
2782 We really want to see both the "forall k" and the kind signatures
2783 on m and a. The latter comes from pprTvBndr.
2784
2785 Note [Infix type variables]
2786 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2787 With TypeOperators you can say
2788
2789 f :: (a ~> b) -> b
2790
2791 and the (~>) is considered a type variable. However, the type
2792 pretty-printer in this module will just see (a ~> b) as
2793
2794 App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
2795
2796 So it'll print the type in prefix form. To avoid confusion we must
2797 remember to parenthesise the operator, thus
2798
2799 (~>) a b -> b
2800
2801 See Trac #2766.
2802 -}
2803
2804 pprDataCons :: TyCon -> SDoc
2805 pprDataCons = sepWithVBars . fmap pprDataConWithArgs . tyConDataCons
2806 where
2807 sepWithVBars [] = empty
2808 sepWithVBars docs = sep (punctuate (space <> vbar) docs)
2809
2810 pprDataConWithArgs :: DataCon -> SDoc
2811 pprDataConWithArgs dc = sep [forAllDoc, thetaDoc, ppr dc <+> argsDoc]
2812 where
2813 (_univ_tvs, _ex_tvs, _eq_spec, theta, arg_tys, _res_ty) = dataConFullSig dc
2814 user_bndrs = dataConUserTyVarBinders dc
2815 forAllDoc = pprUserForAll user_bndrs
2816 thetaDoc = pprThetaArrowTy theta
2817 argsDoc = hsep (fmap pprParendType arg_tys)
2818
2819
2820 pprTypeApp :: TyCon -> [Type] -> SDoc
2821 pprTypeApp tc tys
2822 = pprIfaceTypeApp TopPrec (toIfaceTyCon tc)
2823 (toIfaceTcArgs tc tys)
2824 -- TODO: toIfaceTcArgs seems rather wasteful here
2825
2826 ------------------
2827 ppSuggestExplicitKinds :: SDoc
2828 -- Print a helpful suggstion about -fprint-explicit-kinds,
2829 -- if it is not already on
2830 ppSuggestExplicitKinds
2831 = sdocWithDynFlags $ \ dflags ->
2832 ppUnless (gopt Opt_PrintExplicitKinds dflags) $
2833 text "Use -fprint-explicit-kinds to see the kind arguments"
2834
2835 {-
2836 %************************************************************************
2837 %* *
2838 \subsection{TidyType}
2839 %* *
2840 %************************************************************************
2841 -}
2842
2843 -- | This tidies up a type for printing in an error message, or in
2844 -- an interface file.
2845 --
2846 -- It doesn't change the uniques at all, just the print names.
2847 tidyTyCoVarBndrs :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar])
2848 tidyTyCoVarBndrs (occ_env, subst) tvs
2849 = mapAccumL tidyTyCoVarBndr tidy_env' tvs
2850 where
2851 -- Seed the occ_env with clashes among the names, see
2852 -- Node [Tidying multiple names at once] in OccName
2853 -- Se still go through tidyTyCoVarBndr so that each kind variable is tidied
2854 -- with the correct tidy_env
2855 occs = map getHelpfulOccName tvs
2856 tidy_env' = (avoidClashesOccEnv occ_env occs, subst)
2857
2858 tidyTyCoVarBndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar)
2859 tidyTyCoVarBndr tidy_env@(occ_env, subst) tyvar
2860 = case tidyOccName occ_env (getHelpfulOccName tyvar) of
2861 (occ_env', occ') -> ((occ_env', subst'), tyvar')
2862 where
2863 subst' = extendVarEnv subst tyvar tyvar'
2864 tyvar' = setTyVarKind (setTyVarName tyvar name') kind'
2865 kind' = tidyKind tidy_env (tyVarKind tyvar)
2866 name' = tidyNameOcc name occ'
2867 name = tyVarName tyvar
2868
2869 getHelpfulOccName :: TyCoVar -> OccName
2870 getHelpfulOccName tyvar = occ1
2871 where
2872 name = tyVarName tyvar
2873 occ = getOccName name
2874 -- A TcTyVar with a System Name is probably a unification variable;
2875 -- when we tidy them we give them a trailing "0" (or 1 etc)
2876 -- so that they don't take precedence for the un-modified name
2877 -- Plus, indicating a unification variable in this way is a
2878 -- helpful clue for users
2879 occ1 | isSystemName name
2880 , isTcTyVar tyvar
2881 = mkTyVarOcc (occNameString occ ++ "0")
2882 | otherwise
2883 = occ
2884
2885 tidyTyVarBinder :: TidyEnv -> TyVarBndr TyVar vis
2886 -> (TidyEnv, TyVarBndr TyVar vis)
2887 tidyTyVarBinder tidy_env (TvBndr tv vis)
2888 = (tidy_env', TvBndr tv' vis)
2889 where
2890 (tidy_env', tv') = tidyTyCoVarBndr tidy_env tv
2891
2892 tidyTyVarBinders :: TidyEnv -> [TyVarBndr TyVar vis]
2893 -> (TidyEnv, [TyVarBndr TyVar vis])
2894 tidyTyVarBinders = mapAccumL tidyTyVarBinder
2895
2896 ---------------
2897 tidyFreeTyCoVars :: TidyEnv -> [TyCoVar] -> TidyEnv
2898 -- ^ Add the free 'TyVar's to the env in tidy form,
2899 -- so that we can tidy the type they are free in
2900 tidyFreeTyCoVars (full_occ_env, var_env) tyvars
2901 = fst (tidyOpenTyCoVars (full_occ_env, var_env) tyvars)
2902
2903 ---------------
2904 tidyOpenTyCoVars :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar])
2905 tidyOpenTyCoVars env tyvars = mapAccumL tidyOpenTyCoVar env tyvars
2906
2907 ---------------
2908 tidyOpenTyCoVar :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar)
2909 -- ^ Treat a new 'TyCoVar' as a binder, and give it a fresh tidy name
2910 -- using the environment if one has not already been allocated. See
2911 -- also 'tidyTyCoVarBndr'
2912 tidyOpenTyCoVar env@(_, subst) tyvar
2913 = case lookupVarEnv subst tyvar of
2914 Just tyvar' -> (env, tyvar') -- Already substituted
2915 Nothing ->
2916 let env' = tidyFreeTyCoVars env (tyCoVarsOfTypeList (tyVarKind tyvar))
2917 in tidyTyCoVarBndr env' tyvar -- Treat it as a binder
2918
2919 ---------------
2920 tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar
2921 tidyTyVarOcc env@(_, subst) tv
2922 = case lookupVarEnv subst tv of
2923 Nothing -> updateTyVarKind (tidyType env) tv
2924 Just tv' -> tv'
2925
2926 ---------------
2927 tidyTypes :: TidyEnv -> [Type] -> [Type]
2928 tidyTypes env tys = map (tidyType env) tys
2929
2930 ---------------
2931 tidyType :: TidyEnv -> Type -> Type
2932 tidyType _ (LitTy n) = LitTy n
2933 tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv)
2934 tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys
2935 in args `seqList` TyConApp tycon args
2936 tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg)
2937 tidyType env (FunTy fun arg) = (FunTy $! (tidyType env fun)) $! (tidyType env arg)
2938 tidyType env (ty@(ForAllTy{})) = mkForAllTys' (zip tvs' vis) $! tidyType env' body_ty
2939 where
2940 (tvs, vis, body_ty) = splitForAllTys' ty
2941 (env', tvs') = tidyTyCoVarBndrs env tvs
2942 tidyType env (CastTy ty co) = (CastTy $! tidyType env ty) $! (tidyCo env co)
2943 tidyType env (CoercionTy co) = CoercionTy $! (tidyCo env co)
2944
2945
2946 -- The following two functions differ from mkForAllTys and splitForAllTys in that
2947 -- they expect/preserve the ArgFlag argument. Thes belong to types/Type.hs, but
2948 -- how should they be named?
2949 mkForAllTys' :: [(TyVar, ArgFlag)] -> Type -> Type
2950 mkForAllTys' tvvs ty = foldr strictMkForAllTy ty tvvs
2951 where
2952 strictMkForAllTy (tv,vis) ty = (ForAllTy $! ((TvBndr $! tv) $! vis)) $! ty
2953
2954 splitForAllTys' :: Type -> ([TyVar], [ArgFlag], Type)
2955 splitForAllTys' ty = go ty [] []
2956 where
2957 go (ForAllTy (TvBndr tv vis) ty) tvs viss = go ty (tv:tvs) (vis:viss)
2958 go ty tvs viss = (reverse tvs, reverse viss, ty)
2959
2960
2961 ---------------
2962 -- | Grabs the free type variables, tidies them
2963 -- and then uses 'tidyType' to work over the type itself
2964 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
2965 tidyOpenTypes env tys
2966 = (env', tidyTypes (trimmed_occ_env, var_env) tys)
2967 where
2968 (env'@(_, var_env), tvs') = tidyOpenTyCoVars env $
2969 tyCoVarsOfTypesWellScoped tys
2970 trimmed_occ_env = initTidyOccEnv (map getOccName tvs')
2971 -- The idea here was that we restrict the new TidyEnv to the
2972 -- _free_ vars of the types, so that we don't gratuitously rename
2973 -- the _bound_ variables of the types.
2974
2975 ---------------
2976 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
2977 tidyOpenType env ty = let (env', [ty']) = tidyOpenTypes env [ty] in
2978 (env', ty')
2979
2980 ---------------
2981 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
2982 tidyTopType :: Type -> Type
2983 tidyTopType ty = tidyType emptyTidyEnv ty
2984
2985 ---------------
2986 tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
2987 tidyOpenKind = tidyOpenType
2988
2989 tidyKind :: TidyEnv -> Kind -> Kind
2990 tidyKind = tidyType
2991
2992 ----------------
2993 tidyCo :: TidyEnv -> Coercion -> Coercion
2994 tidyCo env@(_, subst) co
2995 = go co
2996 where
2997 go (Refl r ty) = Refl r (tidyType env ty)
2998 go (TyConAppCo r tc cos) = let args = map go cos
2999 in args `seqList` TyConAppCo r tc args
3000 go (AppCo co1 co2) = (AppCo $! go co1) $! go co2
3001 go (ForAllCo tv h co) = ((ForAllCo $! tvp) $! (go h)) $! (tidyCo envp co)
3002 where (envp, tvp) = tidyTyCoVarBndr env tv
3003 -- the case above duplicates a bit of work in tidying h and the kind
3004 -- of tv. But the alternative is to use coercionKind, which seems worse.
3005 go (FunCo r co1 co2) = (FunCo r $! go co1) $! go co2
3006 go (CoVarCo cv) = case lookupVarEnv subst cv of
3007 Nothing -> CoVarCo cv
3008 Just cv' -> CoVarCo cv'
3009 go (HoleCo h) = HoleCo h
3010 go (AxiomInstCo con ind cos) = let args = map go cos
3011 in args `seqList` AxiomInstCo con ind args
3012 go (UnivCo p r t1 t2) = (((UnivCo $! (go_prov p)) $! r) $!
3013 tidyType env t1) $! tidyType env t2
3014 go (SymCo co) = SymCo $! go co
3015 go (TransCo co1 co2) = (TransCo $! go co1) $! go co2
3016 go (NthCo d co) = NthCo d $! go co
3017 go (LRCo lr co) = LRCo lr $! go co
3018 go (InstCo co ty) = (InstCo $! go co) $! go ty
3019 go (CoherenceCo co1 co2) = (CoherenceCo $! go co1) $! go co2
3020 go (KindCo co) = KindCo $! go co
3021 go (SubCo co) = SubCo $! go co
3022 go (AxiomRuleCo ax cos) = let cos1 = tidyCos env cos
3023 in cos1 `seqList` AxiomRuleCo ax cos1
3024
3025 go_prov UnsafeCoerceProv = UnsafeCoerceProv
3026 go_prov (PhantomProv co) = PhantomProv (go co)
3027 go_prov (ProofIrrelProv co) = ProofIrrelProv (go co)
3028 go_prov p@(PluginProv _) = p
3029
3030 tidyCos :: TidyEnv -> [Coercion] -> [Coercion]
3031 tidyCos env = map (tidyCo env)
3032
3033
3034 {- *********************************************************************
3035 * *
3036 typeSize, coercionSize
3037 * *
3038 ********************************************************************* -}
3039
3040 -- NB: We put typeSize/coercionSize here because they are mutually
3041 -- recursive, and have the CPR property. If we have mutual
3042 -- recursion across a hi-boot file, we don't get the CPR property
3043 -- and these functions allocate a tremendous amount of rubbish.
3044 -- It's not critical (because typeSize is really only used in
3045 -- debug mode, but I tripped over an example (T5642) in which
3046 -- typeSize was one of the biggest single allocators in all of GHC.
3047 -- And it's easy to fix, so I did.
3048
3049 -- NB: typeSize does not respect `eqType`, in that two types that
3050 -- are `eqType` may return different sizes. This is OK, because this
3051 -- function is used only in reporting, not decision-making.
3052
3053 typeSize :: Type -> Int
3054 typeSize (LitTy {}) = 1
3055 typeSize (TyVarTy {}) = 1
3056 typeSize (AppTy t1 t2) = typeSize t1 + typeSize t2
3057 typeSize (FunTy t1 t2) = typeSize t1 + typeSize t2
3058 typeSize (ForAllTy (TvBndr tv _) t) = typeSize (tyVarKind tv) + typeSize t
3059 typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts)
3060 typeSize (CastTy ty co) = typeSize ty + coercionSize co
3061 typeSize (CoercionTy co) = coercionSize co
3062
3063 coercionSize :: Coercion -> Int
3064 coercionSize (Refl _ ty) = typeSize ty
3065 coercionSize (TyConAppCo _ _ args) = 1 + sum (map coercionSize args)
3066 coercionSize (AppCo co arg) = coercionSize co + coercionSize arg
3067 coercionSize (ForAllCo _ h co) = 1 + coercionSize co + coercionSize h
3068 coercionSize (FunCo _ co1 co2) = 1 + coercionSize co1 + coercionSize co2
3069 coercionSize (CoVarCo _) = 1
3070 coercionSize (HoleCo _) = 1
3071 coercionSize (AxiomInstCo _ _ args) = 1 + sum (map coercionSize args)
3072 coercionSize (UnivCo p _ t1 t2) = 1 + provSize p + typeSize t1 + typeSize t2
3073 coercionSize (SymCo co) = 1 + coercionSize co
3074 coercionSize (TransCo co1 co2) = 1 + coercionSize co1 + coercionSize co2
3075 coercionSize (NthCo _ co) = 1 + coercionSize co
3076 coercionSize (LRCo _ co) = 1 + coercionSize co
3077 coercionSize (InstCo co arg) = 1 + coercionSize co + coercionSize arg
3078 coercionSize (CoherenceCo c1 c2) = 1 + coercionSize c1 + coercionSize c2
3079 coercionSize (KindCo co) = 1 + coercionSize co
3080 coercionSize (SubCo co) = 1 + coercionSize co
3081 coercionSize (AxiomRuleCo _ cs) = 1 + sum (map coercionSize cs)
3082
3083 provSize :: UnivCoProvenance -> Int
3084 provSize UnsafeCoerceProv = 1
3085 provSize (PhantomProv co) = 1 + coercionSize co
3086 provSize (ProofIrrelProv co) = 1 + coercionSize co
3087 provSize (PluginProv _) = 1