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