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