8ff78fbccfa5f2c082fcb1b7d39b8d1c6e4a13ab
[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, unionTvSubst,
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 tv ty) -- The kind of a coercion binder 
838                               -- can mention type variables!
839   | isTyVar tv                = inner_tvs `delVarSet` tv
840   | otherwise  {- Coercion -} = -- ASSERT( not (tv `elemVarSet` inner_tvs) )
841                                 inner_tvs `unionVarSet` tyVarsOfType (tyVarKind tv)
842   where
843     inner_tvs = tyVarsOfType ty
844
845 tyVarsOfTypes :: [Type] -> TyVarSet
846 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
847
848 tyVarsOfPred :: PredType -> TyVarSet
849 tyVarsOfPred (IParam _ ty)    = tyVarsOfType ty
850 tyVarsOfPred (ClassP _ tys)   = tyVarsOfTypes tys
851 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
852
853 tyVarsOfTheta :: ThetaType -> TyVarSet
854 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
855 \end{code}
856
857
858 %************************************************************************
859 %*                                                                      *
860 \subsection{Type families}
861 %*                                                                      *
862 %************************************************************************
863
864 \begin{code}
865 -- | Finds type family instances occuring in a type after expanding synonyms.
866 tyFamInsts :: Type -> [(TyCon, [Type])]
867 tyFamInsts ty 
868   | Just exp_ty <- tcView ty    = tyFamInsts exp_ty
869 tyFamInsts (TyVarTy _)          = []
870 tyFamInsts (TyConApp tc tys) 
871   | isSynFamilyTyCon tc           = [(tc, tys)]
872   | otherwise                   = concat (map tyFamInsts tys)
873 tyFamInsts (FunTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
874 tyFamInsts (AppTy ty1 ty2)      = tyFamInsts ty1 ++ tyFamInsts ty2
875 tyFamInsts (ForAllTy _ ty)      = tyFamInsts ty
876 tyFamInsts (PredTy pty)         = predFamInsts pty
877
878 -- | Finds type family instances occuring in a predicate type after expanding 
879 -- synonyms.
880 predFamInsts :: PredType -> [(TyCon, [Type])]
881 predFamInsts (ClassP _cla tys) = concat (map tyFamInsts tys)
882 predFamInsts (IParam _ ty)     = tyFamInsts ty
883 predFamInsts (EqPred ty1 ty2)  = tyFamInsts ty1 ++ tyFamInsts ty2
884 \end{code}
885
886
887 %************************************************************************
888 %*                                                                      *
889 \subsection{Liftedness}
890 %*                                                                      *
891 %************************************************************************
892
893 \begin{code}
894 -- | See "Type#type_classification" for what an unlifted type is
895 isUnLiftedType :: Type -> Bool
896         -- isUnLiftedType returns True for forall'd unlifted types:
897         --      x :: forall a. Int#
898         -- I found bindings like these were getting floated to the top level.
899         -- They are pretty bogus types, mind you.  It would be better never to
900         -- construct them
901
902 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
903 isUnLiftedType (ForAllTy _ ty)   = isUnLiftedType ty
904 isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
905 isUnLiftedType _                 = False
906
907 isUnboxedTupleType :: Type -> Bool
908 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
909                            Just (tc, _ty_args) -> isUnboxedTupleTyCon tc
910                            _                   -> False
911
912 -- | See "Type#type_classification" for what an algebraic type is.
913 -- Should only be applied to /types/, as opposed to e.g. partially
914 -- saturated type constructors
915 isAlgType :: Type -> Bool
916 isAlgType ty 
917   = case splitTyConApp_maybe ty of
918       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
919                             isAlgTyCon tc
920       _other             -> False
921
922 -- | See "Type#type_classification" for what an algebraic type is.
923 -- Should only be applied to /types/, as opposed to e.g. partially
924 -- saturated type constructors. Closed type constructors are those
925 -- with a fixed right hand side, as opposed to e.g. associated types
926 isClosedAlgType :: Type -> Bool
927 isClosedAlgType ty
928   = case splitTyConApp_maybe ty of
929       Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
930                             isAlgTyCon tc && not (isFamilyTyCon tc)
931       _other             -> False
932 \end{code}
933
934 \begin{code}
935 -- | Computes whether an argument (or let right hand side) should
936 -- be computed strictly or lazily, based only on its type.
937 -- Works just like 'isUnLiftedType', except that it has a special case 
938 -- for dictionaries (i.e. does not work purely on representation types)
939
940 -- Since it takes account of class 'PredType's, you might think
941 -- this function should be in 'TcType', but 'isStrictType' is used by 'DataCon',
942 -- which is below 'TcType' in the hierarchy, so it's convenient to put it here.
943 isStrictType :: Type -> Bool
944 isStrictType (PredTy pred)     = isStrictPred pred
945 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
946 isStrictType (ForAllTy _ ty)   = isStrictType ty
947 isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
948 isStrictType _                 = False
949
950 -- | We may be strict in dictionary types, but only if it 
951 -- has more than one component.
952 --
953 -- (Being strict in a single-component dictionary risks
954 --  poking the dictionary component, which is wrong.)
955 isStrictPred :: PredType -> Bool
956 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
957 isStrictPred _               = False
958 \end{code}
959
960 \begin{code}
961 isPrimitiveType :: Type -> Bool
962 -- ^ Returns true of types that are opaque to Haskell.
963 -- Most of these are unlifted, but now that we interact with .NET, we
964 -- may have primtive (foreign-imported) types that are lifted
965 isPrimitiveType ty = case splitTyConApp_maybe ty of
966                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
967                                               isPrimTyCon tc
968                         _                  -> False
969 \end{code}
970
971
972 %************************************************************************
973 %*                                                                      *
974 \subsection{Sequencing on types}
975 %*                                                                      *
976 %************************************************************************
977
978 \begin{code}
979 seqType :: Type -> ()
980 seqType (TyVarTy tv)      = tv `seq` ()
981 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
982 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
983 seqType (PredTy p)        = seqPred p
984 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
985 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
986
987 seqTypes :: [Type] -> ()
988 seqTypes []       = ()
989 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
990
991 seqPred :: PredType -> ()
992 seqPred (ClassP c tys)   = c `seq` seqTypes tys
993 seqPred (IParam n ty)    = n `seq` seqType ty
994 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
995 \end{code}
996
997
998 %************************************************************************
999 %*                                                                      *
1000                 Equality for Core types 
1001         (We don't use instances so that we know where it happens)
1002 %*                                                                      *
1003 %************************************************************************
1004
1005 Note that eqType works right even for partial applications of newtypes.
1006 See Note [Newtype eta] in TyCon.lhs
1007
1008 \begin{code}
1009 -- | Type equality test for Core types (i.e. ignores predicate-types, synonyms etc.)
1010 coreEqType :: Type -> Type -> Bool
1011 coreEqType t1 t2 = coreEqType2 rn_env t1 t2
1012   where
1013     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1014
1015 coreEqType2 :: RnEnv2 -> Type -> Type -> Bool
1016 coreEqType2 rn_env t1 t2
1017   = eq rn_env t1 t2
1018   where
1019     eq env (TyVarTy tv1)       (TyVarTy tv2)     = rnOccL env tv1 == rnOccR env tv2
1020     eq env (ForAllTy tv1 t1)   (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
1021     eq env (AppTy s1 t1)       (AppTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1022     eq env (FunTy s1 t1)       (FunTy s2 t2)     = eq env s1 s2 && eq env t1 t2
1023     eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
1024         | tc1 == tc2, all2 (eq env) tys1 tys2 = True
1025                         -- The lengths should be equal because
1026                         -- the two types have the same kind
1027         -- NB: if the type constructors differ that does not 
1028         --     necessarily mean that the types aren't equal
1029         --     (synonyms, newtypes)
1030         -- Even if the type constructors are the same, but the arguments
1031         -- differ, the two types could be the same (e.g. if the arg is just
1032         -- ignored in the RHS).  In both these cases we fall through to an 
1033         -- attempt to expand one side or the other.
1034
1035         -- Now deal with newtypes, synonyms, pred-tys
1036     eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2 
1037                  | Just t2' <- coreView t2 = eq env t1 t2' 
1038
1039         -- Fall through case; not equal!
1040     eq _ _ _ = False
1041 \end{code}
1042
1043
1044 %************************************************************************
1045 %*                                                                      *
1046                 Comparision for source types 
1047         (We don't use instances so that we know where it happens)
1048 %*                                                                      *
1049 %************************************************************************
1050
1051 \begin{code}
1052 tcEqType :: Type -> Type -> Bool
1053 -- ^ Type equality on source types. Does not look through @newtypes@ or 
1054 -- 'PredType's, but it does look through type synonyms.
1055 tcEqType t1 t2 = isEqual $ cmpType t1 t2
1056
1057 tcEqTypes :: [Type] -> [Type] -> Bool
1058 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
1059
1060 tcCmpType :: Type -> Type -> Ordering
1061 -- ^ Type ordering on source types. Does not look through @newtypes@ or 
1062 -- 'PredType's, but it does look through type synonyms.
1063 tcCmpType t1 t2 = cmpType t1 t2
1064
1065 tcCmpTypes :: [Type] -> [Type] -> Ordering
1066 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
1067
1068 tcEqPred :: PredType -> PredType -> Bool
1069 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
1070
1071 tcEqPredX :: RnEnv2 -> PredType -> PredType -> Bool
1072 tcEqPredX env p1 p2 = isEqual $ cmpPredX env p1 p2
1073
1074 tcCmpPred :: PredType -> PredType -> Ordering
1075 tcCmpPred p1 p2 = cmpPred p1 p2
1076
1077 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
1078 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
1079 \end{code}
1080
1081 \begin{code}
1082 -- | Checks whether the second argument is a subterm of the first.  (We don't care
1083 -- about binders, as we are only interested in syntactic subterms.)
1084 tcPartOfType :: Type -> Type -> Bool
1085 tcPartOfType t1              t2 
1086   | tcEqType t1 t2              = True
1087 tcPartOfType t1              t2 
1088   | Just t2' <- tcView t2       = tcPartOfType t1 t2'
1089 tcPartOfType _  (TyVarTy _)     = False
1090 tcPartOfType t1 (ForAllTy _ t2) = tcPartOfType t1 t2
1091 tcPartOfType t1 (AppTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1092 tcPartOfType t1 (FunTy s2 t2)   = tcPartOfType t1 s2 || tcPartOfType t1 t2
1093 tcPartOfType t1 (PredTy p2)     = tcPartOfPred t1 p2
1094 tcPartOfType t1 (TyConApp _ ts) = any (tcPartOfType t1) ts
1095
1096 tcPartOfPred :: Type -> PredType -> Bool
1097 tcPartOfPred t1 (IParam _ t2)  = tcPartOfType t1 t2
1098 tcPartOfPred t1 (ClassP _ ts)  = any (tcPartOfType t1) ts
1099 tcPartOfPred t1 (EqPred s2 t2) = tcPartOfType t1 s2 || tcPartOfType t1 t2
1100 \end{code}
1101
1102 Now here comes the real worker
1103
1104 \begin{code}
1105 cmpType :: Type -> Type -> Ordering
1106 cmpType t1 t2 = cmpTypeX rn_env t1 t2
1107   where
1108     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
1109
1110 cmpTypes :: [Type] -> [Type] -> Ordering
1111 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
1112   where
1113     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
1114
1115 cmpPred :: PredType -> PredType -> Ordering
1116 cmpPred p1 p2 = cmpPredX rn_env p1 p2
1117   where
1118     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
1119
1120 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering  -- Main workhorse
1121 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
1122                    | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
1123
1124 cmpTypeX env (TyVarTy tv1)       (TyVarTy tv2)       = rnOccL env tv1 `compare` rnOccR env tv2
1125 cmpTypeX env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
1126 cmpTypeX env (AppTy s1 t1)       (AppTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1127 cmpTypeX env (FunTy s1 t1)       (FunTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
1128 cmpTypeX env (PredTy p1)         (PredTy p2)         = cmpPredX env p1 p2
1129 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
1130
1131     -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
1132 cmpTypeX _ (AppTy _ _)    (TyVarTy _)    = GT
1133
1134 cmpTypeX _ (FunTy _ _)    (TyVarTy _)    = GT
1135 cmpTypeX _ (FunTy _ _)    (AppTy _ _)    = GT
1136
1137 cmpTypeX _ (TyConApp _ _) (TyVarTy _)    = GT
1138 cmpTypeX _ (TyConApp _ _) (AppTy _ _)    = GT
1139 cmpTypeX _ (TyConApp _ _) (FunTy _ _)    = GT
1140
1141 cmpTypeX _ (ForAllTy _ _) (TyVarTy _)    = GT
1142 cmpTypeX _ (ForAllTy _ _) (AppTy _ _)    = GT
1143 cmpTypeX _ (ForAllTy _ _) (FunTy _ _)    = GT
1144 cmpTypeX _ (ForAllTy _ _) (TyConApp _ _) = GT
1145
1146 cmpTypeX _ (PredTy _)     _              = GT
1147
1148 cmpTypeX _ _              _              = LT
1149
1150 -------------
1151 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1152 cmpTypesX _   []        []        = EQ
1153 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1154 cmpTypesX _   []        _         = LT
1155 cmpTypesX _   _         []        = GT
1156
1157 -------------
1158 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1159 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1160         -- Compare names only for implicit parameters
1161         -- This comparison is used exclusively (I believe) 
1162         -- for the Avails finite map built in TcSimplify
1163         -- If the types differ we keep them distinct so that we see 
1164         -- a distinct pair to run improvement on 
1165 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1166 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1167
1168 -- Constructor order: IParam < ClassP < EqPred
1169 cmpPredX _   (IParam {})     _              = LT
1170 cmpPredX _   (ClassP {})    (IParam {})     = GT
1171 cmpPredX _   (ClassP {})    (EqPred {})     = LT
1172 cmpPredX _   (EqPred {})    _               = GT
1173 \end{code}
1174
1175 PredTypes are used as a FM key in TcSimplify, 
1176 so we take the easy path and make them an instance of Ord
1177
1178 \begin{code}
1179 instance Eq  PredType where { (==)    = tcEqPred }
1180 instance Ord PredType where { compare = tcCmpPred }
1181 \end{code}
1182
1183
1184 %************************************************************************
1185 %*                                                                      *
1186                 Type substitutions
1187 %*                                                                      *
1188 %************************************************************************
1189
1190 \begin{code}
1191 -- | Type substitution
1192 --
1193 -- #tvsubst_invariant#
1194 -- The following invariants must hold of a 'TvSubst':
1195 -- 
1196 -- 1. The in-scope set is needed /only/ to
1197 -- guide the generation of fresh uniques
1198 --
1199 -- 2. In particular, the /kind/ of the type variables in 
1200 -- the in-scope set is not relevant
1201 --
1202 -- 3. The substition is only applied ONCE! This is because
1203 -- in general such application will not reached a fixed point.
1204 data TvSubst            
1205   = TvSubst InScopeSet  -- The in-scope type variables
1206             TvSubstEnv  -- The substitution itself
1207         -- See Note [Apply Once]
1208         -- and Note [Extending the TvSubstEnv]
1209
1210 {- ----------------------------------------------------------
1211
1212 Note [Apply Once]
1213 ~~~~~~~~~~~~~~~~~
1214 We use TvSubsts to instantiate things, and we might instantiate
1215         forall a b. ty
1216 \with the types
1217         [a, b], or [b, a].
1218 So the substition might go [a->b, b->a].  A similar situation arises in Core
1219 when we find a beta redex like
1220         (/\ a /\ b -> e) b a
1221 Then we also end up with a substition that permutes type variables. Other
1222 variations happen to; for example [a -> (a, b)].  
1223
1224         ***************************************************
1225         *** So a TvSubst must be applied precisely once ***
1226         ***************************************************
1227
1228 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1229 we use during unifications, it must not be repeatedly applied.
1230
1231 Note [Extending the TvSubst]
1232 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1233 See #tvsubst_invariant# for the invariants that must hold.
1234
1235 This invariant allows a short-cut when the TvSubstEnv is empty:
1236 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1237 then (substTy subst ty) does nothing.
1238
1239 For example, consider:
1240         (/\a. /\b:(a~Int). ...b..) Int
1241 We substitute Int for 'a'.  The Unique of 'b' does not change, but
1242 nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
1243
1244 This invariant has several crucial consequences:
1245
1246 * In substTyVarBndr, we need extend the TvSubstEnv 
1247         - if the unique has changed
1248         - or if the kind has changed
1249
1250 * In substTyVar, we do not need to consult the in-scope set;
1251   the TvSubstEnv is enough
1252
1253 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1254   
1255
1256 -------------------------------------------------------------- -}
1257
1258 -- | A substitition of 'Type's for 'TyVar's
1259 type TvSubstEnv = TyVarEnv Type
1260         -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1261         -- invariant discussed in Note [Apply Once]), and also independently
1262         -- in the middle of matching, and unification (see Types.Unify)
1263         -- So you have to look at the context to know if it's idempotent or
1264         -- apply-once or whatever
1265
1266 emptyTvSubstEnv :: TvSubstEnv
1267 emptyTvSubstEnv = emptyVarEnv
1268
1269 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1270 -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@.
1271 -- It assumes that both are idempotent.
1272 -- Typically, @env1@ is the refinement to a base substitution @env2@
1273 composeTvSubst in_scope env1 env2
1274   = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1275         -- First apply env1 to the range of env2
1276         -- Then combine the two, making sure that env1 loses if
1277         -- both bind the same variable; that's why env1 is the
1278         --  *left* argument to plusVarEnv, because the right arg wins
1279   where
1280     subst1 = TvSubst in_scope env1
1281
1282 emptyTvSubst :: TvSubst
1283 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1284
1285 isEmptyTvSubst :: TvSubst -> Bool
1286          -- See Note [Extending the TvSubstEnv]
1287 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1288
1289 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1290 mkTvSubst = TvSubst
1291
1292 getTvSubstEnv :: TvSubst -> TvSubstEnv
1293 getTvSubstEnv (TvSubst _ env) = env
1294
1295 getTvInScope :: TvSubst -> InScopeSet
1296 getTvInScope (TvSubst in_scope _) = in_scope
1297
1298 isInScope :: Var -> TvSubst -> Bool
1299 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1300
1301 notElemTvSubst :: TyVar -> TvSubst -> Bool
1302 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1303
1304 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1305 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1306
1307 zapTvSubstEnv :: TvSubst -> TvSubst
1308 zapTvSubstEnv (TvSubst in_scope _) = TvSubst in_scope emptyVarEnv
1309
1310 extendTvInScope :: TvSubst -> Var -> TvSubst
1311 extendTvInScope (TvSubst in_scope env) var = TvSubst (extendInScopeSet in_scope var) env
1312
1313 extendTvInScopeList :: TvSubst -> [Var] -> TvSubst
1314 extendTvInScopeList (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1315
1316 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1317 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1318
1319 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1320 extendTvSubstList (TvSubst in_scope env) tvs tys 
1321   = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1322
1323 unionTvSubst :: TvSubst -> TvSubst -> TvSubst
1324 -- Works when the ranges are disjoint
1325 unionTvSubst (TvSubst in_scope1 env1) (TvSubst in_scope2 env2)
1326   = ASSERT( not (env1 `intersectsVarEnv` env2) )
1327     TvSubst (in_scope1 `unionInScope` in_scope2)
1328             (env1      `plusVarEnv`   env2)
1329
1330 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1331 -- the types given; but it's just a thunk so with a bit of luck
1332 -- it'll never be evaluated
1333
1334 -- Note [Generating the in-scope set for a substitution]
1335 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1336 -- If we want to substitute [a -> ty1, b -> ty2] I used to 
1337 -- think it was enough to generate an in-scope set that includes
1338 -- fv(ty1,ty2).  But that's not enough; we really should also take the
1339 -- free vars of the type we are substituting into!  Example:
1340 --      (forall b. (a,b,x)) [a -> List b]
1341 -- Then if we use the in-scope set {b}, there is a danger we will rename
1342 -- the forall'd variable to 'x' by mistake, getting this:
1343 --      (forall x. (List b, x, x)
1344 -- Urk!  This means looking at all the calls to mkOpenTvSubst....
1345
1346
1347 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1348 -- environment, hence "open"
1349 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1350 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1351
1352 -- | Generates the in-scope set for the 'TvSubst' from the types in the incoming
1353 -- environment, hence "open"
1354 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1355 zipOpenTvSubst tyvars tys 
1356   | debugIsOn && (length tyvars /= length tys)
1357   = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1358   | otherwise
1359   = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1360
1361 -- | Called when doing top-level substitutions. Here we expect that the 
1362 -- free vars of the range of the substitution will be empty.
1363 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1364 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1365
1366 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1367 zipTopTvSubst tyvars tys 
1368   | debugIsOn && (length tyvars /= length tys)
1369   = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1370   | otherwise
1371   = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1372
1373 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1374 zipTyEnv tyvars tys
1375   | debugIsOn && (length tyvars /= length tys)
1376   = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1377   | otherwise
1378   = zip_ty_env tyvars tys emptyVarEnv
1379
1380 -- Later substitutions in the list over-ride earlier ones, 
1381 -- but there should be no loops
1382 zip_ty_env :: [TyVar] -> [Type] -> TvSubstEnv -> TvSubstEnv
1383 zip_ty_env []       []       env = env
1384 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1385         -- There used to be a special case for when 
1386         --      ty == TyVarTy tv
1387         -- (a not-uncommon case) in which case the substitution was dropped.
1388         -- But the type-tidier changes the print-name of a type variable without
1389         -- changing the unique, and that led to a bug.   Why?  Pre-tidying, we had 
1390         -- a type {Foo t}, where Foo is a one-method class.  So Foo is really a newtype.
1391         -- And it happened that t was the type variable of the class.  Post-tiding, 
1392         -- it got turned into {Foo t2}.  The ext-core printer expanded this using
1393         -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1394         -- and so generated a rep type mentioning t not t2.  
1395         --
1396         -- Simplest fix is to nuke the "optimisation"
1397 zip_ty_env tvs      tys      env   = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1398 -- zip_ty_env _ _ env = env
1399
1400 instance Outputable TvSubst where
1401   ppr (TvSubst ins env) 
1402     = brackets $ sep[ ptext (sLit "TvSubst"),
1403                       nest 2 (ptext (sLit "In scope:") <+> ppr ins), 
1404                       nest 2 (ptext (sLit "Env:") <+> ppr env) ]
1405 \end{code}
1406
1407 %************************************************************************
1408 %*                                                                      *
1409                 Performing type substitutions
1410 %*                                                                      *
1411 %************************************************************************
1412
1413 \begin{code}
1414 -- | Type substitution making use of an 'TvSubst' that
1415 -- is assumed to be open, see 'zipOpenTvSubst'
1416 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1417 substTyWith tvs tys = ASSERT( length tvs == length tys )
1418                       substTy (zipOpenTvSubst tvs tys)
1419
1420 -- | Type substitution making use of an 'TvSubst' that
1421 -- is assumed to be open, see 'zipOpenTvSubst'
1422 substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type]
1423 substTysWith tvs tys = ASSERT( length tvs == length tys )
1424                        substTys (zipOpenTvSubst tvs tys)
1425
1426 -- | Substitute within a 'Type'
1427 substTy :: TvSubst -> Type  -> Type
1428 substTy subst ty | isEmptyTvSubst subst = ty
1429                  | otherwise            = subst_ty subst ty
1430
1431 -- | Substitute within several 'Type's
1432 substTys :: TvSubst -> [Type] -> [Type]
1433 substTys subst tys | isEmptyTvSubst subst = tys
1434                    | otherwise            = map (subst_ty subst) tys
1435
1436 -- | Substitute within a 'ThetaType'
1437 substTheta :: TvSubst -> ThetaType -> ThetaType
1438 substTheta subst theta
1439   | isEmptyTvSubst subst = theta
1440   | otherwise            = map (substPred subst) theta
1441
1442 -- | Substitute within a 'PredType'
1443 substPred :: TvSubst -> PredType -> PredType
1444 substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)
1445 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1446 substPred subst (EqPred ty1 ty2)  = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1447
1448 -- | Remove any nested binders mentioning the 'TyVar's in the 'TyVarSet'
1449 deShadowTy :: TyVarSet -> Type -> Type
1450 deShadowTy tvs ty 
1451   = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1452   where
1453     in_scope = mkInScopeSet tvs
1454
1455 subst_ty :: TvSubst -> Type -> Type
1456 -- subst_ty is the main workhorse for type substitution
1457 --
1458 -- Note that the in_scope set is poked only if we hit a forall
1459 -- so it may often never be fully computed 
1460 subst_ty subst ty
1461    = go ty
1462   where
1463     go (TyVarTy tv)      = substTyVar subst tv
1464     go (TyConApp tc tys) = let args = map go tys
1465                            in  args `seqList` TyConApp tc args
1466
1467     go (PredTy p)        = PredTy $! (substPred subst p)
1468
1469     go (FunTy arg res)   = (FunTy $! (go arg)) $! (go res)
1470     go (AppTy fun arg)   = mkAppTy (go fun) $! (go arg)
1471                 -- The mkAppTy smart constructor is important
1472                 -- we might be replacing (a Int), represented with App
1473                 -- by [Int], represented with TyConApp
1474     go (ForAllTy tv ty)  = case substTyVarBndr subst tv of
1475                               (subst', tv') ->
1476                                  ForAllTy tv' $! (subst_ty subst' ty)
1477
1478 substTyVar :: TvSubst -> TyVar  -> Type
1479 substTyVar subst@(TvSubst _ _) tv
1480   = case lookupTyVar subst tv of {
1481         Nothing -> TyVarTy tv;
1482         Just ty -> ty   -- See Note [Apply Once]
1483     } 
1484
1485 substTyVars :: TvSubst -> [TyVar] -> [Type]
1486 substTyVars subst tvs = map (substTyVar subst) tvs
1487
1488 lookupTyVar :: TvSubst -> TyVar  -> Maybe Type
1489         -- See Note [Extending the TvSubst]
1490 lookupTyVar (TvSubst _ env) tv = lookupVarEnv env tv
1491
1492 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)  
1493 substTyVarBndr subst@(TvSubst in_scope env) old_var
1494   = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1495   where
1496     is_co_var = isCoVar old_var
1497
1498     new_env | no_change = delVarEnv env old_var
1499             | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1500
1501     no_change = new_var == old_var && not is_co_var
1502         -- no_change means that the new_var is identical in
1503         -- all respects to the old_var (same unique, same kind)
1504         -- See Note [Extending the TvSubst]
1505         --
1506         -- In that case we don't need to extend the substitution
1507         -- to map old to new.  But instead we must zap any 
1508         -- current substitution for the variable. For example:
1509         --      (\x.e) with id_subst = [x |-> e']
1510         -- Here we must simply zap the substitution for x
1511
1512     new_var = uniqAway in_scope subst_old_var
1513         -- The uniqAway part makes sure the new variable is not already in scope
1514
1515     subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1516                   -- It's only worth doing the substitution for coercions,
1517                   -- becuase only they can have free type variables
1518         | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1519         | otherwise = old_var
1520 \end{code}
1521
1522 ----------------------------------------------------
1523 -- Kind Stuff
1524
1525 Kinds
1526 ~~~~~
1527
1528 \begin{code}
1529 -- $kind_subtyping
1530 -- #kind_subtyping#
1531 -- There's a little subtyping at the kind level:
1532 --
1533 -- @
1534 --               ?
1535 --              \/ &#92;
1536 --             \/   &#92;
1537 --            ??   (\#)
1538 --           \/  &#92;
1539 --          \*    \#
1540 -- .
1541 -- Where:        \*    [LiftedTypeKind]   means boxed type
1542 --              \#    [UnliftedTypeKind] means unboxed type
1543 --              (\#)  [UbxTupleKind]     means unboxed tuple
1544 --              ??   [ArgTypeKind]      is the lub of {\*, \#}
1545 --              ?    [OpenTypeKind]     means any type at all
1546 -- @
1547 --
1548 -- In particular:
1549 --
1550 -- > error :: forall a:?. String -> a
1551 -- > (->)  :: ?? -> ? -> \*
1552 -- > (\\(x::t) -> ...)
1553 --
1554 -- Where in the last example @t :: ??@ (i.e. is not an unboxed tuple)
1555
1556 type KindVar = TyVar  -- invariant: KindVar will always be a 
1557                       -- TcTyVar with details MetaTv TauTv ...
1558 -- kind var constructors and functions are in TcType
1559
1560 type SimpleKind = Kind
1561 \end{code}
1562
1563 Kind inference
1564 ~~~~~~~~~~~~~~
1565 During kind inference, a kind variable unifies only with 
1566 a "simple kind", sk
1567         sk ::= * | sk1 -> sk2
1568 For example 
1569         data T a = MkT a (T Int#)
1570 fails.  We give T the kind (k -> *), and the kind variable k won't unify
1571 with # (the kind of Int#).
1572
1573 Type inference
1574 ~~~~~~~~~~~~~~
1575 When creating a fresh internal type variable, we give it a kind to express 
1576 constraints on it.  E.g. in (\x->e) we make up a fresh type variable for x, 
1577 with kind ??.  
1578
1579 During unification we only bind an internal type variable to a type
1580 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1581
1582 When unifying two internal type variables, we collect their kind constraints by
1583 finding the GLB of the two.  Since the partial order is a tree, they only
1584 have a glb if one is a sub-kind of the other.  In that case, we bind the
1585 less-informative one to the more informative one.  Neat, eh?