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