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