8a9cf0eac6a0c1c13ba12efbb2014ac783e8d707
[ghc-hetmet.git] / compiler / types / Type.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1998
4 %
5
6 Type - public interface
7
8 \begin{code}
9 -- The above warning supression flag is a temporary kludge.
10 -- While working on this module you are encouraged to remove it and fix
11 -- any warnings in the module. See
12 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
13 -- for details
14
15 -- | Main functions for manipulating types and type-related things
16 module Type (
17         -- Note some of this is just re-exports from TyCon..
18
19         -- * Main data types representing Types
20         -- $type_classification
21         
22         -- $representation_types
23         TyThing(..), Type, PredType(..), ThetaType,
24
25         -- ** Constructing and deconstructing types
26         mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe,
27
28         mkAppTy, mkAppTys, splitAppTy, splitAppTys, 
29         splitAppTy_maybe, repSplitAppTy_maybe,
30
31         mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, 
32         splitFunTys, splitFunTysN,
33         funResultTy, funArgTy, zipFunTys,
34
35         mkTyConApp, mkTyConTy, 
36         tyConAppTyCon, tyConAppArgs, 
37         splitTyConApp_maybe, splitTyConApp, 
38
39         mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
40         applyTy, applyTys, applyTysD, isForAllTy, dropForAlls,
41         
42         -- (Newtypes)
43         newTyConInstRhs, carefullySplitNewType_maybe,
44         
45         -- (Type families)
46         tyFamInsts, predFamInsts,
47
48         -- (Source types)
49         mkPredTy, mkPredTys, mkFamilyTyConApp, isEqPred,
50
51         -- ** Common type constructors
52         funTyCon,
53
54         -- ** Predicates on types
55         isTyVarTy, isFunTy, isDictTy,
56
57         -- (Lifting and boxity)
58         isUnLiftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
59         isPrimitiveType, isStrictType, isStrictPred, 
60
61         -- * Main data types representing Kinds
62         -- $kind_subtyping
63         Kind, SimpleKind, KindVar,
64         
65         -- ** Common Kinds and SuperKinds
66         liftedTypeKind, unliftedTypeKind, openTypeKind,
67         argTypeKind, ubxTupleKind,
68
69         tySuperKind, coSuperKind, 
70
71         -- ** Common Kind type constructors
72         liftedTypeKindTyCon, openTypeKindTyCon, unliftedTypeKindTyCon,
73         argTypeKindTyCon, ubxTupleKindTyCon,
74
75         -- * Type free variables
76         tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
77         expandTypeSynonyms,
78
79         -- * Tidying type related things up for printing
80         tidyType,      tidyTypes,
81         tidyOpenType,  tidyOpenTypes,
82         tidyTyVarBndr, tidyFreeTyVars,
83         tidyOpenTyVar, tidyOpenTyVars,
84         tidyTopType,   tidyPred,
85         tidyKind,
86
87         -- * Type comparison
88         coreEqType, coreEqType2,
89         tcEqType, tcEqTypes, tcCmpType, tcCmpTypes, 
90         tcEqPred, tcEqPredX, tcCmpPred, tcEqTypeX, tcPartOfType, tcPartOfPred,
91
92         -- * Forcing evaluation of types
93         seqType, seqTypes,
94
95         -- * Other views onto Types
96         coreView, tcView, kindView,
97
98         repType, 
99
100         -- * Type representation for the code generator
101         PrimRep(..),
102
103         typePrimRep, predTypeRep,
104
105         -- * Main type substitution data types
106         TvSubstEnv,     -- Representation widely visible
107         TvSubst(..),    -- Representation visible to a few friends
108         
109         -- ** Manipulating type substitutions
110         emptyTvSubstEnv, emptyTvSubst,
111         
112         mkTvSubst, mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
113         getTvSubstEnv, setTvSubstEnv, zapTvSubstEnv, getTvInScope, 
114         extendTvInScope, extendTvInScopeList,
115         extendTvSubst, extendTvSubstList, isInScope, composeTvSubst, zipTyEnv,
116         isEmptyTvSubst,
117
118         -- ** Performing substitution on types
119         substTy, substTys, substTyWith, substTysWith, substTheta, 
120         substPred, substTyVar, substTyVars, substTyVarBndr, deShadowTy, lookupTyVar,
121
122         -- * Pretty-printing
123         pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing, pprForAll,
124         pprPred, pprEqPred, pprTheta, pprThetaArrow, pprClassPred, pprKind, pprParendKind,
125         
126         pprSourceTyCon
127     ) where
128
129 #include "HsVersions.h"
130
131 -- We import the representation and primitive functions from TypeRep.
132 -- Many things are reexported, but not the representation!
133
134 import TypeRep
135
136 -- friends:
137 import Var
138 import VarEnv
139 import VarSet
140
141 import Name
142 import Class
143 import TyCon
144
145 -- others
146 import StaticFlags
147 import Util
148 import Outputable
149 import FastString
150
151 import Data.List
152 import Data.Maybe       ( isJust )
153 \end{code}
154
155 \begin{code}
156 -- $type_classification
157 -- #type_classification#
158 -- 
159 -- Types are one of:
160 -- 
161 -- [Unboxed]            Iff its representation is other than a pointer
162 --                      Unboxed types are also unlifted.
163 -- 
164 -- [Lifted]             Iff it has bottom as an element.
165 --                      Closures always have lifted types: i.e. any
166 --                      let-bound identifier in Core must have a lifted
167 --                      type. Operationally, a lifted object is one that
168 --                      can be entered.
169 --                      Only lifted types may be unified with a type variable.
170 -- 
171 -- [Algebraic]          Iff it is a type with one or more constructors, whether
172 --                      declared with @data@ or @newtype@.
173 --                      An algebraic type is one that can be deconstructed
174 --                      with a case expression. This is /not/ the same as 
175 --                      lifted types, because we also include unboxed
176 --                      tuples in this classification.
177 -- 
178 -- [Data]               Iff it is a type declared with @data@, or a boxed tuple.
179 -- 
180 -- [Primitive]          Iff it is a built-in type that can't be expressed in Haskell.
181 -- 
182 -- Currently, all primitive types are unlifted, but that's not necessarily
183 -- the case: for example, @Int@ could be primitive.
184 -- 
185 -- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
186 -- but unlifted (such as @ByteArray#@).  The only primitive types that we
187 -- classify as algebraic are the unboxed tuples.
188 -- 
189 -- Some examples of type classifications that may make this a bit clearer are:
190 -- 
191 -- @
192 -- Type         primitive       boxed           lifted          algebraic
193 -- -----------------------------------------------------------------------------
194 -- Int#         Yes             No              No              No
195 -- ByteArray#   Yes             Yes             No              No
196 -- (\# a, b \#)   Yes             No              No              Yes
197 -- (  a, b  )   No              Yes             Yes             Yes
198 -- [a]          No              Yes             Yes             Yes
199 -- @
200
201 -- $representation_types
202 -- A /source type/ is a type that is a separate type as far as the type checker is
203 -- concerned, but which has a more low-level representation as far as Core-to-Core
204 -- passes and the rest of the back end is concerned. Notably, 'PredTy's are removed
205 -- from the representation type while they do exist in the source types.
206 --
207 -- You don't normally have to worry about this, as the utility functions in
208 -- this module will automatically convert a source into a representation type
209 -- if they are spotted, to the best of it's abilities. If you don't want this
210 -- to happen, use the equivalent functions from the "TcType" module.
211 \end{code}
212
213 %************************************************************************
214 %*                                                                      *
215                 Type representation
216 %*                                                                      *
217 %************************************************************************
218
219 \begin{code}
220 {-# INLINE coreView #-}
221 coreView :: Type -> Maybe Type
222 -- ^ In Core, we \"look through\" non-recursive newtypes and 'PredTypes': this
223 -- function tries to obtain a different view of the supplied type given this
224 --
225 -- Strips off the /top layer only/ of a type to give 
226 -- its underlying representation type. 
227 -- Returns Nothing if there is nothing to look through.
228 --
229 -- In the case of @newtype@s, it returns one of:
230 --
231 -- 1) A vanilla 'TyConApp' (recursive newtype, or non-saturated)
232 -- 
233 -- 2) The newtype representation (otherwise), meaning the
234 --    type written in the RHS of the newtype declaration,
235 --    which may itself be a newtype
236 --
237 -- For example, with:
238 --
239 -- > newtype R = MkR S
240 -- > newtype S = MkS T
241 -- > newtype T = MkT (T -> T)
242 --
243 -- 'expandNewTcApp' on:
244 --
245 --  * @R@ gives @Just S@
246 --  * @S@ gives @Just T@
247 --  * @T@ gives @Nothing@ (no expansion)
248
249 -- By being non-recursive and inlined, this case analysis gets efficiently
250 -- joined onto the case analysis that the caller is already doing
251 coreView (PredTy p)
252   | isEqPred p             = Nothing
253   | otherwise              = Just (predTypeRep p)
254 coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- coreExpandTyCon_maybe tc tys 
255                            = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
256                                 -- Its important to use mkAppTys, rather than (foldl AppTy),
257                                 -- because the function part might well return a 
258                                 -- partially-applied type constructor; indeed, usually will!
259 coreView _                 = Nothing
260
261
262
263 -----------------------------------------------
264 {-# INLINE tcView #-}
265 tcView :: Type -> Maybe Type
266 -- ^ Similar to 'coreView', but for the type checker, which just looks through synonyms
267 tcView (TyConApp tc tys) | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys 
268                          = Just (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
269 tcView _                 = Nothing
270
271 -----------------------------------------------
272 expandTypeSynonyms :: Type -> Type
273 -- ^ Expand out all type synonyms.  Actually, it'd suffice to expand out
274 -- just the ones that discard type variables (e.g.  type Funny a = Int)
275 -- But we don't know which those are currently, so we just expand all.
276 expandTypeSynonyms ty 
277   = go ty
278   where
279     go (TyConApp tc tys)
280       | Just (tenv, rhs, tys') <- tcExpandTyCon_maybe tc tys 
281       = go (mkAppTys (substTy (mkTopTvSubst tenv) rhs) tys')
282       | otherwise
283       = TyConApp tc (map go tys)
284     go (TyVarTy tv)    = TyVarTy tv
285     go (AppTy t1 t2)   = AppTy (go t1) (go t2)
286     go (FunTy t1 t2)   = FunTy (go t1) (go t2)
287     go (ForAllTy tv t) = ForAllTy tv (go t)
288     go (PredTy p)      = PredTy (go_pred p)
289
290     go_pred (ClassP c ts)  = ClassP c (map go ts)
291     go_pred (IParam ip t)  = IParam ip (go t)
292     go_pred (EqPred t1 t2) = EqPred (go t1) (go t2)
293
294 -----------------------------------------------
295 {-# INLINE kindView #-}
296 kindView :: Kind -> Maybe Kind
297 -- ^ Similar to 'coreView' or 'tcView', but works on 'Kind's
298
299 -- For the moment, we don't even handle synonyms in kinds
300 kindView _            = Nothing
301 \end{code}
302
303
304 %************************************************************************
305 %*                                                                      *
306 \subsection{Constructor-specific functions}
307 %*                                                                      *
308 %************************************************************************
309
310
311 ---------------------------------------------------------------------
312                                 TyVarTy
313                                 ~~~~~~~
314 \begin{code}
315 mkTyVarTy  :: TyVar   -> Type
316 mkTyVarTy  = TyVarTy
317
318 mkTyVarTys :: [TyVar] -> [Type]
319 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
320
321 -- | Attempts to obtain the type variable underlying a 'Type', and panics with the
322 -- given message if this is not a type variable type. See also 'getTyVar_maybe'
323 getTyVar :: String -> Type -> TyVar
324 getTyVar msg ty = case getTyVar_maybe ty of
325                     Just tv -> tv
326                     Nothing -> panic ("getTyVar: " ++ msg)
327
328 isTyVarTy :: Type -> Bool
329 isTyVarTy ty = isJust (getTyVar_maybe ty)
330
331 -- | Attempts to obtain the type variable underlying a 'Type'
332 getTyVar_maybe :: Type -> Maybe TyVar
333 getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
334 getTyVar_maybe (TyVarTy tv)                 = Just tv  
335 getTyVar_maybe _                            = Nothing
336
337 \end{code}
338
339
340 ---------------------------------------------------------------------
341                                 AppTy
342                                 ~~~~~
343 We need to be pretty careful with AppTy to make sure we obey the 
344 invariant that a TyConApp is always visibly so.  mkAppTy maintains the
345 invariant: use it.
346
347 \begin{code}
348 -- | Applies a type to another, as in e.g. @k a@
349 mkAppTy :: Type -> Type -> Type
350 mkAppTy orig_ty1 orig_ty2
351   = mk_app orig_ty1
352   where
353     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
354     mk_app _                 = AppTy orig_ty1 orig_ty2
355         -- Note that the TyConApp could be an 
356         -- under-saturated type synonym.  GHC allows that; e.g.
357         --      type Foo k = k a -> k a
358         --      type Id x = x
359         --      foo :: Foo Id -> Foo Id
360         --
361         -- Here Id is partially applied in the type sig for Foo,
362         -- but once the type synonyms are expanded all is well
363
364 mkAppTys :: Type -> [Type] -> Type
365 mkAppTys orig_ty1 []        = orig_ty1
366         -- This check for an empty list of type arguments
367         -- avoids the needless loss of a type synonym constructor.
368         -- For example: mkAppTys Rational []
369         --   returns to (Ratio Integer), which has needlessly lost
370         --   the Rational part.
371 mkAppTys orig_ty1 orig_tys2
372   = mk_app orig_ty1
373   where
374     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
375                                 -- mkTyConApp: see notes with mkAppTy
376     mk_app _                 = foldl AppTy orig_ty1 orig_tys2
377
378 -------------
379 splitAppTy_maybe :: Type -> Maybe (Type, Type)
380 -- ^ Attempt to take a type application apart, whether it is a
381 -- function, type constructor, or plain type application. Note
382 -- that type family applications are NEVER unsaturated by this!
383 splitAppTy_maybe ty | Just ty' <- coreView ty
384                     = splitAppTy_maybe ty'
385 splitAppTy_maybe ty = repSplitAppTy_maybe ty
386
387 -------------
388 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
389 -- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that 
390 -- any Core view stuff is already done
391 repSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
392 repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
393 repSplitAppTy_maybe (TyConApp tc tys) 
394   | isDecomposableTyCon tc || length tys > tyConArity tc 
395   = case snocView tys of       -- never create unsaturated type family apps
396       Just (tys', ty') -> Just (TyConApp tc tys', ty')
397       Nothing          -> Nothing
398 repSplitAppTy_maybe _other = Nothing
399 -------------
400 splitAppTy :: Type -> (Type, Type)
401 -- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
402 -- and panics if this is not possible
403 splitAppTy ty = case splitAppTy_maybe ty of
404                         Just pr -> pr
405                         Nothing -> panic "splitAppTy"
406
407 -------------
408 splitAppTys :: Type -> (Type, [Type])
409 -- ^ Recursively splits a type as far as is possible, leaving a residual
410 -- type being applied to and the type arguments applied to it. Never fails,
411 -- even if that means returning an empty list of type applications.
412 splitAppTys ty = split ty ty []
413   where
414     split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
415     split _       (AppTy ty arg)        args = split ty ty (arg:args)
416     split _       (TyConApp tc tc_args) args
417       = let -- keep type families saturated
418             n | isDecomposableTyCon tc = 0
419               | otherwise              = tyConArity tc
420             (tc_args1, tc_args2) = splitAt n tc_args
421         in
422         (TyConApp tc tc_args1, tc_args2 ++ args)
423     split _       (FunTy ty1 ty2)       args = ASSERT( null args )
424                                                (TyConApp funTyCon [], [ty1,ty2])
425     split orig_ty _                     args = (orig_ty, args)
426
427 \end{code}
428
429
430 ---------------------------------------------------------------------
431                                 FunTy
432                                 ~~~~~
433
434 \begin{code}
435 mkFunTy :: Type -> Type -> Type
436 -- ^ Creates a function type from the given argument and result type
437 mkFunTy arg@(PredTy (EqPred {})) res = ForAllTy (mkWildCoVar arg) res
438 mkFunTy arg                      res = FunTy    arg               res
439
440 mkFunTys :: [Type] -> Type -> Type
441 mkFunTys tys ty = foldr mkFunTy ty tys
442
443 isFunTy :: Type -> Bool 
444 isFunTy ty = isJust (splitFunTy_maybe ty)
445
446 splitFunTy :: Type -> (Type, Type)
447 -- ^ Attempts to extract the argument and result types from a type, and
448 -- panics if that is not possible. See also 'splitFunTy_maybe'
449 splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
450 splitFunTy (FunTy arg res)   = (arg, res)
451 splitFunTy other             = pprPanic "splitFunTy" (ppr other)
452
453 splitFunTy_maybe :: Type -> Maybe (Type, Type)
454 -- ^ Attempts to extract the argument and result types from a type
455 splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
456 splitFunTy_maybe (FunTy arg res)   = Just (arg, res)
457 splitFunTy_maybe _                 = Nothing
458
459 splitFunTys :: Type -> ([Type], Type)
460 splitFunTys ty = split [] ty ty
461   where
462     split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
463     split args _       (FunTy arg res)   = split (arg:args) res res
464     split args orig_ty _                 = (reverse args, orig_ty)
465
466 splitFunTysN :: Int -> Type -> ([Type], Type)
467 -- ^ Split off exactly the given number argument types, and panics if that is not possible
468 splitFunTysN 0 ty = ([], ty)
469 splitFunTysN n ty = case splitFunTy ty of { (arg, res) ->
470                     case splitFunTysN (n-1) res of { (args, res) ->
471                     (arg:args, res) }}
472
473 -- | Splits off argument types from the given type and associating
474 -- them with the things in the input list from left to right. The
475 -- final result type is returned, along with the resulting pairs of
476 -- objects and types, albeit with the list of pairs in reverse order.
477 -- Panics if there are not enough argument types for the input list.
478 zipFunTys :: Outputable a => [a] -> Type -> ([(a, Type)], Type)
479 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
480   where
481     split acc []     nty _                 = (reverse acc, nty)
482     split acc xs     nty ty 
483           | Just ty' <- coreView ty        = split acc xs nty ty'
484     split acc (x:xs) _   (FunTy arg res)   = split ((x,arg):acc) xs res res
485     split _   _      _   _                 = pprPanic "zipFunTys" (ppr orig_xs <+> ppr orig_ty)
486     
487 funResultTy :: Type -> Type
488 -- ^ Extract the function result type and panic if that is not possible
489 funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
490 funResultTy (FunTy _arg res)  = res
491 funResultTy ty                = pprPanic "funResultTy" (ppr ty)
492
493 funArgTy :: Type -> Type
494 -- ^ Extract the function argument type and panic if that is not possible
495 funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
496 funArgTy (FunTy arg _res)  = arg
497 funArgTy ty                = pprPanic "funArgTy" (ppr ty)
498 \end{code}
499
500 ---------------------------------------------------------------------
501                                 TyConApp
502                                 ~~~~~~~~
503
504 \begin{code}
505 -- | A key function: builds a 'TyConApp' or 'FunTy' as apppropriate to its arguments.
506 -- Applies its arguments to the constructor from left to right
507 mkTyConApp :: TyCon -> [Type] -> Type
508 mkTyConApp tycon tys
509   | isFunTyCon tycon, [ty1,ty2] <- tys
510   = FunTy ty1 ty2
511
512   | otherwise
513   = TyConApp tycon tys
514
515 -- | Create the plain type constructor type which has been applied to no type arguments at all.
516 mkTyConTy :: TyCon -> Type
517 mkTyConTy tycon = mkTyConApp tycon []
518
519 -- splitTyConApp "looks through" synonyms, because they don't
520 -- mean a distinct type, but all other type-constructor applications
521 -- including functions are returned as Just ..
522
523 -- | The same as @fst . splitTyConApp@
524 tyConAppTyCon :: Type -> TyCon
525 tyConAppTyCon ty = fst (splitTyConApp ty)
526
527 -- | The same as @snd . splitTyConApp@
528 tyConAppArgs :: Type -> [Type]
529 tyConAppArgs ty = snd (splitTyConApp ty)
530
531 -- | Attempts to tease a type apart into a type constructor and the application
532 -- of a number of arguments to that constructor. Panics if that is not possible.
533 -- See also 'splitTyConApp_maybe'
534 splitTyConApp :: Type -> (TyCon, [Type])
535 splitTyConApp ty = case splitTyConApp_maybe ty of
536                         Just stuff -> stuff
537                         Nothing    -> pprPanic "splitTyConApp" (ppr ty)
538
539 -- | Attempts to tease a type apart into a type constructor and the application
540 -- of a number of arguments to that constructor
541 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
542 splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
543 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
544 splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
545 splitTyConApp_maybe _                 = Nothing
546
547 newTyConInstRhs :: TyCon -> [Type] -> Type
548 -- ^ Unwrap one 'layer' of newtype on a type constructor and its arguments, using an 
549 -- eta-reduced version of the @newtype@ if possible
550 newTyConInstRhs tycon tys 
551     = ASSERT2( equalLength tvs tys1, ppr tycon $$ ppr tys $$ ppr tvs )
552       mkAppTys (substTyWith tvs tys1 ty) tys2
553   where
554     (tvs, ty)    = newTyConEtadRhs tycon
555     (tys1, tys2) = splitAtList tvs tys
556 \end{code}
557
558
559 ---------------------------------------------------------------------
560                                 SynTy
561                                 ~~~~~
562
563 Notes on type synonyms
564 ~~~~~~~~~~~~~~~~~~~~~~
565 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
566 to return type synonyms whereever possible. Thus
567
568         type Foo a = a -> a
569
570 we want 
571         splitFunTys (a -> Foo a) = ([a], Foo a)
572 not                                ([a], a -> a)
573
574 The reason is that we then get better (shorter) type signatures in 
575 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
576
577
578 Note [Expanding newtypes]
579 ~~~~~~~~~~~~~~~~~~~~~~~~~
580 When expanding a type to expose a data-type constructor, we need to be
581 careful about newtypes, lest we fall into an infinite loop. Here are
582 the key examples:
583
584   newtype Id  x = MkId x
585   newtype Fix f = MkFix (f (Fix f))
586   newtype T     = MkT (T -> T) 
587   
588   Type           Expansion
589  --------------------------
590   T              T -> T
591   Fix Maybe      Maybe (Fix Maybe)
592   Id (Id Int)    Int
593   Fix Id         NO NO NO
594
595 Notice that we can expand T, even though it's recursive.
596 And we can expand Id (Id Int), even though the Id shows up
597 twice at the outer level.  
598
599 So, when expanding, we keep track of when we've seen a recursive
600 newtype at outermost level; and bale out if we see it again.
601
602
603                 Representation types
604                 ~~~~~~~~~~~~~~~~~~~~
605
606 \begin{code}
607 -- | Looks through:
608 --
609 --      1. For-alls
610 --      2. Synonyms
611 --      3. Predicates
612 --      4. All newtypes, including recursive ones, but not newtype families
613 --
614 -- It's useful in the back end of the compiler.
615 repType :: Type -> Type
616 -- Only applied to types of kind *; hence tycons are saturated
617 repType ty
618   = go [] ty
619   where
620     go :: [TyCon] -> Type -> Type
621     go rec_nts ty | Just ty' <- coreView ty     -- Expand synonyms
622         = go rec_nts ty'        
623
624     go rec_nts (ForAllTy _ ty)                  -- Look through foralls
625         = go rec_nts ty
626
627     go rec_nts (TyConApp tc tys)                -- Expand newtypes
628       | Just (rec_nts', ty') <- carefullySplitNewType_maybe rec_nts tc tys
629       = go rec_nts' ty'
630
631     go _ ty = ty
632
633
634 carefullySplitNewType_maybe :: [TyCon] -> TyCon -> [Type] -> Maybe ([TyCon],Type)
635 -- Return the representation of a newtype, unless 
636 -- we've seen it already: see Note [Expanding newtypes]
637 carefullySplitNewType_maybe rec_nts tc tys
638   | isNewTyCon tc
639   , not (tc `elem` rec_nts)  = Just (rec_nts', newTyConInstRhs tc tys)
640   | otherwise                = Nothing
641   where
642     rec_nts' | isRecursiveTyCon tc = tc:rec_nts
643              | otherwise           = rec_nts
644
645
646 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
647 -- of inspecting the type directly.
648
649 -- | Discovers the primitive representation of a more abstract 'Type'
650 typePrimRep :: Type -> PrimRep
651 typePrimRep ty = case repType ty of
652                    TyConApp tc _ -> tyConPrimRep tc
653                    FunTy _ _     -> PtrRep
654                    AppTy _ _     -> PtrRep      -- See note below
655                    TyVarTy _     -> PtrRep
656                    _             -> pprPanic "typePrimRep" (ppr ty)
657         -- Types of the form 'f a' must be of kind *, not *#, so
658         -- we are guaranteed that they are represented by pointers.
659         -- The reason is that f must have kind *->*, not *->*#, because
660         -- (we claim) there is no way to constrain f's kind any other
661         -- way.
662 \end{code}
663
664
665 ---------------------------------------------------------------------
666                                 ForAllTy
667                                 ~~~~~~~~
668
669 \begin{code}
670 mkForAllTy :: TyVar -> Type -> Type
671 mkForAllTy tyvar ty
672   = ForAllTy tyvar ty
673
674 -- | Wraps foralls over the type using the provided 'TyVar's from left to right
675 mkForAllTys :: [TyVar] -> Type -> Type
676 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
677
678 isForAllTy :: Type -> Bool
679 isForAllTy (ForAllTy _ _) = True
680 isForAllTy _              = False
681
682 -- | Attempts to take a forall type apart, returning the bound type variable
683 -- and the remainder of the type
684 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
685 splitForAllTy_maybe ty = splitFAT_m ty
686   where
687     splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
688     splitFAT_m (ForAllTy tyvar ty)          = Just(tyvar, ty)
689     splitFAT_m _                            = Nothing
690
691 -- | Attempts to take a forall type apart, returning all the immediate such bound
692 -- type variables and the remainder of the type. Always suceeds, even if that means
693 -- returning an empty list of 'TyVar's
694 splitForAllTys :: Type -> ([TyVar], Type)
695 splitForAllTys ty = split ty ty []
696    where
697      split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
698      split _       (ForAllTy tv ty)  tvs = split ty ty (tv:tvs)
699      split orig_ty _                 tvs = (reverse tvs, orig_ty)
700
701 -- | Equivalent to @snd . splitForAllTys@
702 dropForAlls :: Type -> Type
703 dropForAlls ty = snd (splitForAllTys ty)
704 \end{code}
705
706 -- (mkPiType now in CoreUtils)
707
708 applyTy, applyTys
709 ~~~~~~~~~~~~~~~~~
710
711 \begin{code}
712 -- | Instantiate a forall type with one or more type arguments.
713 -- Used when we have a polymorphic function applied to type args:
714 --
715 -- > f t1 t2
716 --
717 -- We use @applyTys type-of-f [t1,t2]@ to compute the type of the expression.
718 -- Panics if no application is possible.
719 applyTy :: Type -> Type -> Type
720 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
721 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
722 applyTy _                _   = panic "applyTy"
723
724 applyTys :: Type -> [Type] -> Type
725 -- ^ This function is interesting because:
726 --
727 --      1. The function may have more for-alls than there are args
728 --
729 --      2. Less obviously, it may have fewer for-alls
730 --
731 -- For case 2. think of:
732 --
733 -- > applyTys (forall a.a) [forall b.b, Int]
734 --
735 -- This really can happen, via dressing up polymorphic types with newtype
736 -- clothing.  Here's an example:
737 --
738 -- > newtype R = R (forall a. a->a)
739 -- > foo = case undefined :: R of
740 -- >            R f -> f ()
741
742 applyTys ty args = applyTysD empty ty args
743
744 applyTysD :: SDoc -> Type -> [Type] -> Type     -- Debug version
745 applyTysD _   orig_fun_ty []      = orig_fun_ty
746 applyTysD doc orig_fun_ty arg_tys 
747   | n_tvs == n_args     -- The vastly common case
748   = substTyWith tvs arg_tys rho_ty
749   | n_tvs > n_args      -- Too many for-alls
750   = substTyWith (take n_args tvs) arg_tys 
751                 (mkForAllTys (drop n_args tvs) rho_ty)
752   | otherwise           -- Too many type args
753   = ASSERT2( n_tvs > 0, doc $$ ppr orig_fun_ty )        -- Zero case gives infnite loop!
754     applyTysD doc (substTyWith tvs (take n_tvs arg_tys) rho_ty)
755                   (drop n_tvs arg_tys)
756   where
757     (tvs, rho_ty) = splitForAllTys orig_fun_ty 
758     n_tvs = length tvs
759     n_args = length arg_tys     
760 \end{code}
761
762
763 %************************************************************************
764 %*                                                                      *
765 \subsection{Source types}
766 %*                                                                      *
767 %************************************************************************
768
769 Source types are always lifted.
770
771 The key function is predTypeRep which gives the representation of a source type:
772
773 \begin{code}
774 mkPredTy :: PredType -> Type
775 mkPredTy pred = PredTy pred
776
777 mkPredTys :: ThetaType -> [Type]
778 mkPredTys preds = map PredTy preds
779
780 isEqPred :: PredType -> Bool
781 isEqPred (EqPred _ _) = True
782 isEqPred _            = False
783
784 predTypeRep :: PredType -> Type
785 -- ^ Convert a 'PredType' to its representation type. However, it unwraps 
786 -- only the outermost level; for example, the result might be a newtype application
787 predTypeRep (IParam _ ty)     = ty
788 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
789         -- Result might be a newtype application, but the consumer will
790         -- look through that too if necessary
791 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
792
793 mkFamilyTyConApp :: TyCon -> [Type] -> Type
794 -- ^ Given a family instance TyCon and its arg types, return the
795 -- corresponding family type.  E.g:
796 --
797 -- > data family T a
798 -- > data instance T (Maybe b) = MkT b
799 --
800 -- Where the instance tycon is :RTL, so:
801 --
802 -- > mkFamilyTyConApp :RTL Int  =  T (Maybe Int)
803 mkFamilyTyConApp tc tys
804   | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
805   , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
806   = mkTyConApp fam_tc (substTys fam_subst fam_tys)
807   | otherwise
808   = mkTyConApp tc tys
809
810 -- | Pretty prints a 'TyCon', using the family instance in case of a
811 -- representation tycon.  For example:
812 --
813 -- > data T [a] = ...
814 --
815 -- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
816 pprSourceTyCon :: TyCon -> SDoc
817 pprSourceTyCon tycon 
818   | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
819   = ppr $ fam_tc `TyConApp` tys        -- can't be FunTyCon
820   | otherwise
821   = ppr tycon
822
823 isDictTy :: Type -> Bool
824 isDictTy ty = case splitTyConApp_maybe ty of
825                 Just (tc, _) -> isClassTyCon tc
826                 Nothing      -> False
827 \end{code}
828
829
830 %************************************************************************
831 %*                                                                      *
832              The free variables of a type
833 %*                                                                      *
834 %************************************************************************
835
836 \begin{code}
837 tyVarsOfType :: Type -> TyVarSet
838 -- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
839 tyVarsOfType (TyVarTy tv)               = unitVarSet tv
840 tyVarsOfType (TyConApp _ tys)           = tyVarsOfTypes tys
841 tyVarsOfType (PredTy sty)               = tyVarsOfPred sty
842 tyVarsOfType (FunTy arg res)            = tyVarsOfType arg `unionVarSet` tyVarsOfType res
843 tyVarsOfType (AppTy fun arg)            = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
844 tyVarsOfType (ForAllTy tyvar ty)        = delVarSet (tyVarsOfType ty) tyvar
845
846 tyVarsOfTypes :: [Type] -> TyVarSet
847 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
848
849 tyVarsOfPred :: PredType -> TyVarSet
850 tyVarsOfPred (IParam _ ty)    = tyVarsOfType ty
851 tyVarsOfPred (ClassP _ tys)   = tyVarsOfTypes tys
852 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
853
854 tyVarsOfTheta :: ThetaType -> TyVarSet
855 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
856 \end{code}
857
858
859 %************************************************************************
860 %*                                                                      *
861 \subsection{Type families}
862 %*                                                                      *
863 %************************************************************************
864
865 \begin{code}
866 -- | Finds type family instances occuring in a type after expanding synonyms.
867 tyFamInsts :: Type -> [(TyCon, [Type])]
868 tyFamInsts ty 
869   | Just exp_ty <- tcView ty    = tyFamInsts exp_ty
870 tyFamInsts (TyVarTy _)          = []
871 tyFamInsts (TyConApp tc tys) 
872   | isOpenSynTyCon tc           = [(tc, tys)]
873   | otherwise                   = concat (map tyFamInsts tys)
874 tyFamInsts (FunTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
875 tyFamInsts (AppTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
876 tyFamInsts (ForAllTy _ ty)      = tyFamInsts ty
877 tyFamInsts (PredTy pty)         = predFamInsts pty
878
879 -- | Finds type family instances occuring in a predicate type after expanding 
880 -- synonyms.
881 predFamInsts :: PredType -> [(TyCon, [Type])]
882 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
883 predFamInsts (IParam _ ty)     = tyFamInsts ty
884 predFamInsts (EqPred ty1 ty2)  = tyFamInsts ty1 ++ tyFamInsts ty2
885 \end{code}
886
887
888 %************************************************************************
889 %*                                                                      *
890 \subsection{TidyType}
891 %*                                                                      *
892 %************************************************************************
893
894 \begin{code}
895 -- | This tidies up a type for printing in an error message, or in
896 -- an interface file.
897 -- 
898 -- It doesn't change the uniques at all, just the print names.
899 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
900 tidyTyVarBndr env@(tidy_env, subst) tyvar
901   = case tidyOccName tidy_env (getOccName name) of
902       (tidy', occ') -> ((tidy', subst'), tyvar'')
903         where
904           subst' = extendVarEnv subst tyvar tyvar''
905           tyvar' = setTyVarName tyvar name'
906           name'  = tidyNameOcc name occ'
907                 -- Don't forget to tidy the kind for coercions!
908           tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
909                   | otherwise     = tyvar'
910           kind'  = tidyType env (tyVarKind tyvar)
911   where
912     name = tyVarName tyvar
913
914 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
915 -- ^ Add the free 'TyVar's to the env in tidy form,
916 -- so that we can tidy the type they are free in
917 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
918
919 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
920 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
921
922 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
923 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
924 -- using the environment if one has not already been allocated. See
925 -- also 'tidyTyVarBndr'
926 tidyOpenTyVar env@(_, subst) tyvar
927   = case lookupVarEnv subst tyvar of
928         Just tyvar' -> (env, tyvar')            -- Already substituted
929         Nothing     -> tidyTyVarBndr env tyvar  -- Treat it as a binder
930
931 tidyType :: TidyEnv -> Type -> Type
932 tidyType env@(_, subst) ty
933   = go ty
934   where
935     go (TyVarTy tv)         = case lookupVarEnv subst tv of
936                                 Nothing  -> TyVarTy tv
937                                 Just tv' -> TyVarTy tv'
938     go (TyConApp tycon tys) = let args = map go tys
939                               in args `seqList` TyConApp tycon args
940     go (PredTy sty)         = PredTy (tidyPred env sty)
941     go (AppTy fun arg)      = (AppTy $! (go fun)) $! (go arg)
942     go (FunTy fun arg)      = (FunTy $! (go fun)) $! (go arg)
943     go (ForAllTy tv ty)     = ForAllTy tvp $! (tidyType envp ty)
944                               where
945                                 (envp, tvp) = tidyTyVarBndr env tv
946
947 tidyTypes :: TidyEnv -> [Type] -> [Type]
948 tidyTypes env tys = map (tidyType env) tys
949
950 tidyPred :: TidyEnv -> PredType -> PredType
951 tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
952 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
953 tidyPred env (EqPred ty1 ty2)  = EqPred (tidyType env ty1) (tidyType env ty2)
954 \end{code}
955
956
957 \begin{code}
958 -- | Grabs the free type variables, tidies them
959 -- and then uses 'tidyType' to work over the type itself
960 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
961 tidyOpenType env ty
962   = (env', tidyType env' ty)
963   where
964     env' = tidyFreeTyVars env (tyVarsOfType ty)
965
966 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
967 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
968
969 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
970 tidyTopType :: Type -> Type
971 tidyTopType ty = tidyType emptyTidyEnv ty
972 \end{code}
973
974 \begin{code}
975
976 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
977 tidyKind env k = tidyOpenType env k
978
979 \end{code}
980
981
982 %************************************************************************
983 %*                                                                      *
984 \subsection{Liftedness}
985 %*                                                                      *
986 %************************************************************************
987
988 \begin{code}
989 -- | See "Type#type_classification" for what an unlifted type is
990 isUnLiftedType :: Type -> Bool
991         -- isUnLiftedType returns True for forall'd unlifted types:
992         --      x :: forall a. Int#
993         -- I found bindings like these were getting floated to the top level.
994         -- They are pretty bogus types, mind you.  It would be better never to
995         -- construct them
996
997 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
998 isUnLiftedType (ForAllTy _ ty)   = isUnLiftedType ty
999 isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
1000 isUnLiftedType _                 = False
1001
1002 isUnboxedTupleType :: Type -> Bool
1003 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
1004                            Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
1005                            _                   -> False
1006
1007 -- | See "Type#type_classification" for what an algebraic type is.
1008 -- Should only be applied to /types/, as opposed to e.g. partially
1009 -- saturated type constructors
1010 isAlgType :: Type -> Bool
1011 isAlgType ty 
1012   = case splitTyConApp_maybe ty of
1013       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1014                             isAlgTyCon tc
1015       _other             -> False
1016
1017 -- | See "Type#type_classification" for what an algebraic type is.
1018 -- Should only be applied to /types/, as opposed to e.g. partially
1019 -- saturated type constructors. Closed type constructors are those
1020 -- with a fixed right hand side, as opposed to e.g. associated types
1021 isClosedAlgType :: Type -> Bool
1022 isClosedAlgType ty
1023   = case splitTyConApp_maybe ty of
1024       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1025                             isAlgTyCon tc && not (isOpenTyCon tc)
1026       _other             -> False
1027 \end{code}
1028
1029 \begin{code}
1030 -- | Computes whether an argument (or let right hand side) should
1031 -- be computed strictly or lazily, based only on its type.
1032 -- Works just like 'isUnLiftedType', except that it has a special case 
1033 -- for dictionaries (i.e. does not work purely on representation types)
1034
1035 -- Since it takes account of class 'PredType's, you might think
1036 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
1037 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
1038 isStrictType :: Type -> Bool
1039 isStrictType (PredTy pred)     = isStrictPred pred
1040 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
1041 isStrictType (ForAllTy _ ty)   = isStrictType ty
1042 isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
1043 isStrictType _                 = False
1044
1045 -- | We may be strict in dictionary types, but only if it 
1046 -- has more than one component.
1047 --
1048 -- (Being strict in a single-component dictionary risks
1049 --  poking the dictionary component, which is wrong.)
1050 isStrictPred :: PredType -> Bool
1051 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
1052 isStrictPred _               = False
1053 \end{code}
1054
1055 \begin{code}
1056 isPrimitiveType :: Type -> Bool
1057 -- ^ Returns true of types that are opaque to Haskell.
1058 -- Most of these are unlifted, but now that we interact with .NET, we
1059 -- may have primtive (foreign-imported) types that are lifted
1060 isPrimitiveType ty = case splitTyConApp_maybe ty of
1061                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
1062                                               isPrimTyCon tc
1063                         _                  -> False
1064 \end{code}
1065
1066
1067 %************************************************************************
1068 %*                                                                      *
1069 \subsection{Sequencing on types}
1070 %*                                                                      *
1071 %************************************************************************
1072
1073 \begin{code}
1074 seqType :: Type -> ()
1075 seqType (TyVarTy tv)      = tv `seq` ()
1076 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
1077 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
1078 seqType (PredTy p)        = seqPred p
1079 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
1080 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
1081
1082 seqTypes :: [Type] -> ()
1083 seqTypes []       = ()
1084 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1085
1086 seqPred :: PredType -> ()
1087 seqPred (ClassP c tys)   = c `seq` seqTypes tys
1088 seqPred (IParam n ty)    = n `seq` seqType ty
1089 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
1090 \end{code}
1091
1092
1093 %************************************************************************
1094 %*                                                                      *
1095                 Equality for Core types 
1096         (We don't use instances so that we know where it happens)
1097 %*                                                                      *
1098 %************************************************************************
1099
1100 Note that eqType works right even for partial applications of newtypes.
1101 See Note [Newtype eta] in TyCon.lhs
1102
1103 \begin{code}
1104 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1105 coreEqType :: Type -> Type -> Bool
1106 coreEqType t1 t2 = coreEqType2 rn_env t1 t2
1107   where
1108     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1109
1110 coreEqType2 :: RnEnv2 -> Type -> Type -> Bool
1111 coreEqType2 rn_env t1 t2
1112   = eq rn_env t1 t2
1113   where
1114     eq env (TyVarTy tv1)       (TyVarTy tv2)     = rnOccL env tv1 == rnOccR env tv2
1115     eq env (ForAllTy tv1 t1)   (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1116     eq env (AppTy s1 t1)       (AppTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1117     eq env (FunTy s1 t1)       (FunTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1118     eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
1119         | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1120                         -- The lengths should be equal because
1121                         -- the two types have the same kind
1122         -- NB: if the type constructors differ that does not 
1123         --     necessarily mean that the types aren't equal
1124         --     (synonyms, newtypes)
1125         -- Even if the type constructors are the same, but the arguments
1126         -- differ, the two types could be the same (e.g. if the arg is just
1127         -- ignored in the RHS).  In both these cases we fall through to an 
1128         -- attempt to expand one side or the other.
1129
1130         -- Now deal with newtypes, synonyms, pred-tys
1131     eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2 
1132                  | Just t2' <- coreView t2 = eq env t1 t2' 
1133
1134         -- Fall through case; not equal!
1135     eq _ _ _ = False
1136 \end{code}
1137
1138
1139 %************************************************************************
1140 %*                                                                      *
1141                 Comparision for source types 
1142         (We don't use instances so that we know where it happens)
1143 %*                                                                      *
1144 %************************************************************************
1145
1146 \begin{code}
1147 tcEqType :: Type -> Type -> Bool
1148 -- ^ Type equality on source types. Does not look through @newtypes@ or 
1149 -- 'PredType's, but it does look through type synonyms.
1150 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1151
1152 tcEqTypes :: [Type] -> [Type] -> Bool
1153 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1154
1155 tcCmpType :: Type -> Type -> Ordering
1156 -- ^ Type ordering on source types. Does not look through @newtypes@ or 
1157 -- 'PredType's, but it does look through type synonyms.
1158 tcCmpType t1 t2 = cmpType t1 t2
1159
1160 tcCmpTypes :: [Type] -> [Type] -> Ordering
1161 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1162
1163 tcEqPred :: PredType -> PredType -> Bool
1164 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1165
1166 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1167 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1168
1169 tcCmpPred :: PredType -> PredType -> Ordering
1170 tcCmpPred p1 p2 = cmpPred p1 p2
1171
1172 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1173 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1174 \end{code}
1175
1176 \begin{code}
1177 -- | Checks whether the second argument is a subterm of the first.  (We don't care
1178 -- about binders, as we are only interested in syntactic subterms.)
1179 tcPartOfType :: Type -> Type -> Bool
1180 tcPartOfType t1              t2 
1181   | tcEqType t1 t2              = True
1182 tcPartOfType t1              t2 
1183   | Just t2' <- tcView t2       = tcPartOfType t1 t2'
1184 tcPartOfType _  (TyVarTy _)     = False
1185 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1186 tcPartOfType t1 (AppTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1187 tcPartOfType t1 (FunTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1188 tcPartOfType t1 (PredTy p2)     = tcPartOfPred t1 p2
1189 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1190
1191 tcPartOfPred :: Type -> PredType -> Bool
1192 tcPartOfPred t1 (IParam _ t2)  = tcPartOfType t1 t2
1193 tcPartOfPred t1 (ClassP _ ts)  = any (tcPartOfType t1) ts
1194 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1195 \end{code}
1196
1197 Now here comes the real worker
1198
1199 \begin{code}
1200 cmpType :: Type -> Type -> Ordering
1201 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1202   where
1203     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1204
1205 cmpTypes :: [Type] -> [Type] -> Ordering
1206 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1207   where
1208     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1209
1210 cmpPred :: PredType -> PredType -> Ordering
1211 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1212   where
1213     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1214
1215 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering  -- Main workhorse
1216 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1217                    | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1218
1219 cmpTypeX env (TyVarTy tv1)       (TyVarTy tv2)       = rnOccL env tv1 `compare` rnOccR env tv2
1220 cmpTypeX env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1221 cmpTypeX env (AppTy s1 t1)       (AppTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1222 cmpTypeX env (FunTy s1 t1)       (FunTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1223 cmpTypeX env (PredTy p1)         (PredTy p2)         = cmpPredX env p1 p2
1224 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1225
1226     -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1227 cmpTypeX _ (AppTy _ _)    (TyVarTy _)    = GT
1228
1229 cmpTypeX _ (FunTy _ _)    (TyVarTy _)    = GT
1230 cmpTypeX _ (FunTy _ _)    (AppTy _ _)    = GT
1231
1232 cmpTypeX _ (TyConApp _ _) (TyVarTy _)    = GT
1233 cmpTypeX _ (TyConApp _ _) (AppTy _ _)    = GT
1234 cmpTypeX _ (TyConApp _ _) (FunTy _ _)    = GT
1235
1236 cmpTypeX _ (ForAllTy _ _) (TyVarTy _)    = GT
1237 cmpTypeX _ (ForAllTy _ _) (AppTy _ _)    = GT
1238 cmpTypeX _ (ForAllTy _ _) (FunTy _ _)    = GT
1239 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1240
1241 cmpTypeX _ (PredTy _)     _              = GT
1242
1243 cmpTypeX _ _              _              = LT
1244
1245 -------------
1246 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1247 cmpTypesX _   []        []        = EQ
1248 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1249 cmpTypesX _   []        _         = LT
1250 cmpTypesX _   _         []        = GT
1251
1252 -------------
1253 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1254 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1255         -- Compare names only for implicit parameters
1256         -- This comparison is used exclusively (I believe) 
1257         -- for the Avails finite map built in TcSimplify
1258         -- If the types differ we keep them distinct so that we see 
1259         -- a distinct pair to run improvement on 
1260 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1261 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1262
1263 -- Constructor order: IParam < ClassP < EqPred
1264 cmpPredX _   (IParam {})     _              = LT
1265 cmpPredX _   (ClassP {})    (IParam {})     = GT
1266 cmpPredX _   (ClassP {})    (EqPred {})     = LT
1267 cmpPredX _   (EqPred {})    _               = GT
1268 \end{code}
1269
1270 PredTypes are used as a FM key in TcSimplify, 
1271 so we take the easy path and make them an instance of Ord
1272
1273 \begin{code}
1274 instance Eq  PredType where { (==)    = tcEqPred }
1275 instance Ord PredType where { compare = tcCmpPred }
1276 \end{code}
1277
1278
1279 %************************************************************************
1280 %*                                                                      *
1281                 Type substitutions
1282 %*                                                                      *
1283 %************************************************************************
1284
1285 \begin{code}
1286 -- | Type substitution
1287 --
1288 -- #tvsubst_invariant#
1289 -- The following invariants must hold of a 'TvSubst':
1290 -- 
1291 -- 1. The in-scope set is needed /only/ to
1292 -- guide the generation of fresh uniques
1293 --
1294 -- 2. In particular, the /kind/ of the type variables in 
1295 -- the in-scope set is not relevant
1296 --
1297 -- 3. The substition is only applied ONCE! This is because
1298 -- in general such application will not reached a fixed point.
1299 data TvSubst            
1300   = TvSubst InScopeSet  -- The in-scope type variables
1301             TvSubstEnv  -- The substitution itself
1302         -- See Note [Apply Once]
1303         -- and Note [Extending the TvSubstEnv]
1304
1305 {- ----------------------------------------------------------
1306
1307 Note [Apply Once]
1308 ~~~~~~~~~~~~~~~~~
1309 We use TvSubsts to instantiate things, and we might instantiate
1310         forall a b. ty
1311 \with the types
1312         [a, b], or [b, a].
1313 So the substition might go [a->b, b->a].  A similar situation arises in Core
1314 when we find a beta redex like
1315         (/\ a /\ b -> e) b a
1316 Then we also end up with a substition that permutes type variables. Other
1317 variations happen to; for example [a -> (a, b)].  
1318
1319         ***************************************************
1320         *** So a TvSubst must be applied precisely once ***
1321         ***************************************************
1322
1323 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1324 we use during unifications, it must not be repeatedly applied.
1325
1326 Note [Extending the TvSubst]
1327 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1328 See #tvsubst_invariant# for the invariants that must hold.
1329
1330 This invariant allows a short-cut when the TvSubstEnv is empty:
1331 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1332 then (substTy subst ty) does nothing.
1333
1334 For example, consider:
1335         (/\a. /\b:(a~Int). ...b..) Int
1336 We substitute Int for 'a'.  The Unique of 'b' does not change, but
1337 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1338
1339 This invariant has several crucial consequences:
1340
1341 * In substTyVarBndr, we need extend the TvSubstEnv 
1342         - if the unique has changed
1343         - or if the kind has changed
1344
1345 * In substTyVar, we do not need to consult the in-scope set;
1346   the TvSubstEnv is enough
1347
1348 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1349   
1350
1351 -------------------------------------------------------------- -}
1352
1353 -- | A substitition of 'Type's for 'TyVar's
1354 type TvSubstEnv = TyVarEnv Type
1355         -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1356         -- invariant discussed in Note [Apply Once]), and also independently
1357         -- in the middle of matching, and unification (see Types.Unify)
1358         -- So you have to look at the context to know if it's idempotent or
1359         -- apply-once or whatever
1360
1361 emptyTvSubstEnv :: TvSubstEnv
1362 emptyTvSubstEnv = emptyVarEnv
1363
1364 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1365 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1366 -- It assumes that both are idempotent.
1367 -- Typically, @env1@ is the refinement to a base substitution @env2@
1368 composeTvSubst in_scope env1 env2
1369   = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1370         -- First apply env1 to the range of env2
1371         -- Then combine the two, making sure that env1 loses if
1372         -- both bind the same variable; that's why env1 is the
1373         --  *left* argument to plusVarEnv, because the right arg wins
1374   where
1375     subst1 = TvSubst in_scope env1
1376
1377 emptyTvSubst :: TvSubst
1378 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1379
1380 isEmptyTvSubst :: TvSubst -> Bool
1381          -- See Note [Extending the TvSubstEnv]
1382 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1383
1384 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1385 mkTvSubst = TvSubst
1386
1387 getTvSubstEnv :: TvSubst -> TvSubstEnv
1388 getTvSubstEnv (TvSubst _ env) = env
1389
1390 getTvInScope :: TvSubst -> InScopeSet
1391 getTvInScope (TvSubst in_scope _) = in_scope
1392
1393 isInScope :: Var -> TvSubst -> Bool
1394 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1395
1396 notElemTvSubst :: TyVar -> TvSubst -> Bool
1397 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1398
1399 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1400 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1401
1402 zapTvSubstEnv :: TvSubst -> TvSubst
1403 zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
1404
1405 extendTvInScope :: TvSubst -> Var -> TvSubst
1406 extendTvInScope (TvSubst in_scope env) var = TvSubst (extendInScopeSet in_scope var) env
1407
1408 extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
1409 extendTvInScopeList (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1410
1411 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1412 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1413
1414 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1415 extendTvSubstList (TvSubst in_scope env) tvs tys 
1416   = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1417
1418 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1419 -- the types given; but it's just a thunk so with a bit of luck
1420 -- it'll never be evaluated
1421
1422 -- Note [Generating the in-scope set for a substitution]
1423 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1424 -- If we want to substitute [a -> ty1, b -> ty2] I used to 
1425 -- think it was enough to generate an in-scope set that includes
1426 -- fv(ty1,ty2).  But that's not enough; we really should also take the
1427 -- free vars of the type we are substituting into!  Example:
1428 --      (forall b. (a,b,x)) [a -> List b]
1429 -- Then if we use the in-scope set {b}, there is a danger we will rename
1430 -- the forall'd variable to 'x' by mistake, getting this:
1431 --      (forall x. (List b, x, x)
1432 -- Urk!  This means looking at all the calls to mkOpenTvSubst....
1433
1434
1435 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1436 -- environment, hence "open"
1437 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1438 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1439
1440 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1441 -- environment, hence "open"
1442 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1443 zipOpenTvSubst tyvars tys 
1444   | debugIsOn && (length tyvars /= length tys)
1445   = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1446   | otherwise
1447   = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1448
1449 -- | Called when doing top-level substitutions. Here we expect that the 
1450 -- free vars of the range of the substitution will be empty.
1451 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1452 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1453
1454 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1455 zipTopTvSubst tyvars tys 
1456   | debugIsOn && (length tyvars /= length tys)
1457   = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1458   | otherwise
1459   = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1460
1461 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1462 zipTyEnv tyvars tys
1463   | debugIsOn && (length tyvars /= length tys)
1464   = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1465   | otherwise
1466   = zip_ty_env tyvars tys emptyVarEnv
1467
1468 -- Later substitutions in the list over-ride earlier ones, 
1469 -- but there should be no loops
1470 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1471 zip_ty_env []       []       env = env
1472 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1473         -- There used to be a special case for when 
1474         --      ty == TyVarTy tv
1475         -- (a not-uncommon case) in which case the substitution was dropped.
1476         -- But the type-tidier changes the print-name of a type variable without
1477         -- changing the unique, and that led to a bug.   Why?  Pre-tidying, we had 
1478         -- a type {Foo t}, where Foo is a one-method class.  So Foo is really a newtype.
1479         -- And it happened that t was the type variable of the class.  Post-tiding, 
1480         -- it got turned into {Foo t2}.  The ext-core printer expanded this using
1481         -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1482         -- and so generated a rep type mentioning t not t2.  
1483         --
1484         -- Simplest fix is to nuke the "optimisation"
1485 zip_ty_env tvs      tys      env   = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1486 -- zip_ty_env _ _ env = env
1487
1488 instance Outputable TvSubst where
1489   ppr (TvSubst ins env) 
1490     = brackets $ sep[ ptext (sLit "TvSubst"),
1491                       nest 2 (ptext (sLit "In scope:") <+> ppr ins), 
1492                       nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1493 \end{code}
1494
1495 %************************************************************************
1496 %*                                                                      *
1497                 Performing type substitutions
1498 %*                                                                      *
1499 %************************************************************************
1500
1501 \begin{code}
1502 -- | Type substitution making use of an 'TvSubst' that
1503 -- is assumed to be open, see 'zipOpenTvSubst'
1504 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1505 substTyWith tvs tys = ASSERT( length tvs == length tys )
1506                       substTy (zipOpenTvSubst tvs tys)
1507
1508 -- | Type substitution making use of an 'TvSubst' that
1509 -- is assumed to be open, see 'zipOpenTvSubst'
1510 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1511 substTysWith tvs tys = ASSERT( length tvs == length tys )
1512                        substTys (zipOpenTvSubst tvs tys)
1513
1514 -- | Substitute within a 'Type'
1515 substTy :: TvSubst -> Type  -> Type
1516 substTy subst ty | isEmptyTvSubst subst = ty
1517                  | otherwise            = subst_ty subst ty
1518
1519 -- | Substitute within several 'Type's
1520 substTys :: TvSubst -> [Type] -> [Type]
1521 substTys subst tys | isEmptyTvSubst subst = tys
1522                    | otherwise            = map (subst_ty subst) tys
1523
1524 -- | Substitute within a 'ThetaType'
1525 substTheta :: TvSubst -> ThetaType -> ThetaType
1526 substTheta subst theta
1527   | isEmptyTvSubst subst = theta
1528   | otherwise            = map (substPred subst) theta
1529
1530 -- | Substitute within a 'PredType'
1531 substPred :: TvSubst -> PredType -> PredType
1532 substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)
1533 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1534 substPred subst (EqPred ty1 ty2)  = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1535
1536 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1537 deShadowTy :: TyVarSet -> Type -> Type
1538 deShadowTy tvs ty 
1539   = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1540   where
1541     in_scope = mkInScopeSet tvs
1542
1543 subst_ty :: TvSubst -> Type -> Type
1544 -- subst_ty is the main workhorse for type substitution
1545 --
1546 -- Note that the in_scope set is poked only if we hit a forall
1547 -- so it may often never be fully computed 
1548 subst_ty subst ty
1549    = go ty
1550   where
1551     go (TyVarTy tv)      = substTyVar subst tv
1552     go (TyConApp tc tys) = let args = map go tys
1553                            in  args `seqList` TyConApp tc args
1554
1555     go (PredTy p)        = PredTy $! (substPred subst p)
1556
1557     go (FunTy arg res)   = (FunTy $! (go arg)) $! (go res)
1558     go (AppTy fun arg)   = mkAppTy (go fun) $! (go arg)
1559                 -- The mkAppTy smart constructor is important
1560                 -- we might be replacing (a Int), represented with App
1561                 -- by [Int], represented with TyConApp
1562     go (ForAllTy tv ty)  = case substTyVarBndr subst tv of
1563                               (subst', tv') ->
1564                                  ForAllTy tv' $! (subst_ty subst' ty)
1565
1566 substTyVar :: TvSubst -> TyVar  -> Type
1567 substTyVar subst@(TvSubst _ _) tv
1568   = case lookupTyVar subst tv of {
1569         Nothing -> TyVarTy tv;
1570         Just ty -> ty   -- See Note [Apply Once]
1571     } 
1572
1573 substTyVars :: TvSubst -> [TyVar] -> [Type]
1574 substTyVars subst tvs = map (substTyVar subst) tvs
1575
1576 lookupTyVar :: TvSubst -> TyVar  -> Maybe Type
1577         -- See Note [Extending the TvSubst]
1578 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1579
1580 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)  
1581 substTyVarBndr subst@(TvSubst in_scope env) old_var
1582   = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1583   where
1584     is_co_var = isCoVar old_var
1585
1586     new_env | no_change = delVarEnv env old_var
1587             | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1588
1589     no_change = new_var == old_var && not is_co_var
1590         -- no_change means that the new_var is identical in
1591         -- all respects to the old_var (same unique, same kind)
1592         -- See Note [Extending the TvSubst]
1593         --
1594         -- In that case we don't need to extend the substitution
1595         -- to map old to new.  But instead we must zap any 
1596         -- current substitution for the variable. For example:
1597         --      (\x.e) with id_subst = [x |-> e']
1598         -- Here we must simply zap the substitution for x
1599
1600     new_var = uniqAway in_scope subst_old_var
1601         -- The uniqAway part makes sure the new variable is not already in scope
1602
1603     subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1604                   -- It's only worth doing the substitution for coercions,
1605                   -- becuase only they can have free type variables
1606         | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1607         | otherwise = old_var
1608 \end{code}
1609
1610 ----------------------------------------------------
1611 -- Kind Stuff
1612
1613 Kinds
1614 ~~~~~
1615
1616 \begin{code}
1617 -- $kind_subtyping
1618 -- #kind_subtyping#
1619 -- There's a little subtyping at the kind level:
1620 --
1621 -- @
1622 --               ?
1623 --              \/ &#92;
1624 --             \/   &#92;
1625 --            ??   (\#)
1626 --           \/  &#92;
1627 --          \*    \#
1628 -- .
1629 -- Where:        \*    [LiftedTypeKind]   means boxed type
1630 --              \#    [UnliftedTypeKind] means unboxed type
1631 --              (\#)  [UbxTupleKind]     means unboxed tuple
1632 --              ??   [ArgTypeKind]      is the lub of {\*, \#}
1633 --              ?    [OpenTypeKind]     means any type at all
1634 -- @
1635 --
1636 -- In particular:
1637 --
1638 -- > error :: forall a:?. String -> a
1639 -- > (->)  :: ?? -> ? -> \*
1640 -- > (\\(x::t) -> ...)
1641 --
1642 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1643
1644 type KindVar = TyVar  -- invariant: KindVar will always be a 
1645                       -- TcTyVar with details MetaTv TauTv ...
1646 -- kind var constructors and functions are in TcType
1647
1648 type SimpleKind = Kind
1649 \end{code}
1650
1651 Kind inference
1652 ~~~~~~~~~~~~~~
1653 During kind inference, a kind variable unifies only with 
1654 a "simple kind", sk
1655         sk ::= * | sk1 -> sk2
1656 For example 
1657         data T a = MkT a (T Int#)
1658 fails.  We give T the kind (k -> *), and the kind variable k won't unify
1659 with # (the kind of Int#).
1660
1661 Type inference
1662 ~~~~~~~~~~~~~~
1663 When creating a fresh internal type variable, we give it a kind to express 
1664 constraints on it.  E.g. in (\x->e) we make up a fresh type variable for x, 
1665 with kind ??.  
1666
1667 During unification we only bind an internal type variable to a type
1668 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1669
1670 When unifying two internal type variables, we collect their kind constraints by
1671 finding the GLB of the two.  Since the partial order is a tree, they only
1672 have a glb if one is a sub-kind of the other.  In that case, we bind the
1673 less-informative one to the more informative one.  Neat, eh?