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