b1f35da3114eb0c73b2346d5da599e10d854fad7
[ghc.git] / compiler / types / TyCoRep.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1998
4 \section[TyCoRep]{Type and Coercion - friends' interface}
5
6 Note [The Type-related module hierarchy]
7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
8 Class
9 CoAxiom
10 TyCon imports Class, CoAxiom
11 TyCoRep imports Class, CoAxiom, TyCon
12 TysPrim imports TyCoRep ( including mkTyConTy )
13 Kind imports TysPrim ( mainly for primitive kinds )
14 Type imports Kind
15 Coercion imports Type
16 -}
17
18 -- We expose the relevant stuff from this module via the Type module
19 {-# OPTIONS_HADDOCK hide #-}
20 {-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
21 DeriveTraversable, MultiWayIf #-}
22 {-# LANGUAGE ImplicitParams #-}
23
24 module TyCoRep (
25 TyThing(..),
26 Type(..),
27 TyBinder(..),
28 TyLit(..),
29 KindOrType, Kind,
30 PredType, ThetaType, -- Synonyms
31 VisibilityFlag(..),
32
33 -- * Coercions
34 Coercion(..), LeftOrRight(..),
35 UnivCoProvenance(..), CoercionHole(..),
36 CoercionN, CoercionR, CoercionP, KindCoercion,
37
38 -- * Functions over types
39 mkTyConTy, mkTyVarTy, mkTyVarTys,
40 mkFunTy, mkFunTys, mkForAllTys,
41 isLiftedTypeKind, isUnliftedTypeKind,
42 isCoercionType, isRuntimeRepTy, isRuntimeRepVar,
43 isRuntimeRepKindedTy, dropRuntimeRepArgs,
44 sameVis,
45
46 -- * Functions over binders
47 binderType, delBinderVar, isInvisibleBinder, isVisibleBinder,
48 isNamedBinder, isAnonBinder,
49
50 -- * Functions over coercions
51 pickLR,
52
53 -- * Pretty-printing
54 pprType, pprParendType, pprTypeApp, pprTvBndr, pprTvBndrs,
55 pprTyThing, pprTyThingCategory, pprSigmaType,
56 pprTheta, pprForAll, pprForAllImplicit, pprUserForAll,
57 pprThetaArrowTy, pprClassPred,
58 pprKind, pprParendKind, pprTyLit,
59 TyPrec(..), maybeParen, pprTcAppCo, pprTcAppTy,
60 pprPrefixApp, pprArrowChain, ppr_type,
61 pprDataCons,
62
63 -- * Free variables
64 tyCoVarsOfType, tyCoVarsOfTypeDSet, tyCoVarsOfTypes, tyCoVarsOfTypesDSet,
65 tyCoVarsBndrAcc, tyCoVarsOfTypeAcc, tyCoVarsOfTypeList,
66 tyCoVarsOfTypesAcc, tyCoVarsOfTypesList,
67 closeOverKindsDSet, closeOverKindsAcc,
68 coVarsOfType, coVarsOfTypes,
69 coVarsOfCo, coVarsOfCos,
70 tyCoVarsOfCo, tyCoVarsOfCos,
71 tyCoVarsOfCoDSet,
72 tyCoVarsOfCoAcc, tyCoVarsOfCosAcc,
73 tyCoVarsOfCoList, tyCoVarsOfProv,
74 closeOverKinds,
75 tyCoVarsOfTelescope,
76
77 -- * Substitutions
78 TCvSubst(..), TvSubstEnv, CvSubstEnv,
79 emptyTvSubstEnv, emptyCvSubstEnv, composeTCvSubstEnv, composeTCvSubst,
80 emptyTCvSubst, mkEmptyTCvSubst, isEmptyTCvSubst,
81 mkTCvSubst, mkTvSubst,
82 getTvSubstEnv,
83 getCvSubstEnv, getTCvInScope, isInScope, notElemTCvSubst,
84 setTvSubstEnv, setCvSubstEnv, zapTCvSubst,
85 extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
86 extendTCvSubst,
87 extendCvSubst, extendCvSubstWithClone,
88 extendTvSubst, extendTvSubstWithClone,
89 extendTvSubstList, extendTvSubstAndInScope,
90 extendTvSubstBinder,
91 unionTCvSubst, zipTyEnv, zipCoEnv, mkTyCoInScopeSet,
92 zipTvSubst, zipCvSubst,
93 zipTyBinderSubst,
94 mkTvSubstPrs,
95
96 substTyWith, substTyWithCoVars, substTysWith, substTysWithCoVars,
97 substCoWith,
98 substTy, substTyAddInScope,
99 substTyUnchecked, substTysUnchecked, substThetaUnchecked,
100 substTyWithUnchecked,
101 substCoUnchecked, substCoWithUnchecked,
102 substTyWithInScope,
103 substTys, substTheta,
104 lookupTyVar, substTyVarBndr,
105 substCo, substCos, substCoVar, substCoVars, lookupCoVar,
106 substCoVarBndr, cloneTyVarBndr, cloneTyVarBndrs,
107 substTyVar, substTyVars,
108 substForAllCoBndr,
109 substTyVarBndrCallback, substForAllCoBndrCallback,
110 substCoVarBndrCallback,
111
112 -- * Tidying type related things up for printing
113 tidyType, tidyTypes,
114 tidyOpenType, tidyOpenTypes,
115 tidyOpenKind,
116 tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
117 tidyOpenTyCoVar, tidyOpenTyCoVars,
118 tidyTyVarOcc,
119 tidyTopType,
120 tidyKind,
121 tidyCo, tidyCos,
122 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(..) )
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 deriving (Eq)
1567
1568 instance Outputable TyThing where
1569 ppr = pprTyThing
1570
1571 pprTyThing :: TyThing -> SDoc
1572 pprTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
1573
1574 pprTyThingCategory :: TyThing -> SDoc
1575 pprTyThingCategory (ATyCon tc)
1576 | isClassTyCon tc = text "Class"
1577 | otherwise = text "Type constructor"
1578 pprTyThingCategory (ACoAxiom _) = text "Coercion axiom"
1579 pprTyThingCategory (AnId _) = text "Identifier"
1580 pprTyThingCategory (AConLike (RealDataCon _)) = text "Data constructor"
1581 pprTyThingCategory (AConLike (PatSynCon _)) = text "Pattern synonym"
1582
1583
1584 instance NamedThing TyThing where -- Can't put this with the type
1585 getName (AnId id) = getName id -- decl, because the DataCon instance
1586 getName (ATyCon tc) = getName tc -- isn't visible there
1587 getName (ACoAxiom cc) = getName cc
1588 getName (AConLike cl) = getName cl
1589
1590 {-
1591 %************************************************************************
1592 %* *
1593 Substitutions
1594 Data type defined here to avoid unnecessary mutual recursion
1595 %* *
1596 %************************************************************************
1597 -}
1598
1599 -- | Type & coercion substitution
1600 --
1601 -- #tcvsubst_invariant#
1602 -- The following invariants must hold of a 'TCvSubst':
1603 --
1604 -- 1. The in-scope set is needed /only/ to
1605 -- guide the generation of fresh uniques
1606 --
1607 -- 2. In particular, the /kind/ of the type variables in
1608 -- the in-scope set is not relevant
1609 --
1610 -- 3. The substitution is only applied ONCE! This is because
1611 -- in general such application will not reach a fixed point.
1612 data TCvSubst
1613 = TCvSubst InScopeSet -- The in-scope type and kind variables
1614 TvSubstEnv -- Substitutes both type and kind variables
1615 CvSubstEnv -- Substitutes coercion variables
1616 -- See Note [Apply Once]
1617 -- and Note [Extending the TvSubstEnv]
1618 -- and Note [Substituting types and coercions]
1619 -- and Note [The substitution invariant]
1620
1621 -- | A substitution of 'Type's for 'TyVar's
1622 -- and 'Kind's for 'KindVar's
1623 type TvSubstEnv = TyVarEnv Type
1624 -- A TvSubstEnv is used both inside a TCvSubst (with the apply-once
1625 -- invariant discussed in Note [Apply Once]), and also independently
1626 -- in the middle of matching, and unification (see Types.Unify)
1627 -- So you have to look at the context to know if it's idempotent or
1628 -- apply-once or whatever
1629
1630 -- | A substitution of 'Coercion's for 'CoVar's
1631 type CvSubstEnv = CoVarEnv Coercion
1632
1633 {-
1634 Note [Apply Once]
1635 ~~~~~~~~~~~~~~~~~
1636 We use TCvSubsts to instantiate things, and we might instantiate
1637 forall a b. ty
1638 \with the types
1639 [a, b], or [b, a].
1640 So the substitution might go [a->b, b->a]. A similar situation arises in Core
1641 when we find a beta redex like
1642 (/\ a /\ b -> e) b a
1643 Then we also end up with a substitution that permutes type variables. Other
1644 variations happen to; for example [a -> (a, b)].
1645
1646 ****************************************************
1647 *** So a TCvSubst must be applied precisely once ***
1648 ****************************************************
1649
1650 A TCvSubst is not idempotent, but, unlike the non-idempotent substitution
1651 we use during unifications, it must not be repeatedly applied.
1652
1653 Note [Extending the TvSubstEnv]
1654 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1655 See #tcvsubst_invariant# for the invariants that must hold.
1656
1657 This invariant allows a short-cut when the subst envs are empty:
1658 if the TvSubstEnv and CvSubstEnv are empty --- i.e. (isEmptyTCvSubst subst)
1659 holds --- then (substTy subst ty) does nothing.
1660
1661 For example, consider:
1662 (/\a. /\b:(a~Int). ...b..) Int
1663 We substitute Int for 'a'. The Unique of 'b' does not change, but
1664 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
1665
1666 This invariant has several crucial consequences:
1667
1668 * In substTyVarBndr, we need extend the TvSubstEnv
1669 - if the unique has changed
1670 - or if the kind has changed
1671
1672 * In substTyVar, we do not need to consult the in-scope set;
1673 the TvSubstEnv is enough
1674
1675 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1676
1677 Note [Substituting types and coercions]
1678 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1679 Types and coercions are mutually recursive, and either may have variables
1680 "belonging" to the other. Thus, every time we wish to substitute in a
1681 type, we may also need to substitute in a coercion, and vice versa.
1682 However, the constructor used to create type variables is distinct from
1683 that of coercion variables, so we carry two VarEnvs in a TCvSubst. Note
1684 that it would be possible to use the CoercionTy constructor to combine
1685 these environments, but that seems like a false economy.
1686
1687 Note that the TvSubstEnv should *never* map a CoVar (built with the Id
1688 constructor) and the CvSubstEnv should *never* map a TyVar. Furthermore,
1689 the range of the TvSubstEnv should *never* include a type headed with
1690 CoercionTy.
1691
1692 Note [The substitution invariant]
1693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1694 When calling (substTy subst ty) it should be the case that
1695 the in-scope set in the substitution is a superset of both:
1696
1697 * The free vars of the range of the substitution
1698 * The free vars of ty minus the domain of the substitution
1699
1700 If we want to substitute [a -> ty1, b -> ty2] I used to
1701 think it was enough to generate an in-scope set that includes
1702 fv(ty1,ty2). But that's not enough; we really should also take the
1703 free vars of the type we are substituting into! Example:
1704 (forall b. (a,b,x)) [a -> List b]
1705 Then if we use the in-scope set {b}, there is a danger we will rename
1706 the forall'd variable to 'x' by mistake, getting this:
1707 (forall x. (List b, x, x))
1708
1709 Breaking this invariant caused the bug from #11371.
1710 -}
1711
1712 emptyTvSubstEnv :: TvSubstEnv
1713 emptyTvSubstEnv = emptyVarEnv
1714
1715 emptyCvSubstEnv :: CvSubstEnv
1716 emptyCvSubstEnv = emptyVarEnv
1717
1718 composeTCvSubstEnv :: InScopeSet
1719 -> (TvSubstEnv, CvSubstEnv)
1720 -> (TvSubstEnv, CvSubstEnv)
1721 -> (TvSubstEnv, CvSubstEnv)
1722 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1723 -- It assumes that both are idempotent.
1724 -- Typically, @env1@ is the refinement to a base substitution @env2@
1725 composeTCvSubstEnv in_scope (tenv1, cenv1) (tenv2, cenv2)
1726 = ( tenv1 `plusVarEnv` mapVarEnv (substTy subst1) tenv2
1727 , cenv1 `plusVarEnv` mapVarEnv (substCo subst1) cenv2 )
1728 -- First apply env1 to the range of env2
1729 -- Then combine the two, making sure that env1 loses if
1730 -- both bind the same variable; that's why env1 is the
1731 -- *left* argument to plusVarEnv, because the right arg wins
1732 where
1733 subst1 = TCvSubst in_scope tenv1 cenv1
1734
1735 -- | Composes two substitutions, applying the second one provided first,
1736 -- like in function composition.
1737 composeTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst
1738 composeTCvSubst (TCvSubst is1 tenv1 cenv1) (TCvSubst is2 tenv2 cenv2)
1739 = TCvSubst is3 tenv3 cenv3
1740 where
1741 is3 = is1 `unionInScope` is2
1742 (tenv3, cenv3) = composeTCvSubstEnv is3 (tenv1, cenv1) (tenv2, cenv2)
1743
1744 emptyTCvSubst :: TCvSubst
1745 emptyTCvSubst = TCvSubst emptyInScopeSet emptyTvSubstEnv emptyCvSubstEnv
1746
1747 mkEmptyTCvSubst :: InScopeSet -> TCvSubst
1748 mkEmptyTCvSubst is = TCvSubst is emptyTvSubstEnv emptyCvSubstEnv
1749
1750 isEmptyTCvSubst :: TCvSubst -> Bool
1751 -- See Note [Extending the TvSubstEnv]
1752 isEmptyTCvSubst (TCvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv
1753
1754 mkTCvSubst :: InScopeSet -> (TvSubstEnv, CvSubstEnv) -> TCvSubst
1755 mkTCvSubst in_scope (tenv, cenv) = TCvSubst in_scope tenv cenv
1756
1757 mkTvSubst :: InScopeSet -> TvSubstEnv -> TCvSubst
1758 -- ^ Mkae a TCvSubst with specified tyvar subst and empty covar subst
1759 mkTvSubst in_scope tenv = TCvSubst in_scope tenv emptyCvSubstEnv
1760
1761 getTvSubstEnv :: TCvSubst -> TvSubstEnv
1762 getTvSubstEnv (TCvSubst _ env _) = env
1763
1764 getCvSubstEnv :: TCvSubst -> CvSubstEnv
1765 getCvSubstEnv (TCvSubst _ _ env) = env
1766
1767 getTCvInScope :: TCvSubst -> InScopeSet
1768 getTCvInScope (TCvSubst in_scope _ _) = in_scope
1769
1770 isInScope :: Var -> TCvSubst -> Bool
1771 isInScope v (TCvSubst in_scope _ _) = v `elemInScopeSet` in_scope
1772
1773 notElemTCvSubst :: Var -> TCvSubst -> Bool
1774 notElemTCvSubst v (TCvSubst _ tenv cenv)
1775 | isTyVar v
1776 = not (v `elemVarEnv` tenv)
1777 | otherwise
1778 = not (v `elemVarEnv` cenv)
1779
1780 setTvSubstEnv :: TCvSubst -> TvSubstEnv -> TCvSubst
1781 setTvSubstEnv (TCvSubst in_scope _ cenv) tenv = TCvSubst in_scope tenv cenv
1782
1783 setCvSubstEnv :: TCvSubst -> CvSubstEnv -> TCvSubst
1784 setCvSubstEnv (TCvSubst in_scope tenv _) cenv = TCvSubst in_scope tenv cenv
1785
1786 zapTCvSubst :: TCvSubst -> TCvSubst
1787 zapTCvSubst (TCvSubst in_scope _ _) = TCvSubst in_scope emptyVarEnv emptyVarEnv
1788
1789 extendTCvInScope :: TCvSubst -> Var -> TCvSubst
1790 extendTCvInScope (TCvSubst in_scope tenv cenv) var
1791 = TCvSubst (extendInScopeSet in_scope var) tenv cenv
1792
1793 extendTCvInScopeList :: TCvSubst -> [Var] -> TCvSubst
1794 extendTCvInScopeList (TCvSubst in_scope tenv cenv) vars
1795 = TCvSubst (extendInScopeSetList in_scope vars) tenv cenv
1796
1797 extendTCvInScopeSet :: TCvSubst -> VarSet -> TCvSubst
1798 extendTCvInScopeSet (TCvSubst in_scope tenv cenv) vars
1799 = TCvSubst (extendInScopeSetSet in_scope vars) tenv cenv
1800
1801 extendTCvSubst :: TCvSubst -> TyCoVar -> Type -> TCvSubst
1802 extendTCvSubst subst v ty
1803 | isTyVar v
1804 = extendTvSubst subst v ty
1805 | CoercionTy co <- ty
1806 = extendCvSubst subst v co
1807 | otherwise
1808 = pprPanic "extendTCvSubst" (ppr v <+> text "|->" <+> ppr ty)
1809
1810 extendTvSubst :: TCvSubst -> TyVar -> Type -> TCvSubst
1811 extendTvSubst (TCvSubst in_scope tenv cenv) tv ty
1812 = TCvSubst in_scope (extendVarEnv tenv tv ty) cenv
1813
1814 extendTvSubstWithClone :: TCvSubst -> TyVar -> TyVar -> TCvSubst
1815 -- Adds a new tv -> tv mapping, /and/ extends the in-scope set
1816 extendTvSubstWithClone (TCvSubst in_scope tenv cenv) tv tv'
1817 = TCvSubst (extendInScopeSet in_scope tv')
1818 (extendVarEnv tenv tv (mkTyVarTy tv'))
1819 cenv
1820
1821 extendCvSubst :: TCvSubst -> CoVar -> Coercion -> TCvSubst
1822 extendCvSubst (TCvSubst in_scope tenv cenv) v co
1823 = TCvSubst in_scope tenv (extendVarEnv cenv v co)
1824
1825 extendCvSubstWithClone :: TCvSubst -> CoVar -> CoVar -> TCvSubst
1826 extendCvSubstWithClone (TCvSubst in_scope tenv cenv) cv cv'
1827 = TCvSubst (extendInScopeSet in_scope cv')
1828 tenv
1829 (extendVarEnv cenv cv (mkCoVarCo cv'))
1830
1831 extendTvSubstAndInScope :: TCvSubst -> TyVar -> Type -> TCvSubst
1832 -- Also extends the in-scope set
1833 extendTvSubstAndInScope (TCvSubst in_scope tenv cenv) tv ty
1834 = TCvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfType ty)
1835 (extendVarEnv tenv tv ty)
1836 cenv
1837
1838 extendTvSubstList :: TCvSubst -> [Var] -> [Type] -> TCvSubst
1839 extendTvSubstList subst tvs tys
1840 = foldl2 extendTvSubst subst tvs tys
1841
1842 extendTvSubstBinder :: TCvSubst -> TyBinder -> Type -> TCvSubst
1843 extendTvSubstBinder env (Anon {}) _ = env
1844 extendTvSubstBinder env (Named tv _) ty = extendTvSubst env tv ty
1845
1846 unionTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst
1847 -- Works when the ranges are disjoint
1848 unionTCvSubst (TCvSubst in_scope1 tenv1 cenv1) (TCvSubst in_scope2 tenv2 cenv2)
1849 = ASSERT( not (tenv1 `intersectsVarEnv` tenv2)
1850 && not (cenv1 `intersectsVarEnv` cenv2) )
1851 TCvSubst (in_scope1 `unionInScope` in_scope2)
1852 (tenv1 `plusVarEnv` tenv2)
1853 (cenv1 `plusVarEnv` cenv2)
1854
1855 -- mkTvSubstPrs and zipTvSubst generate the in-scope set from
1856 -- the types given; but it's just a thunk so with a bit of luck
1857 -- it'll never be evaluated
1858
1859 -- | Generates an in-scope set from the free variables in a list of types
1860 -- and a list of coercions
1861 mkTyCoInScopeSet :: [Type] -> [Coercion] -> InScopeSet
1862 mkTyCoInScopeSet tys cos
1863 = mkInScopeSet (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos)
1864
1865 -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming
1866 -- environment. No CoVars, please!
1867 zipTvSubst :: [TyVar] -> [Type] -> TCvSubst
1868 zipTvSubst tvs tys
1869 | debugIsOn
1870 , not (all isTyVar tvs) || length tvs /= length tys
1871 = pprTrace "zipTvSubst" (ppr tvs $$ ppr tys) emptyTCvSubst
1872 | otherwise
1873 = mkTvSubst (mkInScopeSet (tyCoVarsOfTypes tys)) tenv
1874 where
1875 tenv = zipTyEnv tvs tys
1876
1877 -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming
1878 -- environment. No TyVars, please!
1879 zipCvSubst :: [CoVar] -> [Coercion] -> TCvSubst
1880 zipCvSubst cvs cos
1881 | debugIsOn
1882 , not (all isCoVar cvs) || length cvs /= length cos
1883 = pprTrace "zipCvSubst" (ppr cvs $$ ppr cos) emptyTCvSubst
1884 | otherwise
1885 = TCvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv cenv
1886 where
1887 cenv = zipCoEnv cvs cos
1888
1889 -- | Create a TCvSubst combining the binders and types provided.
1890 -- NB: It is specifically OK if the lists are of different lengths.
1891 zipTyBinderSubst :: [TyBinder] -> [Type] -> TCvSubst
1892 zipTyBinderSubst bndrs tys
1893 = mkTvSubst is tenv
1894 where
1895 is = mkInScopeSet (tyCoVarsOfTypes tys)
1896 tenv = mkVarEnv [ (tv, ty) | (Named tv _, ty) <- zip bndrs tys ]
1897
1898 -- | Generates the in-scope set for the 'TCvSubst' from the types in the
1899 -- incoming environment. No CoVars, please!
1900 mkTvSubstPrs :: [(TyVar, Type)] -> TCvSubst
1901 mkTvSubstPrs prs =
1902 ASSERT2( onlyTyVarsAndNoCoercionTy, text "prs" <+> ppr prs )
1903 mkTvSubst in_scope tenv
1904 where tenv = mkVarEnv prs
1905 in_scope = mkInScopeSet $ tyCoVarsOfTypes $ map snd prs
1906 onlyTyVarsAndNoCoercionTy =
1907 and [ isTyVar tv && not (isCoercionTy ty)
1908 | (tv, ty) <- prs ]
1909
1910 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1911 zipTyEnv tyvars tys
1912 = ASSERT( all (not . isCoercionTy) tys )
1913 mkVarEnv (zipEqual "zipTyEnv" tyvars tys)
1914 -- There used to be a special case for when
1915 -- ty == TyVarTy tv
1916 -- (a not-uncommon case) in which case the substitution was dropped.
1917 -- But the type-tidier changes the print-name of a type variable without
1918 -- changing the unique, and that led to a bug. Why? Pre-tidying, we had
1919 -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype.
1920 -- And it happened that t was the type variable of the class. Post-tiding,
1921 -- it got turned into {Foo t2}. The ext-core printer expanded this using
1922 -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1923 -- and so generated a rep type mentioning t not t2.
1924 --
1925 -- Simplest fix is to nuke the "optimisation"
1926
1927 zipCoEnv :: [CoVar] -> [Coercion] -> CvSubstEnv
1928 zipCoEnv cvs cos = mkVarEnv (zipEqual "zipCoEnv" cvs cos)
1929
1930 instance Outputable TCvSubst where
1931 ppr (TCvSubst ins tenv cenv)
1932 = brackets $ sep[ text "TCvSubst",
1933 nest 2 (text "In scope:" <+> ppr ins),
1934 nest 2 (text "Type env:" <+> ppr tenv),
1935 nest 2 (text "Co env:" <+> ppr cenv) ]
1936
1937 {-
1938 %************************************************************************
1939 %* *
1940 Performing type or kind substitutions
1941 %* *
1942 %************************************************************************
1943
1944 Note [Sym and ForAllCo]
1945 ~~~~~~~~~~~~~~~~~~~~~~~
1946 In OptCoercion, we try to push "sym" out to the leaves of a coercion. But,
1947 how do we push sym into a ForAllCo? It's a little ugly.
1948
1949 Here is the typing rule:
1950
1951 h : k1 ~# k2
1952 (tv : k1) |- g : ty1 ~# ty2
1953 ----------------------------
1954 ForAllCo tv h g : (ForAllTy (tv : k1) ty1) ~#
1955 (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h]))
1956
1957 Here is what we want:
1958
1959 ForAllCo tv h' g' : (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h])) ~#
1960 (ForAllTy (tv : k1) ty1)
1961
1962
1963 Because the kinds of the type variables to the right of the colon are the kinds
1964 coerced by h', we know (h' : k2 ~# k1). Thus, (h' = sym h).
1965
1966 Now, we can rewrite ty1 to be (ty1[tv |-> tv |> sym h' |> h']). We thus want
1967
1968 ForAllCo tv h' g' :
1969 (ForAllTy (tv : k2) (ty2[tv |-> tv |> h'])) ~#
1970 (ForAllTy (tv : k1) (ty1[tv |-> tv |> h'][tv |-> tv |> sym h']))
1971
1972 We thus see that we want
1973
1974 g' : ty2[tv |-> tv |> h'] ~# ty1[tv |-> tv |> h']
1975
1976 and thus g' = sym (g[tv |-> tv |> h']).
1977
1978 Putting it all together, we get this:
1979
1980 sym (ForAllCo tv h g)
1981 ==>
1982 ForAllCo tv (sym h) (sym g[tv |-> tv |> sym h])
1983
1984 -}
1985
1986 -- | Type substitution, see 'zipTvSubst'
1987 substTyWith ::
1988 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
1989 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
1990 (?callStack :: CallStack) =>
1991 #endif
1992 [TyVar] -> [Type] -> Type -> Type
1993 -- Works only if the domain of the substitution is a
1994 -- superset of the type being substituted into
1995 substTyWith tvs tys = ASSERT( length tvs == length tys )
1996 substTy (zipTvSubst tvs tys)
1997
1998 -- | Type substitution, see 'zipTvSubst'. Disables sanity checks.
1999 -- The problems that the sanity checks in substTy catch are described in
2000 -- Note [The substitution invariant].
2001 -- The goal of #11371 is to migrate all the calls of substTyUnchecked to
2002 -- substTy and remove this function. Please don't use in new code.
2003 substTyWithUnchecked :: [TyVar] -> [Type] -> Type -> Type
2004 substTyWithUnchecked tvs tys
2005 = ASSERT( length tvs == length tys )
2006 substTyUnchecked (zipTvSubst tvs tys)
2007
2008 -- | Substitute tyvars within a type using a known 'InScopeSet'.
2009 -- Pre-condition: the 'in_scope' set should satisfy Note [The substitution
2010 -- invariant]; specifically it should include the free vars of 'tys',
2011 -- and of 'ty' minus the domain of the subst.
2012 substTyWithInScope :: InScopeSet -> [TyVar] -> [Type] -> Type -> Type
2013 substTyWithInScope in_scope tvs tys ty =
2014 ASSERT( length tvs == length tys )
2015 substTy (mkTvSubst in_scope tenv) ty
2016 where tenv = zipTyEnv tvs tys
2017
2018 -- | Coercion substitution, see 'zipTvSubst'
2019 substCoWith ::
2020 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2021 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2022 (?callStack :: CallStack) =>
2023 #endif
2024 [TyVar] -> [Type] -> Coercion -> Coercion
2025 substCoWith tvs tys = ASSERT( length tvs == length tys )
2026 substCo (zipTvSubst tvs tys)
2027
2028 -- | Coercion substitution, see 'zipTvSubst'. Disables sanity checks.
2029 -- The problems that the sanity checks in substCo catch are described in
2030 -- Note [The substitution invariant].
2031 -- The goal of #11371 is to migrate all the calls of substCoUnchecked to
2032 -- substCo and remove this function. Please don't use in new code.
2033 substCoWithUnchecked :: [TyVar] -> [Type] -> Coercion -> Coercion
2034 substCoWithUnchecked tvs tys
2035 = ASSERT( length tvs == length tys )
2036 substCoUnchecked (zipTvSubst tvs tys)
2037
2038
2039
2040 -- | Substitute covars within a type
2041 substTyWithCoVars :: [CoVar] -> [Coercion] -> Type -> Type
2042 substTyWithCoVars cvs cos = substTy (zipCvSubst cvs cos)
2043
2044 -- | Type substitution, see 'zipTvSubst'
2045 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
2046 substTysWith tvs tys = ASSERT( length tvs == length tys )
2047 substTys (zipTvSubst tvs tys)
2048
2049 -- | Type substitution, see 'zipTvSubst'
2050 substTysWithCoVars :: [CoVar] -> [Coercion] -> [Type] -> [Type]
2051 substTysWithCoVars cvs cos = ASSERT( length cvs == length cos )
2052 substTys (zipCvSubst cvs cos)
2053
2054 -- | Substitute within a 'Type' after adding the free variables of the type
2055 -- to the in-scope set. This is useful for the case when the free variables
2056 -- aren't already in the in-scope set or easily available.
2057 -- See also Note [The substitution invariant].
2058 substTyAddInScope :: TCvSubst -> Type -> Type
2059 substTyAddInScope subst ty =
2060 substTy (extendTCvInScopeSet subst $ tyCoVarsOfType ty) ty
2061
2062 -- | When calling `substTy` it should be the case that the in-scope set in
2063 -- the substitution is a superset of the free vars of the range of the
2064 -- substitution.
2065 -- See also Note [The substitution invariant].
2066 isValidTCvSubst :: TCvSubst -> Bool
2067 isValidTCvSubst (TCvSubst in_scope tenv cenv) =
2068 (tenvFVs `varSetInScope` in_scope) &&
2069 (cenvFVs `varSetInScope` in_scope)
2070 where
2071 tenvFVs = tyCoVarsOfTypes $ varEnvElts tenv
2072 cenvFVs = tyCoVarsOfCos $ varEnvElts cenv
2073
2074 -- | This checks if the substitution satisfies the invariant from
2075 -- Note [The substitution invariant].
2076 checkValidSubst ::
2077 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2078 (?callStack :: CallStack) =>
2079 #endif
2080 TCvSubst -> [Type] -> [Coercion] -> a -> a
2081 checkValidSubst subst@(TCvSubst in_scope tenv cenv) tys cos a
2082 = ASSERT2( isValidTCvSubst subst,
2083 text "in_scope" <+> ppr in_scope $$
2084 text "tenv" <+> ppr tenv $$
2085 text "tenvFVs"
2086 <+> ppr (tyCoVarsOfTypes $ varEnvElts tenv) $$
2087 text "cenv" <+> ppr cenv $$
2088 text "cenvFVs"
2089 <+> ppr (tyCoVarsOfCos $ varEnvElts cenv) $$
2090 text "tys" <+> ppr tys $$
2091 text "cos" <+> ppr cos )
2092 ASSERT2( tysCosFVsInScope,
2093 text "in_scope" <+> ppr in_scope $$
2094 text "tenv" <+> ppr tenv $$
2095 text "cenv" <+> ppr cenv $$
2096 text "tys" <+> ppr tys $$
2097 text "cos" <+> ppr cos $$
2098 text "needInScope" <+> ppr needInScope )
2099 a
2100 where
2101 substDomain = varEnvKeys tenv ++ varEnvKeys cenv
2102 needInScope = (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos)
2103 `delListFromUFM_Directly` substDomain
2104 tysCosFVsInScope = needInScope `varSetInScope` in_scope
2105
2106
2107 -- | Substitute within a 'Type'
2108 -- The substitution has to satisfy the invariants described in
2109 -- Note [The substitution invariant].
2110 substTy ::
2111 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2112 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2113 (?callStack :: CallStack) =>
2114 #endif
2115 TCvSubst -> Type -> Type
2116 substTy subst ty
2117 | isEmptyTCvSubst subst = ty
2118 | otherwise = checkValidSubst subst [ty] [] $ subst_ty subst ty
2119
2120 -- | Substitute within a 'Type' disabling the sanity checks.
2121 -- The problems that the sanity checks in substTy catch are described in
2122 -- Note [The substitution invariant].
2123 -- The goal of #11371 is to migrate all the calls of substTyUnchecked to
2124 -- substTy and remove this function. Please don't use in new code.
2125 substTyUnchecked :: TCvSubst -> Type -> Type
2126 substTyUnchecked subst ty
2127 | isEmptyTCvSubst subst = ty
2128 | otherwise = subst_ty subst ty
2129
2130 -- | Substitute within several 'Type's
2131 -- The substitution has to satisfy the invariants described in
2132 -- Note [The substitution invariant].
2133 substTys ::
2134 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2135 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2136 (?callStack :: CallStack) =>
2137 #endif
2138 TCvSubst -> [Type] -> [Type]
2139 substTys subst tys
2140 | isEmptyTCvSubst subst = tys
2141 | otherwise = checkValidSubst subst tys [] $ map (subst_ty subst) tys
2142
2143 -- | Substitute within several 'Type's disabling the sanity checks.
2144 -- The problems that the sanity checks in substTys catch are described in
2145 -- Note [The substitution invariant].
2146 -- The goal of #11371 is to migrate all the calls of substTysUnchecked to
2147 -- substTys and remove this function. Please don't use in new code.
2148 substTysUnchecked :: TCvSubst -> [Type] -> [Type]
2149 substTysUnchecked subst tys
2150 | isEmptyTCvSubst subst = tys
2151 | otherwise = map (subst_ty subst) tys
2152
2153 -- | Substitute within a 'ThetaType'
2154 -- The substitution has to satisfy the invariants described in
2155 -- Note [The substitution invariant].
2156 substTheta ::
2157 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2158 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2159 (?callStack :: CallStack) =>
2160 #endif
2161 TCvSubst -> ThetaType -> ThetaType
2162 substTheta = substTys
2163
2164 -- | Substitute within a 'ThetaType' disabling the sanity checks.
2165 -- The problems that the sanity checks in substTys catch are described in
2166 -- Note [The substitution invariant].
2167 -- The goal of #11371 is to migrate all the calls of substThetaUnchecked to
2168 -- substTheta and remove this function. Please don't use in new code.
2169 substThetaUnchecked :: TCvSubst -> ThetaType -> ThetaType
2170 substThetaUnchecked = substTysUnchecked
2171
2172
2173 subst_ty :: TCvSubst -> Type -> Type
2174 -- subst_ty is the main workhorse for type substitution
2175 --
2176 -- Note that the in_scope set is poked only if we hit a forall
2177 -- so it may often never be fully computed
2178 subst_ty subst ty
2179 = go ty
2180 where
2181 go (TyVarTy tv) = substTyVar subst tv
2182 go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
2183 -- The mkAppTy smart constructor is important
2184 -- we might be replacing (a Int), represented with App
2185 -- by [Int], represented with TyConApp
2186 go (TyConApp tc tys) = let args = map go tys
2187 in args `seqList` TyConApp tc args
2188 go (ForAllTy (Anon arg) res)
2189 = (ForAllTy $! (Anon $! go arg)) $! go res
2190 go (ForAllTy (Named tv vis) ty)
2191 = case substTyVarBndrUnchecked subst tv of
2192 (subst', tv') ->
2193 (ForAllTy $! ((Named $! tv') vis)) $!
2194 (subst_ty subst' ty)
2195 go (LitTy n) = LitTy $! n
2196 go (CastTy ty co) = (CastTy $! (go ty)) $! (subst_co subst co)
2197 go (CoercionTy co) = CoercionTy $! (subst_co subst co)
2198
2199 substTyVar :: TCvSubst -> TyVar -> Type
2200 substTyVar (TCvSubst _ tenv _) tv
2201 = ASSERT( isTyVar tv )
2202 case lookupVarEnv tenv tv of
2203 Just ty -> ty
2204 Nothing -> TyVarTy tv
2205
2206 substTyVars :: TCvSubst -> [TyVar] -> [Type]
2207 substTyVars subst = map $ substTyVar subst
2208
2209 lookupTyVar :: TCvSubst -> TyVar -> Maybe Type
2210 -- See Note [Extending the TCvSubst]
2211 lookupTyVar (TCvSubst _ tenv _) tv
2212 = ASSERT( isTyVar tv )
2213 lookupVarEnv tenv tv
2214
2215 -- | Substitute within a 'Coercion'
2216 -- The substitution has to satisfy the invariants described in
2217 -- Note [The substitution invariant].
2218 substCo ::
2219 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2220 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2221 (?callStack :: CallStack) =>
2222 #endif
2223 TCvSubst -> Coercion -> Coercion
2224 substCo subst co
2225 | isEmptyTCvSubst subst = co
2226 | otherwise = checkValidSubst subst [] [co] $ subst_co subst co
2227
2228 -- | Substitute within a 'Coercion' disabling sanity checks.
2229 -- The problems that the sanity checks in substCo catch are described in
2230 -- Note [The substitution invariant].
2231 -- The goal of #11371 is to migrate all the calls of substCoUnchecked to
2232 -- substCo and remove this function. Please don't use in new code.
2233 substCoUnchecked :: TCvSubst -> Coercion -> Coercion
2234 substCoUnchecked subst co
2235 | isEmptyTCvSubst subst = co
2236 | otherwise = subst_co subst co
2237
2238 -- | Substitute within several 'Coercion's
2239 -- The substitution has to satisfy the invariants described in
2240 -- Note [The substitution invariant].
2241 substCos ::
2242 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2243 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2244 (?callStack :: CallStack) =>
2245 #endif
2246 TCvSubst -> [Coercion] -> [Coercion]
2247 substCos subst cos
2248 | isEmptyTCvSubst subst = cos
2249 | otherwise = checkValidSubst subst [] cos $ map (subst_co subst) cos
2250
2251 subst_co :: TCvSubst -> Coercion -> Coercion
2252 subst_co subst co
2253 = go co
2254 where
2255 go_ty :: Type -> Type
2256 go_ty = subst_ty subst
2257
2258 go :: Coercion -> Coercion
2259 go (Refl r ty) = mkReflCo r $! go_ty ty
2260 go (TyConAppCo r tc args)= let args' = map go args
2261 in args' `seqList` mkTyConAppCo r tc args'
2262 go (AppCo co arg) = (mkAppCo $! go co) $! go arg
2263 go (ForAllCo tv kind_co co)
2264 = case substForAllCoBndrUnchecked subst tv kind_co of { (subst', tv', kind_co') ->
2265 ((mkForAllCo $! tv') $! kind_co') $! subst_co subst' co }
2266 go (CoVarCo cv) = substCoVar subst cv
2267 go (AxiomInstCo con ind cos) = mkAxiomInstCo con ind $! map go cos
2268 go (UnivCo p r t1 t2) = (((mkUnivCo $! go_prov p) $! r) $!
2269 (go_ty t1)) $! (go_ty t2)
2270 go (SymCo co) = mkSymCo $! (go co)
2271 go (TransCo co1 co2) = (mkTransCo $! (go co1)) $! (go co2)
2272 go (NthCo d co) = mkNthCo d $! (go co)
2273 go (LRCo lr co) = mkLRCo lr $! (go co)
2274 go (InstCo co arg) = (mkInstCo $! (go co)) $! go arg
2275 go (CoherenceCo co1 co2) = (mkCoherenceCo $! (go co1)) $! (go co2)
2276 go (KindCo co) = mkKindCo $! (go co)
2277 go (SubCo co) = mkSubCo $! (go co)
2278 go (AxiomRuleCo c cs) = let cs1 = map go cs
2279 in cs1 `seqList` AxiomRuleCo c cs1
2280
2281 go_prov UnsafeCoerceProv = UnsafeCoerceProv
2282 go_prov (PhantomProv kco) = PhantomProv (go kco)
2283 go_prov (ProofIrrelProv kco) = ProofIrrelProv (go kco)
2284 go_prov p@(PluginProv _) = p
2285 go_prov p@(HoleProv _) = p
2286 -- NB: this last case is a little suspicious, but we need it. Originally,
2287 -- there was a panic here, but it triggered from deeplySkolemise. Because
2288 -- we only skolemise tyvars that are manually bound, this operation makes
2289 -- sense, even over a coercion with holes.
2290
2291 substForAllCoBndr :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion)
2292 substForAllCoBndr subst
2293 = substForAllCoBndrCallback False (substCo subst) subst
2294
2295 -- | Like 'substForAllCoBndr', but disables sanity checks.
2296 -- The problems that the sanity checks in substCo catch are described in
2297 -- Note [The substitution invariant].
2298 -- The goal of #11371 is to migrate all the calls of substCoUnchecked to
2299 -- substCo and remove this function. Please don't use in new code.
2300 substForAllCoBndrUnchecked :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion)
2301 substForAllCoBndrUnchecked subst
2302 = substForAllCoBndrCallback False (substCoUnchecked subst) subst
2303
2304 -- See Note [Sym and ForAllCo]
2305 substForAllCoBndrCallback :: Bool -- apply sym to binder?
2306 -> (Coercion -> Coercion) -- transformation to kind co
2307 -> TCvSubst -> TyVar -> Coercion
2308 -> (TCvSubst, TyVar, Coercion)
2309 substForAllCoBndrCallback sym sco (TCvSubst in_scope tenv cenv)
2310 old_var old_kind_co
2311 = ( TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv
2312 , new_var, new_kind_co )
2313 where
2314 new_env | no_change && not sym = delVarEnv tenv old_var
2315 | sym = extendVarEnv tenv old_var $
2316 TyVarTy new_var `CastTy` new_kind_co
2317 | otherwise = extendVarEnv tenv old_var (TyVarTy new_var)
2318
2319 no_kind_change = isEmptyVarSet (tyCoVarsOfCo old_kind_co)
2320 no_change = no_kind_change && (new_var == old_var)
2321
2322 new_kind_co | no_kind_change = old_kind_co
2323 | otherwise = sco old_kind_co
2324
2325 Pair new_ki1 _ = coercionKind new_kind_co
2326
2327 new_var = uniqAway in_scope (setTyVarKind old_var new_ki1)
2328
2329 substCoVar :: TCvSubst -> CoVar -> Coercion
2330 substCoVar (TCvSubst _ _ cenv) cv
2331 = case lookupVarEnv cenv cv of
2332 Just co -> co
2333 Nothing -> CoVarCo cv
2334
2335 substCoVars :: TCvSubst -> [CoVar] -> [Coercion]
2336 substCoVars subst cvs = map (substCoVar subst) cvs
2337
2338 lookupCoVar :: TCvSubst -> Var -> Maybe Coercion
2339 lookupCoVar (TCvSubst _ _ cenv) v = lookupVarEnv cenv v
2340
2341 substTyVarBndr ::
2342 -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1
2343 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0)
2344 (?callStack :: CallStack) =>
2345 #endif
2346 TCvSubst -> TyVar -> (TCvSubst, TyVar)
2347 substTyVarBndr = substTyVarBndrCallback substTy
2348
2349 -- | Like 'substTyVarBndr' but disables sanity checks.
2350 -- The problems that the sanity checks in substTy catch are described in
2351 -- Note [The substitution invariant].
2352 -- The goal of #11371 is to migrate all the calls of substTyUnchecked to
2353 -- substTy and remove this function. Please don't use in new code.
2354 substTyVarBndrUnchecked :: TCvSubst -> TyVar -> (TCvSubst, TyVar)
2355 substTyVarBndrUnchecked = substTyVarBndrCallback substTyUnchecked
2356
2357 -- | Substitute a tyvar in a binding position, returning an
2358 -- extended subst and a new tyvar.
2359 substTyVarBndrCallback :: (TCvSubst -> Type -> Type) -- ^ the subst function
2360 -> TCvSubst -> TyVar -> (TCvSubst, TyVar)
2361 substTyVarBndrCallback subst_fn subst@(TCvSubst in_scope tenv cenv) old_var
2362 = ASSERT2( _no_capture, pprTvBndr old_var $$ pprTvBndr new_var $$ ppr subst )
2363 ASSERT( isTyVar old_var )
2364 (TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv, new_var)
2365 where
2366 new_env | no_change = delVarEnv tenv old_var
2367 | otherwise = extendVarEnv tenv old_var (TyVarTy new_var)
2368
2369 _no_capture = not (new_var `elemVarSet` tyCoVarsOfTypes (varEnvElts tenv))
2370 -- Assertion check that we are not capturing something in the substitution
2371
2372 old_ki = tyVarKind old_var
2373 no_kind_change = isEmptyVarSet (tyCoVarsOfType old_ki) -- verify that kind is closed
2374 no_change = no_kind_change && (new_var == old_var)
2375 -- no_change means that the new_var is identical in
2376 -- all respects to the old_var (same unique, same kind)
2377 -- See Note [Extending the TCvSubst]
2378 --
2379 -- In that case we don't need to extend the substitution
2380 -- to map old to new. But instead we must zap any
2381 -- current substitution for the variable. For example:
2382 -- (\x.e) with id_subst = [x |-> e']
2383 -- Here we must simply zap the substitution for x
2384
2385 new_var | no_kind_change = uniqAway in_scope old_var
2386 | otherwise = uniqAway in_scope $
2387 setTyVarKind old_var (subst_fn subst old_ki)
2388 -- The uniqAway part makes sure the new variable is not already in scope
2389
2390 substCoVarBndr :: TCvSubst -> CoVar -> (TCvSubst, CoVar)
2391 substCoVarBndr = substCoVarBndrCallback False substTy
2392
2393 substCoVarBndrCallback :: Bool -- apply "sym" to the covar?
2394 -> (TCvSubst -> Type -> Type)
2395 -> TCvSubst -> CoVar -> (TCvSubst, CoVar)
2396 substCoVarBndrCallback sym subst_fun subst@(TCvSubst in_scope tenv cenv) old_var
2397 = ASSERT( isCoVar old_var )
2398 (TCvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var)
2399 where
2400 -- When we substitute (co :: t1 ~ t2) we may get the identity (co :: t ~ t)
2401 -- In that case, mkCoVarCo will return a ReflCoercion, and
2402 -- we want to substitute that (not new_var) for old_var
2403 new_co = (if sym then mkSymCo else id) $ mkCoVarCo new_var
2404 no_kind_change = isEmptyVarSet (tyCoVarsOfTypes [t1, t2])
2405 no_change = new_var == old_var && not (isReflCo new_co) && no_kind_change
2406
2407 new_cenv | no_change = delVarEnv cenv old_var
2408 | otherwise = extendVarEnv cenv old_var new_co
2409
2410 new_var = uniqAway in_scope subst_old_var
2411 subst_old_var = mkCoVar (varName old_var) new_var_type
2412
2413 (_, _, t1, t2, role) = coVarKindsTypesRole old_var
2414 t1' = subst_fun subst t1
2415 t2' = subst_fun subst t2
2416 new_var_type = uncurry (mkCoercionType role) (if sym then (t2', t1') else (t1', t2'))
2417 -- It's important to do the substitution for coercions,
2418 -- because they can have free type variables
2419
2420 cloneTyVarBndr :: TCvSubst -> TyVar -> Unique -> (TCvSubst, TyVar)
2421 cloneTyVarBndr subst@(TCvSubst in_scope tv_env cv_env) tv uniq
2422 = ASSERT2( isTyVar tv, ppr tv ) -- I think it's only called on TyVars
2423 (TCvSubst (extendInScopeSet in_scope tv')
2424 (extendVarEnv tv_env tv (mkTyVarTy tv')) cv_env, tv')
2425 where
2426 old_ki = tyVarKind tv
2427 no_kind_change = isEmptyVarSet (tyCoVarsOfType old_ki) -- verify that kind is closed
2428
2429 tv1 | no_kind_change = tv
2430 | otherwise = setTyVarKind tv (substTy subst old_ki)
2431
2432 tv' = setVarUnique tv1 uniq
2433
2434 cloneTyVarBndrs :: TCvSubst -> [TyVar] -> UniqSupply -> (TCvSubst, [TyVar])
2435 cloneTyVarBndrs subst [] _usupply = (subst, [])
2436 cloneTyVarBndrs subst (t:ts) usupply = (subst'', tv:tvs)
2437 where
2438 (uniq, usupply') = takeUniqFromSupply usupply
2439 (subst' , tv ) = cloneTyVarBndr subst t uniq
2440 (subst'', tvs) = cloneTyVarBndrs subst' ts usupply'
2441
2442 {-
2443 %************************************************************************
2444 %* *
2445 Pretty-printing types
2446
2447 Defined very early because of debug printing in assertions
2448 %* *
2449 %************************************************************************
2450
2451 @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
2452 defined to use this. @pprParendType@ is the same, except it puts
2453 parens around the type, except for the atomic cases. @pprParendType@
2454 works just by setting the initial context precedence very high.
2455
2456 Note [Precedence in types]
2457 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2458 We don't keep the fixity of type operators in the operator. So the pretty printer
2459 operates the following precedene structre:
2460 Type constructor application binds more tightly than
2461 Operator applications which bind more tightly than
2462 Function arrow
2463
2464 So we might see a :+: T b -> c
2465 meaning (a :+: (T b)) -> c
2466
2467 Maybe operator applications should bind a bit less tightly?
2468
2469 Anyway, that's the current story, and it is used consistently for Type and HsType
2470 -}
2471
2472 data TyPrec -- See Note [Prededence in types]
2473 = TopPrec -- No parens
2474 | FunPrec -- Function args; no parens for tycon apps
2475 | TyOpPrec -- Infix operator
2476 | TyConPrec -- Tycon args; no parens for atomic
2477 deriving( Eq, Ord )
2478
2479 maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc
2480 maybeParen ctxt_prec inner_prec pretty
2481 | ctxt_prec < inner_prec = pretty
2482 | otherwise = parens pretty
2483
2484 ------------------
2485
2486 {-
2487 Note [Defaulting RuntimeRep variables]
2488 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2489
2490 RuntimeRep variables are considered by many (most?) users to be little more than
2491 syntactic noise. When the notion was introduced there was a signficant and
2492 understandable push-back from those with pedagogy in mind, which argued that
2493 RuntimeRep variables would throw a wrench into nearly any teach approach since
2494 they appear in even the lowly ($) function's type,
2495
2496 ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b
2497
2498 which is significantly less readable than its non RuntimeRep-polymorphic type of
2499
2500 ($) :: (a -> b) -> a -> b
2501
2502 Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell
2503 programs, so it makes little sense to make all users pay this syntactic
2504 overhead.
2505
2506 For this reason it was decided that we would hide RuntimeRep variables for now
2507 (see #11549). We do this by defaulting all type variables of kind RuntimeRep to
2508 PtrLiftedRep. This is done in a pass right before pretty-printing
2509 (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps)
2510 -}
2511
2512 -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g.
2513 --
2514 -- @
2515 -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r).
2516 -- (a -> b) -> a -> b
2517 -- @
2518 --
2519 -- turns in to,
2520 --
2521 -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @
2522 --
2523 -- We do this to prevent RuntimeRep variables from incurring a significant
2524 -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See
2525 -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion.
2526 --
2527 defaultRuntimeRepVars :: Type -> Type
2528 defaultRuntimeRepVars = defaultRuntimeRepVars' emptyVarSet
2529
2530 defaultRuntimeRepVars' :: TyVarSet -- ^ the binders which we should default
2531 -> Type -> Type
2532 -- TODO: Eventually we should just eliminate the Type pretty-printer
2533 -- entirely and simply use IfaceType; this task is tracked as #11660.
2534 defaultRuntimeRepVars' subs (ForAllTy (Named var vis) ty)
2535 | isRuntimeRepVar var =
2536 let subs' = extendVarSet subs var
2537 in defaultRuntimeRepVars' subs' ty
2538 | otherwise =
2539 let var' = var { varType = defaultRuntimeRepVars' subs (varType var) }
2540 in ForAllTy (Named var' vis) (defaultRuntimeRepVars' subs ty)
2541
2542 defaultRuntimeRepVars' subs (ForAllTy (Anon kind) ty) =
2543 ForAllTy (Anon $ defaultRuntimeRepVars' subs kind)
2544 (defaultRuntimeRepVars' subs ty)
2545
2546 defaultRuntimeRepVars' subs (TyVarTy var)
2547 | var `elemVarSet` subs = ptrRepLiftedTy
2548
2549 defaultRuntimeRepVars' subs (TyConApp tc args) =
2550 TyConApp tc $ map (defaultRuntimeRepVars' subs) args
2551
2552 defaultRuntimeRepVars' subs (AppTy x y) =
2553 defaultRuntimeRepVars' subs x `AppTy` defaultRuntimeRepVars' subs y
2554
2555 defaultRuntimeRepVars' subs (CastTy ty co) =
2556 CastTy (defaultRuntimeRepVars' subs ty) co
2557
2558 defaultRuntimeRepVars' _ other = other
2559
2560 eliminateRuntimeRep :: (Type -> SDoc) -> Type -> SDoc
2561 eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags ->
2562 if gopt Opt_PrintExplicitRuntimeReps dflags
2563 then f ty
2564 else f (defaultRuntimeRepVars ty)
2565
2566 pprType, pprParendType :: Type -> SDoc
2567 pprType ty = eliminateRuntimeRep (ppr_type TopPrec) ty
2568 pprParendType ty = eliminateRuntimeRep (ppr_type TyConPrec) ty
2569
2570 pprTyLit :: TyLit -> SDoc
2571 pprTyLit = ppr_tylit TopPrec
2572
2573 pprKind, pprParendKind :: Kind -> SDoc
2574 pprKind = pprType
2575 pprParendKind = pprParendType
2576
2577 ------------
2578 pprClassPred :: Class -> [Type] -> SDoc
2579 pprClassPred clas tys = pprTypeApp (classTyCon clas) tys
2580
2581 ------------
2582 pprTheta :: ThetaType -> SDoc
2583 pprTheta [pred] = ppr_type TopPrec pred -- I'm in two minds about this
2584 pprTheta theta = parens (sep (punctuate comma (map (ppr_type TopPrec) theta)))
2585
2586 pprThetaArrowTy :: ThetaType -> SDoc
2587 pprThetaArrowTy [] = empty
2588 pprThetaArrowTy [pred] = ppr_type TyOpPrec pred <+> darrow
2589 -- TyOpPrec: Num a => a -> a does not need parens
2590 -- bug (a :~: b) => a -> b currently does
2591 -- Trac # 9658
2592 pprThetaArrowTy preds = parens (fsep (punctuate comma (map (ppr_type TopPrec) preds)))
2593 <+> darrow
2594 -- Notice 'fsep' here rather that 'sep', so that
2595 -- type contexts don't get displayed in a giant column
2596 -- Rather than
2597 -- instance (Eq a,
2598 -- Eq b,
2599 -- Eq c,
2600 -- Eq d,
2601 -- Eq e,
2602 -- Eq f,
2603 -- Eq g,
2604 -- Eq h,
2605 -- Eq i,
2606 -- Eq j,
2607 -- Eq k,
2608 -- Eq l) =>
2609 -- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
2610 -- we get
2611 --
2612 -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i,
2613 -- Eq j, Eq k, Eq l) =>
2614 -- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
2615
2616 ------------------
2617 instance Outputable Type where
2618 ppr ty = pprType ty
2619
2620 instance Outputable TyLit where
2621 ppr = pprTyLit
2622
2623 ------------------
2624 -- OK, here's the main printer
2625
2626 ppr_type :: TyPrec -> Type -> SDoc
2627 ppr_type _ (TyVarTy tv) = ppr_tvar tv
2628
2629 ppr_type p (TyConApp tc tys) = pprTyTcApp p tc tys
2630 ppr_type p (LitTy l) = ppr_tylit p l
2631 ppr_type p ty@(ForAllTy {}) = ppr_forall_type p ty
2632
2633 ppr_type p (AppTy t1 t2)
2634 = if_print_coercions
2635 ppr_app_ty
2636 (case split_app_tys t1 [t2] of
2637 (CastTy head _, args) -> ppr_type p (mk_app_tys head args)
2638 _ -> ppr_app_ty)
2639 where
2640 ppr_app_ty = maybeParen p TyConPrec $
2641 ppr_type FunPrec t1 <+> ppr_type TyConPrec t2
2642
2643 split_app_tys (AppTy ty1 ty2) args = split_app_tys ty1 (ty2:args)
2644 split_app_tys head args = (head, args)
2645
2646 mk_app_tys (TyConApp tc tys1) tys2 = TyConApp tc (tys1 ++ tys2)
2647 mk_app_tys ty1 tys2 = foldl AppTy ty1 tys2
2648
2649 ppr_type p (CastTy ty co)
2650 = if_print_coercions
2651 (parens (ppr_type TopPrec ty <+> text "|>" <+> ppr co))
2652 (ppr_type p ty)
2653
2654 ppr_type _ (CoercionTy co)
2655 = if_print_coercions
2656 (parens (ppr co))
2657 (text "<>")
2658
2659 ppr_forall_type :: TyPrec -> Type -> SDoc
2660 ppr_forall_type p ty
2661 = maybeParen p FunPrec $
2662 sdocWithDynFlags $ \dflags ->
2663 ppr_sigma_type dflags True ty
2664 -- True <=> we always print the foralls on *nested* quantifiers
2665 -- Opt_PrintExplicitForalls only affects top-level quantifiers
2666
2667 ppr_tvar :: TyVar -> SDoc
2668 ppr_tvar tv -- Note [Infix type variables]
2669 = parenSymOcc (getOccName tv) (ppr tv)
2670
2671 ppr_tylit :: TyPrec -> TyLit -> SDoc
2672 ppr_tylit _ tl =
2673 case tl of
2674 NumTyLit n -> integer n
2675 StrTyLit s -> text (show s)
2676
2677 if_print_coercions :: SDoc -- if printing coercions
2678 -> SDoc -- otherwise
2679 -> SDoc
2680 if_print_coercions yes no
2681 = sdocWithDynFlags $ \dflags ->
2682 getPprStyle $ \style ->
2683 if gopt Opt_PrintExplicitCoercions dflags
2684 || dumpStyle style || debugStyle style
2685 then yes
2686 else no
2687
2688 -------------------
2689 ppr_sigma_type :: DynFlags
2690 -> Bool -- ^ True <=> Show the foralls unconditionally
2691 -> Type -> SDoc
2692 -- Suppose we have (forall a. Show a => forall b. a -> b). When we're not
2693 -- printing foralls, we want to drop both the (forall a) and the (forall b).
2694 -- This logic does so.
2695 ppr_sigma_type dflags False orig_ty
2696 | not (gopt Opt_PrintExplicitForalls dflags)
2697 , all (isEmptyVarSet . tyCoVarsOfType . binderType) named
2698 -- See Note [When to print foralls]
2699 = sep [ pprThetaArrowTy (map binderType ctxt)
2700 , pprArrowChain TopPrec (ppr_fun_tail tau) ]
2701 where
2702 (invis_bndrs, tau) = split [] orig_ty
2703 (named, ctxt) = partition isNamedBinder invis_bndrs
2704
2705 split acc (ForAllTy bndr ty) | isInvisibleBinder bndr = split (bndr:acc) ty
2706 split acc ty = (reverse acc, ty)
2707
2708 ppr_sigma_type _ _ ty
2709 = sep [ pprForAll bndrs
2710 , pprThetaArrowTy ctxt
2711 , pprArrowChain TopPrec (ppr_fun_tail tau) ]
2712 where
2713 (bndrs, rho) = split1 [] ty
2714 (ctxt, tau) = split2 [] rho
2715
2716 split1 bndrs (ForAllTy bndr@(Named {}) ty) = split1 (bndr:bndrs) ty
2717 split1 bndrs ty = (reverse bndrs, ty)
2718
2719 split2 ps (ForAllTy (Anon ty1) ty2) | isPredTy ty1 = split2 (ty1:ps) ty2
2720 split2 ps ty = (reverse ps, ty)
2721
2722 -- We don't want to lose synonyms, so we mustn't use splitFunTys here.
2723 ppr_fun_tail :: Type -> [SDoc]
2724 ppr_fun_tail (ForAllTy (Anon ty1) ty2)
2725 | not (isPredTy ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2
2726 ppr_fun_tail other_ty = [ppr_type TopPrec other_ty]
2727
2728 pprSigmaType :: Type -> SDoc
2729 pprSigmaType ty = sdocWithDynFlags $ \dflags ->
2730 eliminateRuntimeRep (ppr_sigma_type dflags False) ty
2731
2732 pprUserForAll :: [TyBinder] -> SDoc
2733 -- Print a user-level forall; see Note [When to print foralls]
2734 pprUserForAll bndrs
2735 = sdocWithDynFlags $ \dflags ->
2736 ppWhen (any bndr_has_kind_var bndrs || gopt Opt_PrintExplicitForalls dflags) $
2737 pprForAll bndrs
2738 where
2739 bndr_has_kind_var bndr
2740 = not (isEmptyVarSet (tyCoVarsOfType (binderType bndr)))
2741
2742 pprForAllImplicit :: [TyVar] -> SDoc
2743 pprForAllImplicit tvs = pprForAll (zipWith Named tvs (repeat Specified))
2744
2745 -- | Render the "forall ... ." or "forall ... ->" bit of a type.
2746 -- Do not pass in anonymous binders!
2747 pprForAll :: [TyBinder] -> SDoc
2748 pprForAll [] = empty
2749 pprForAll bndrs@(Named _ vis : _)
2750 = add_separator (forAllLit <+> doc) <+> pprForAll bndrs'
2751 where
2752 (bndrs', doc) = ppr_tv_bndrs bndrs vis
2753
2754 add_separator stuff = case vis of
2755 Visible -> stuff <+> arrow
2756 _inv -> stuff <> dot
2757 pprForAll bndrs = pprPanic "pprForAll: anonymous binder" (ppr bndrs)
2758
2759 pprTvBndrs :: [TyVar] -> SDoc
2760 pprTvBndrs tvs = sep (map pprTvBndr tvs)
2761
2762 -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@.
2763 -- Returns both the list of not-yet-rendered binders and the doc.
2764 -- No anonymous binders here!
2765 ppr_tv_bndrs :: [TyBinder]
2766 -> VisibilityFlag -- ^ visibility of the first binder in the list
2767 -> ([TyBinder], SDoc)
2768 ppr_tv_bndrs all_bndrs@(Named tv vis : bndrs) vis1
2769 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_tv_bndrs bndrs vis1
2770 pp_tv = sdocWithDynFlags $ \dflags ->
2771 if Invisible == vis &&
2772 gopt Opt_PrintExplicitForalls dflags
2773 then braces (pprTvBndrNoParens tv)
2774 else pprTvBndr tv
2775 in
2776 (bndrs', pp_tv <+> doc)
2777 | otherwise = (all_bndrs, empty)
2778 ppr_tv_bndrs [] _ = ([], empty)
2779 ppr_tv_bndrs bndrs _ = pprPanic "ppr_tv_bndrs: anonymous binder" (ppr bndrs)
2780
2781 pprTvBndr :: TyVar -> SDoc
2782 pprTvBndr tv
2783 | isLiftedTypeKind kind = ppr_tvar tv
2784 | otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind)
2785 where
2786 kind = tyVarKind tv
2787
2788 pprTvBndrNoParens :: TyVar -> SDoc
2789 pprTvBndrNoParens tv
2790 | isLiftedTypeKind kind = ppr_tvar tv
2791 | otherwise = ppr_tvar tv <+> dcolon <+> pprKind kind
2792 where
2793 kind = tyVarKind tv
2794
2795 instance Outputable TyBinder where
2796 ppr (Named v Visible) = ppr v
2797 ppr (Named v Specified) = char '@' <> ppr v
2798 ppr (Named v Invisible) = braces (ppr v)
2799 ppr (Anon ty) = text "[anon]" <+> ppr ty
2800
2801 instance Outputable VisibilityFlag where
2802 ppr Visible = text "[vis]"
2803 ppr Specified = text "[spec]"
2804 ppr Invisible = text "[invis]"
2805
2806 -----------------
2807 instance Outputable Coercion where -- defined here to avoid orphans
2808 ppr = pprCo
2809 instance Outputable LeftOrRight where
2810 ppr CLeft = text "Left"
2811 ppr CRight = text "Right"
2812
2813 {-
2814 Note [When to print foralls]
2815 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2816 Mostly we want to print top-level foralls when (and only when) the user specifies
2817 -fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses
2818 too much information; see Trac #9018.
2819
2820 So I'm trying out this rule: print explicit foralls if
2821 a) User specifies -fprint-explicit-foralls, or
2822 b) Any of the quantified type variables has a kind
2823 that mentions a kind variable
2824
2825 This catches common situations, such as a type siguature
2826 f :: m a
2827 which means
2828 f :: forall k. forall (m :: k->*) (a :: k). m a
2829 We really want to see both the "forall k" and the kind signatures
2830 on m and a. The latter comes from pprTvBndr.
2831
2832 Note [Infix type variables]
2833 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2834 With TypeOperators you can say
2835
2836 f :: (a ~> b) -> b
2837
2838 and the (~>) is considered a type variable. However, the type
2839 pretty-printer in this module will just see (a ~> b) as
2840
2841 App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
2842
2843 So it'll print the type in prefix form. To avoid confusion we must
2844 remember to parenthesise the operator, thus
2845
2846 (~>) a b -> b
2847
2848 See Trac #2766.
2849 -}
2850
2851 pprDataCons :: TyCon -> SDoc
2852 pprDataCons = sepWithVBars . fmap pprDataConWithArgs . tyConDataCons
2853 where
2854 sepWithVBars [] = empty
2855 sepWithVBars docs = sep (punctuate (space <> vbar) docs)
2856
2857 pprDataConWithArgs :: DataCon -> SDoc
2858 pprDataConWithArgs dc = sep [forAllDoc, thetaDoc, ppr dc <+> argsDoc]
2859 where
2860 (_univ_tvs, _ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig dc
2861 univ_bndrs = dataConUnivTyBinders dc
2862 ex_bndrs = dataConExTyBinders dc
2863 forAllDoc = pprUserForAll $ (filterEqSpec eq_spec univ_bndrs ++ ex_bndrs)
2864 thetaDoc = pprThetaArrowTy theta
2865 argsDoc = hsep (fmap pprParendType arg_tys)
2866
2867
2868 pprTypeApp :: TyCon -> [Type] -> SDoc
2869 pprTypeApp tc tys = pprTyTcApp TopPrec tc tys
2870 -- We have to use ppr on the TyCon (not its name)
2871 -- so that we get promotion quotes in the right place
2872
2873 pprTyTcApp :: TyPrec -> TyCon -> [Type] -> SDoc
2874 -- Used for types only; so that we can make a
2875 -- special case for type-level lists
2876 pprTyTcApp p tc tys
2877 | tc `hasKey` ipClassKey
2878 , [LitTy (StrTyLit n),ty] <- tys
2879 = maybeParen p FunPrec $
2880 char '?' <> ftext n <> text "::" <> ppr_type TopPrec ty
2881
2882 | tc `hasKey` consDataConKey
2883 , [_kind,ty1,ty2] <- tys
2884 = sdocWithDynFlags $ \dflags ->
2885 if gopt Opt_PrintExplicitKinds dflags then ppr_deflt
2886 else pprTyList p ty1 ty2
2887
2888 | not opt_PprStyle_Debug
2889 , tc `hasKey` errorMessageTypeErrorFamKey
2890 = text "(TypeError ...)" -- Suppress detail unles you _really_ want to see
2891
2892 | tc `hasKey` tYPETyConKey
2893 , [TyConApp ptr_rep []] <- tys
2894 , ptr_rep `hasKey` ptrRepLiftedDataConKey
2895 = unicodeSyntax (char '') (char '*')
2896
2897 | tc `hasKey` tYPETyConKey
2898 , [TyConApp ptr_rep []] <- tys
2899 , ptr_rep `hasKey` ptrRepUnliftedDataConKey
2900 = char '#'
2901
2902 | otherwise
2903 = ppr_deflt
2904 where
2905 ppr_deflt = pprTcAppTy p ppr_type tc tys
2906
2907 pprTcAppTy :: TyPrec -> (TyPrec -> Type -> SDoc) -> TyCon -> [Type] -> SDoc
2908 pprTcAppTy p pp tc tys
2909 = getPprStyle $ \style -> pprTcApp style id p pp tc tys
2910
2911 pprTcAppCo :: TyPrec -> (TyPrec -> Coercion -> SDoc)
2912 -> TyCon -> [Coercion] -> SDoc
2913 pprTcAppCo p pp tc cos
2914 = getPprStyle $ \style ->
2915 pprTcApp style (pFst . coercionKind) p pp tc cos
2916
2917 pprTcApp :: PprStyle
2918 -> (a -> Type) -> TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc
2919 -- Used for both types and coercions, hence polymorphism
2920 pprTcApp _ _ _ pp tc [ty]
2921 | tc `hasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty)
2922 | tc `hasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty)
2923
2924 pprTcApp style to_type p pp tc tys
2925 | not (debugStyle style)
2926 , Just sort <- tyConTuple_maybe tc
2927 , let arity = tyConArity tc
2928 , arity == length tys
2929 , let num_to_drop = case sort of UnboxedTuple -> arity `div` 2
2930 _ -> 0
2931 = pprTupleApp p pp tc sort (drop num_to_drop tys)
2932
2933 | not (debugStyle style)
2934 , Just dc <- isPromotedDataCon_maybe tc
2935 , let dc_tc = dataConTyCon dc
2936 , Just tup_sort <- tyConTuple_maybe dc_tc
2937 , let arity = tyConArity dc_tc -- E.g. 3 for (,,) k1 k2 k3 t1 t2 t3
2938 ty_args = drop arity tys -- Drop the kind args
2939 , ty_args `lengthIs` arity -- Result is saturated
2940 = pprPromotionQuote tc <>
2941 (tupleParens tup_sort $ pprWithCommas (pp TopPrec) ty_args)
2942
2943 | otherwise
2944 = sdocWithDynFlags $ \dflags ->
2945 pprTcApp_help to_type p pp tc tys dflags style
2946 where
2947
2948 pprTupleApp :: TyPrec -> (TyPrec -> a -> SDoc)
2949 -> TyCon -> TupleSort -> [a] -> SDoc
2950 -- Print a saturated tuple
2951 pprTupleApp p pp tc sort tys
2952 | null tys
2953 , ConstraintTuple <- sort
2954 = if opt_PprStyle_Debug then text "(%%)"
2955 else maybeParen p FunPrec $
2956 text "() :: Constraint"
2957 | otherwise
2958 = pprPromotionQuote tc <>
2959 tupleParens sort (pprWithCommas (pp TopPrec) tys)
2960
2961 pprTcApp_help :: (a -> Type) -> TyPrec -> (TyPrec -> a -> SDoc)
2962 -> TyCon -> [a] -> DynFlags -> PprStyle -> SDoc
2963 -- This one has accss to the DynFlags
2964 pprTcApp_help to_type p pp tc tys dflags style
2965 | is_equality
2966 = print_equality
2967
2968 | print_prefix
2969 = pprPrefixApp p pp_tc (map (pp TyConPrec) tys_wo_kinds)
2970
2971 | [ty1,ty2] <- tys_wo_kinds -- Infix, two arguments;
2972 -- we know nothing of precedence though
2973 = pprInfixApp p pp pp_tc ty1 ty2
2974
2975 | tc_name `hasKey` starKindTyConKey
2976 || tc_name `hasKey` unicodeStarKindTyConKey
2977 || tc_name `hasKey` unliftedTypeKindTyConKey
2978 = pp_tc -- Do not wrap *, # in parens
2979
2980 | otherwise
2981 = pprPrefixApp p (parens (pp_tc)) (map (pp TyConPrec) tys_wo_kinds)
2982 where
2983 tc_name = tyConName tc
2984
2985 is_equality = tc `hasKey` eqPrimTyConKey ||
2986 tc `hasKey` heqTyConKey ||
2987 tc `hasKey` eqReprPrimTyConKey ||
2988 tc `hasKey` eqTyConKey
2989 -- don't include Coercible here, which should be printed
2990 -- normally
2991
2992 -- This is all a bit ad-hoc, trying to print out the best representation
2993 -- of equalities. If you see a better design, go for it.
2994 print_equality = case either_op_msg of
2995 Left op ->
2996 sep [ parens (pp TyOpPrec ty1 <+> dcolon <+> pp TyOpPrec ki1)
2997 , op
2998 , parens (pp TyOpPrec ty2 <+> dcolon <+> pp TyOpPrec ki2)]
2999 Right msg ->
3000 msg
3001 where
3002 hetero_tc = tc `hasKey` eqPrimTyConKey
3003 || tc `hasKey` eqReprPrimTyConKey
3004 || tc `hasKey` heqTyConKey
3005
3006 print_kinds = gopt Opt_PrintExplicitKinds dflags
3007 print_eqs = gopt Opt_PrintEqualityRelations dflags ||
3008 dumpStyle style ||
3009 debugStyle style
3010
3011 (ki1, ki2, ty1, ty2)
3012 | hetero_tc
3013 , [k1, k2, t1, t2] <- tys
3014 = (k1, k2, t1, t2)
3015 | [k, t1, t2] <- tys -- we must have (~)
3016 = (k, k, t1, t2)
3017 | otherwise
3018 = pprPanic "print_equality" pp_tc
3019
3020 -- if "Left", print hetero equality; if "Right" just print that msg
3021 either_op_msg
3022 | print_eqs
3023 = Left pp_tc
3024
3025 | hetero_tc
3026 , print_kinds || not (to_type ki1 `eqType` to_type ki2)
3027 = Left $ if tc `hasKey` eqPrimTyConKey
3028 then text "~~"
3029 else pp_tc
3030
3031 | otherwise
3032 = Right $ if tc `hasKey` eqReprPrimTyConKey
3033 then text "Coercible" <+> (sep [ pp TyConPrec ty1
3034 , pp TyConPrec ty2 ])
3035 else sep [pp TyOpPrec ty1, text "~", pp TyOpPrec ty2]
3036
3037 print_prefix = not (isSymOcc (nameOccName tc_name))
3038 tys_wo_kinds = suppressInvisibles to_type dflags tc tys
3039 pp_tc = ppr tc
3040
3041 ------------------
3042 -- | Given a 'TyCon',and the args to which it is applied,
3043 -- suppress the args that are implicit
3044 suppressInvisibles :: (a -> Type) -> DynFlags -> TyCon -> [a] -> [a]
3045 suppressInvisibles to_type dflags tc xs
3046 | gopt Opt_PrintExplicitKinds dflags = xs
3047 | otherwise = snd $ partitionInvisibles tc to_type xs
3048
3049 ----------------
3050 pprTyList :: TyPrec -> Type -> Type -> SDoc
3051 -- Given a type-level list (t1 ': t2), see if we can print
3052 -- it in list notation [t1, ...].
3053 pprTyList p ty1 ty2
3054 = case gather ty2 of
3055 (arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma
3056 (map (ppr_type TopPrec) (ty1:arg_tys))))
3057 (arg_tys, Just tl) -> maybeParen p FunPrec $
3058 hang (ppr_type FunPrec ty1)
3059 2 (fsep [ colon <+> ppr_type FunPrec ty | ty <- arg_tys ++ [tl]])
3060 where
3061 gather :: Type -> ([Type], Maybe Type)
3062 -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn]
3063 -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl
3064 gather (TyConApp tc tys)
3065 | tc `hasKey` consDataConKey
3066 , [_kind, ty1,ty2] <- tys
3067 , (args, tl) <- gather ty2
3068 = (ty1:args, tl)
3069 | tc `hasKey` nilDataConKey
3070 = ([], Nothing)
3071 gather ty = ([], Just ty)
3072
3073 ----------------
3074 pprInfixApp :: TyPrec -> (TyPrec -> a -> SDoc) -> SDoc -> a -> a -> SDoc
3075 pprInfixApp p pp pp_tc ty1 ty2
3076 = maybeParen p TyOpPrec $
3077 sep [pp TyOpPrec ty1, pprInfixVar True pp_tc <+> pp TyOpPrec ty2]
3078
3079 pprPrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc
3080 pprPrefixApp p pp_fun pp_tys
3081 | null pp_tys = pp_fun
3082 | otherwise = maybeParen p TyConPrec $
3083 hang pp_fun 2 (sep pp_tys)
3084 ----------------
3085 pprArrowChain :: TyPrec -> [SDoc] -> SDoc
3086 -- pprArrowChain p [a,b,c] generates a -> b -> c
3087 pprArrowChain _ [] = empty
3088 pprArrowChain p (arg:args) = maybeParen p FunPrec $
3089 sep [arg, sep (map (arrow <+>) args)]
3090
3091 {-
3092 %************************************************************************
3093 %* *
3094 \subsection{TidyType}
3095 %* *
3096 %************************************************************************
3097 -}
3098
3099 -- | This tidies up a type for printing in an error message, or in
3100 -- an interface file.
3101 --
3102 -- It doesn't change the uniques at all, just the print names.
3103 tidyTyCoVarBndrs :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar])
3104 tidyTyCoVarBndrs env tvs = mapAccumL tidyTyCoVarBndr env tvs
3105
3106 tidyTyCoVarBndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar)
3107 tidyTyCoVarBndr tidy_env@(occ_env, subst) tyvar
3108 = case tidyOccName occ_env occ1 of
3109 (tidy', occ') -> ((tidy', subst'), tyvar')
3110 where
3111 subst' = extendVarEnv subst tyvar tyvar'
3112 tyvar' = setTyVarKind (setTyVarName tyvar name') kind'
3113 name' = tidyNameOcc name occ'
3114 kind' = tidyKind tidy_env (tyVarKind tyvar)
3115 where
3116 name = tyVarName tyvar
3117 occ = getOccName name
3118 -- System Names are for unification variables;
3119 -- when we tidy them we give them a trailing "0" (or 1 etc)
3120 -- so that they don't take precedence for the un-modified name
3121 -- Plus, indicating a unification variable in this way is a
3122 -- helpful clue for users
3123 occ1 | isSystemName name
3124 = if isTyVar tyvar
3125 then mkTyVarOcc (occNameString occ ++ "0")
3126 else mkVarOcc (occNameString occ ++ "0")
3127 | otherwise = occ
3128
3129 tidyTyBinder :: TidyEnv -> TyBinder -> (TidyEnv, TyBinder)
3130 tidyTyBinder tidy_env (Named tv vis)
3131 = (tidy_env', Named tv' vis)
3132 where
3133 (tidy_env', tv') = tidyTyCoVarBndr tidy_env tv
3134 tidyTyBinder tidy_env (Anon ty)
3135 = (tidy_env, Anon $ tidyType tidy_env ty)
3136
3137 tidyTyBinders :: TidyEnv -> [TyBinder] -> (TidyEnv, [TyBinder])
3138 tidyTyBinders = mapAccumL tidyTyBinder
3139
3140 ---------------
3141 tidyFreeTyCoVars :: TidyEnv -> TyCoVarSet -> TidyEnv
3142 -- ^ Add the free 'TyVar's to the env in tidy form,
3143 -- so that we can tidy the type they are free in
3144 tidyFreeTyCoVars (full_occ_env, var_env) tyvars
3145 = fst (tidyOpenTyCoVars (full_occ_env, var_env) (varSetElemsWellScoped tyvars))
3146
3147 ---------------
3148 tidyOpenTyCoVars :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar])
3149 tidyOpenTyCoVars env tyvars = mapAccumL tidyOpenTyCoVar env tyvars
3150
3151 ---------------
3152 tidyOpenTyCoVar :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar)
3153 -- ^ Treat a new 'TyCoVar' as a binder, and give it a fresh tidy name
3154 -- using the environment if one has not already been allocated. See
3155 -- also 'tidyTyCoVarBndr'
3156 tidyOpenTyCoVar env@(_, subst) tyvar
3157 = case lookupVarEnv subst tyvar of
3158 Just tyvar' -> (env, tyvar') -- Already substituted
3159 Nothing ->
3160 let env' = tidyFreeTyCoVars env (tyCoVarsOfType (tyVarKind tyvar)) in
3161 tidyTyCoVarBndr env' tyvar -- Treat it as a binder
3162
3163 ---------------
3164 tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar
3165 tidyTyVarOcc env@(_, subst) tv
3166 = case lookupVarEnv subst tv of
3167 Nothing -> updateTyVarKind (tidyType env) tv
3168 Just tv' -> tv'
3169
3170 ---------------
3171 tidyTypes :: TidyEnv -> [Type] -> [Type]
3172 tidyTypes env tys = map (tidyType env) tys
3173
3174 ---------------
3175 tidyType :: TidyEnv -> Type -> Type
3176 tidyType _ (LitTy n) = LitTy n
3177 tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv)
3178 tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys
3179 in args `seqList` TyConApp tycon args
3180 tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg)
3181 tidyType env (ForAllTy (Anon fun) arg)
3182 = (ForAllTy $! (Anon $! (tidyType env fun))) $! (tidyType env arg)
3183 tidyType env (ForAllTy (Named tv vis) ty)
3184 = (ForAllTy $! ((Named $! tvp) $! vis)) $! (tidyType envp ty)
3185 where
3186 (envp, tvp) = tidyTyCoVarBndr env tv
3187 tidyType env (CastTy ty co) = (CastTy $! tidyType env ty) $! (tidyCo env co)
3188 tidyType env (CoercionTy co) = CoercionTy $! (tidyCo env co)
3189
3190 ---------------
3191 -- | Grabs the free type variables, tidies them
3192 -- and then uses 'tidyType' to work over the type itself
3193 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
3194 tidyOpenTypes env tys
3195 = (env', tidyTypes (trimmed_occ_env, var_env) tys)
3196 where
3197 (env'@(_, var_env), tvs') = tidyOpenTyCoVars env $
3198 tyCoVarsOfTypesWellScoped tys
3199 trimmed_occ_env = initTidyOccEnv (map getOccName tvs')
3200 -- The idea here was that we restrict the new TidyEnv to the
3201 -- _free_ vars of the types, so that we don't gratuitously rename
3202 -- the _bound_ variables of the types.
3203
3204 ---------------
3205 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
3206 tidyOpenType env ty = let (env', [ty']) = tidyOpenTypes env [ty] in
3207 (env', ty')
3208
3209 ---------------
3210 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
3211 tidyTopType :: Type -> Type
3212 tidyTopType ty = tidyType emptyTidyEnv ty
3213
3214 ---------------
3215 tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
3216 tidyOpenKind = tidyOpenType
3217
3218 tidyKind :: TidyEnv -> Kind -> Kind
3219 tidyKind = tidyType
3220
3221 ----------------
3222 tidyCo :: TidyEnv -> Coercion -> Coercion
3223 tidyCo env@(_, subst) co
3224 = go co
3225 where
3226 go (Refl r ty) = Refl r (tidyType env ty)
3227 go (TyConAppCo r tc cos) = let args = map go cos
3228 in args `seqList` TyConAppCo r tc args
3229 go (AppCo co1 co2) = (AppCo $! go co1) $! go co2
3230 go (ForAllCo tv h co) = ((ForAllCo $! tvp) $! (go h)) $! (tidyCo envp co)
3231 where (envp, tvp) = tidyTyCoVarBndr env tv
3232 -- the case above duplicates a bit of work in tidying h and the kind
3233 -- of tv. But the alternative is to use coercionKind, which seems worse.
3234 go (CoVarCo cv) = case lookupVarEnv subst cv of
3235 Nothing -> CoVarCo cv
3236 Just cv' -> CoVarCo cv'
3237 go (AxiomInstCo con ind cos) = let args = map go cos
3238 in args `seqList` AxiomInstCo con ind args
3239 go (UnivCo p r t1 t2) = (((UnivCo $! (go_prov p)) $! r) $!
3240 tidyType env t1) $! tidyType env t2
3241 go (SymCo co) = SymCo $! go co
3242 go (TransCo co1 co2) = (TransCo $! go co1) $! go co2
3243 go (NthCo d co) = NthCo d $! go co
3244 go (LRCo lr co) = LRCo lr $! go co
3245 go (InstCo co ty) = (InstCo $! go co) $! go ty
3246 go (CoherenceCo co1 co2) = (CoherenceCo $! go co1) $! go co2
3247 go (KindCo co) = KindCo $! go co
3248 go (SubCo co) = SubCo $! go co
3249 go (AxiomRuleCo ax cos) = let cos1 = tidyCos env cos
3250 in cos1 `seqList` AxiomRuleCo ax cos1
3251
3252 go_prov UnsafeCoerceProv = UnsafeCoerceProv
3253 go_prov (PhantomProv co) = PhantomProv (go co)
3254 go_prov (ProofIrrelProv co) = ProofIrrelProv (go co)
3255 go_prov p@(PluginProv _) = p
3256 go_prov p@(HoleProv _) = p
3257
3258 tidyCos :: TidyEnv -> [Coercion] -> [Coercion]
3259 tidyCos env = map (tidyCo env)