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