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