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