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