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