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