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