Type checking for type synonym 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         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.List
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 newTyConInstRhs :: TyCon -> [Type] -> Type
411 newTyConInstRhs tycon tys =
412     let (tvs, ty) = newTyConRhs tycon in substTyWith tvs tys ty
413 \end{code}
414
415
416 ---------------------------------------------------------------------
417                                 SynTy
418                                 ~~~~~
419
420 Notes on type synonyms
421 ~~~~~~~~~~~~~~~~~~~~~~
422 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
423 to return type synonyms whereever possible. Thus
424
425         type Foo a = a -> a
426
427 we want 
428         splitFunTys (a -> Foo a) = ([a], Foo a)
429 not                                ([a], a -> a)
430
431 The reason is that we then get better (shorter) type signatures in 
432 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
433
434
435                 Representation types
436                 ~~~~~~~~~~~~~~~~~~~~
437 repType looks through 
438         (a) for-alls, and
439         (b) synonyms
440         (c) predicates
441         (d) usage annotations
442         (e) all newtypes, including recursive ones, but not newtype families
443 It's useful in the back end.
444
445 \begin{code}
446 repType :: Type -> Type
447 -- Only applied to types of kind *; hence tycons are saturated
448 repType ty | Just ty' <- coreView ty = repType ty'
449 repType (ForAllTy _ ty)  = repType ty
450 repType (TyConApp tc tys)
451   | isNewTyCon tc
452   , (tvs, rep_ty) <- newTyConRep tc
453   = -- 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( tys `lengthIs` tyConArity tc )
458     repType (substTyWith tvs tys rep_ty)
459
460 repType ty = ty
461
462 -- repType' aims to be a more thorough version of repType
463 -- For now it simply looks through the TyConApp args too
464 repType' ty -- | pprTrace "repType'" (ppr ty $$ ppr (go1 ty)) False = undefined
465             | otherwise = go1 ty 
466  where 
467         go1 = go . repType
468         go (TyConApp tc tys) = mkTyConApp tc (map repType' tys)
469         go ty = ty
470
471
472 -- ToDo: this could be moved to the code generator, using splitTyConApp instead
473 -- of inspecting the type directly.
474 typePrimRep :: Type -> PrimRep
475 typePrimRep ty = case repType ty of
476                    TyConApp tc _ -> tyConPrimRep tc
477                    FunTy _ _     -> PtrRep
478                    AppTy _ _     -> PtrRep      -- See note below
479                    TyVarTy _     -> PtrRep
480                    other         -> pprPanic "typePrimRep" (ppr ty)
481         -- Types of the form 'f a' must be of kind *, not *#, so
482         -- we are guaranteed that they are represented by pointers.
483         -- The reason is that f must have kind *->*, not *->*#, because
484         -- (we claim) there is no way to constrain f's kind any other
485         -- way.
486 \end{code}
487
488
489 ---------------------------------------------------------------------
490                                 ForAllTy
491                                 ~~~~~~~~
492
493 \begin{code}
494 mkForAllTy :: TyVar -> Type -> Type
495 mkForAllTy tyvar ty
496   = mkForAllTys [tyvar] ty
497
498 mkForAllTys :: [TyVar] -> Type -> Type
499 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
500
501 isForAllTy :: Type -> Bool
502 isForAllTy (NoteTy _ ty)  = isForAllTy ty
503 isForAllTy (ForAllTy _ _) = True
504 isForAllTy other_ty       = False
505
506 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
507 splitForAllTy_maybe ty = splitFAT_m ty
508   where
509     splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
510     splitFAT_m (ForAllTy tyvar ty)          = Just(tyvar, ty)
511     splitFAT_m _                            = Nothing
512
513 splitForAllTys :: Type -> ([TyVar], Type)
514 splitForAllTys ty = split ty ty []
515    where
516      split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
517      split orig_ty (ForAllTy tv ty)  tvs = split ty ty (tv:tvs)
518      split orig_ty t                 tvs = (reverse tvs, orig_ty)
519
520 dropForAlls :: Type -> Type
521 dropForAlls ty = snd (splitForAllTys ty)
522 \end{code}
523
524 -- (mkPiType now in CoreUtils)
525
526 applyTy, applyTys
527 ~~~~~~~~~~~~~~~~~
528 Instantiate a for-all type with one or more type arguments.
529 Used when we have a polymorphic function applied to type args:
530         f t1 t2
531 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
532 the expression. 
533
534 \begin{code}
535 applyTy :: Type -> Type -> Type
536 applyTy ty arg | Just ty' <- coreView ty = applyTy ty' arg
537 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
538 applyTy other            arg = panic "applyTy"
539
540 applyTys :: Type -> [Type] -> Type
541 -- This function is interesting because 
542 --      a) the function may have more for-alls than there are args
543 --      b) less obviously, it may have fewer for-alls
544 -- For case (b) think of 
545 --      applyTys (forall a.a) [forall b.b, Int]
546 -- This really can happen, via dressing up polymorphic types with newtype
547 -- clothing.  Here's an example:
548 --      newtype R = R (forall a. a->a)
549 --      foo = case undefined :: R of
550 --              R f -> f ()
551
552 applyTys orig_fun_ty []      = orig_fun_ty
553 applyTys orig_fun_ty arg_tys 
554   | n_tvs == n_args     -- The vastly common case
555   = substTyWith tvs arg_tys rho_ty
556   | n_tvs > n_args      -- Too many for-alls
557   = substTyWith (take n_args tvs) arg_tys 
558                 (mkForAllTys (drop n_args tvs) rho_ty)
559   | otherwise           -- Too many type args
560   = ASSERT2( n_tvs > 0, ppr orig_fun_ty )       -- Zero case gives infnite loop!
561     applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
562              (drop n_tvs arg_tys)
563   where
564     (tvs, rho_ty) = splitForAllTys orig_fun_ty 
565     n_tvs = length tvs
566     n_args = length arg_tys     
567 \end{code}
568
569
570 %************************************************************************
571 %*                                                                      *
572 \subsection{Source types}
573 %*                                                                      *
574 %************************************************************************
575
576 A "source type" is a type that is a separate type as far as the type checker is
577 concerned, but which has low-level representation as far as the back end is concerned.
578
579 Source types are always lifted.
580
581 The key function is predTypeRep which gives the representation of a source type:
582
583 \begin{code}
584 mkPredTy :: PredType -> Type
585 mkPredTy pred = PredTy pred
586
587 mkPredTys :: ThetaType -> [Type]
588 mkPredTys preds = map PredTy preds
589
590 predTypeRep :: PredType -> Type
591 -- Convert a PredType to its "representation type";
592 -- the post-type-checking type used by all the Core passes of GHC.
593 -- Unwraps only the outermost level; for example, the result might
594 -- be a newtype application
595 predTypeRep (IParam _ ty)     = ty
596 predTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
597         -- Result might be a newtype application, but the consumer will
598         -- look through that too if necessary
599 predTypeRep (EqPred ty1 ty2) = pprPanic "predTypeRep" (ppr (EqPred ty1 ty2))
600
601 mkFamilyTyConApp :: TyCon -> [Type] -> Type
602 -- Given a family instance TyCon and its arg types, return the
603 -- corresponding family type.  E.g.
604 --      data family T a
605 --      data instance T (Maybe b) = MkT b       -- Instance tycon :RTL
606 -- Then 
607 --      mkFamilyTyConApp :RTL Int  =  T (Maybe Int)
608 mkFamilyTyConApp tc tys
609   | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
610   , let fam_subst = zipTopTvSubst (tyConTyVars tc) tys
611   = mkTyConApp fam_tc (substTys fam_subst fam_tys)
612   | otherwise
613   = mkTyConApp tc tys
614
615 -- Pretty prints a tycon, using the family instance in case of a
616 -- representation tycon.  For example
617 --      e.g.  data T [a] = ...
618 -- In that case we want to print `T [a]', where T is the family TyCon
619 pprSourceTyCon tycon 
620   | Just (fam_tc, tys) <- tyConFamInst_maybe tycon
621   = ppr $ fam_tc `TyConApp` tys        -- can't be FunTyCon
622   | otherwise
623   = ppr tycon
624 \end{code}
625
626
627 %************************************************************************
628 %*                                                                      *
629 \subsection{Kinds and free variables}
630 %*                                                                      *
631 %************************************************************************
632
633 ---------------------------------------------------------------------
634                 Finding the kind of a type
635                 ~~~~~~~~~~~~~~~~~~~~~~~~~~
636 \begin{code}
637 typeKind :: Type -> Kind
638 typeKind (TyConApp tycon tys) = ASSERT( not (isCoercionTyCon tycon) )
639                                    -- We should be looking for the coercion kind,
640                                    -- not the type kind
641                                 foldr (\_ k -> kindFunResult k) (tyConKind tycon) tys
642 typeKind (NoteTy _ ty)        = typeKind ty
643 typeKind (PredTy pred)        = predKind pred
644 typeKind (AppTy fun arg)      = kindFunResult (typeKind fun)
645 typeKind (ForAllTy tv ty)     = typeKind ty
646 typeKind (TyVarTy tyvar)      = tyVarKind tyvar
647 typeKind (FunTy arg res)
648     -- Hack alert.  The kind of (Int -> Int#) is liftedTypeKind (*), 
649     --              not unliftedTypKind (#)
650     -- The only things that can be after a function arrow are
651     --   (a) types (of kind openTypeKind or its sub-kinds)
652     --   (b) kinds (of super-kind TY) (e.g. * -> (* -> *))
653     | isTySuperKind k         = k
654     | otherwise               = ASSERT( isSubOpenTypeKind k) liftedTypeKind 
655     where
656       k = typeKind res
657
658 predKind :: PredType -> Kind
659 predKind (EqPred {}) = coSuperKind      -- A coercion kind!
660 predKind (ClassP {}) = liftedTypeKind   -- Class and implicitPredicates are
661 predKind (IParam {}) = liftedTypeKind   -- always represented by lifted types
662 \end{code}
663
664
665 ---------------------------------------------------------------------
666                 Free variables of a type
667                 ~~~~~~~~~~~~~~~~~~~~~~~~
668 \begin{code}
669 tyVarsOfType :: Type -> TyVarSet
670 -- NB: for type synonyms tyVarsOfType does *not* expand the synonym
671 tyVarsOfType (TyVarTy tv)               = unitVarSet tv
672 tyVarsOfType (TyConApp tycon tys)       = tyVarsOfTypes tys
673 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
674 tyVarsOfType (PredTy sty)               = tyVarsOfPred sty
675 tyVarsOfType (FunTy arg res)            = tyVarsOfType arg `unionVarSet` tyVarsOfType res
676 tyVarsOfType (AppTy fun arg)            = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
677 tyVarsOfType (ForAllTy tyvar ty)        = delVarSet (tyVarsOfType ty) tyvar
678
679 tyVarsOfTypes :: [Type] -> TyVarSet
680 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
681
682 tyVarsOfPred :: PredType -> TyVarSet
683 tyVarsOfPred (IParam _ ty)    = tyVarsOfType ty
684 tyVarsOfPred (ClassP _ tys)   = tyVarsOfTypes tys
685 tyVarsOfPred (EqPred ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
686
687 tyVarsOfTheta :: ThetaType -> TyVarSet
688 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
689
690 -- Add a Note with the free tyvars to the top of the type
691 addFreeTyVars :: Type -> Type
692 addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
693 addFreeTyVars ty                             = NoteTy (FTVNote (tyVarsOfType ty)) ty
694 \end{code}
695
696
697 %************************************************************************
698 %*                                                                      *
699 \subsection{TidyType}
700 %*                                                                      *
701 %************************************************************************
702
703 tidyTy tidies up a type for printing in an error message, or in
704 an interface file.
705
706 It doesn't change the uniques at all, just the print names.
707
708 \begin{code}
709 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
710 tidyTyVarBndr env@(tidy_env, subst) tyvar
711   = case tidyOccName tidy_env (getOccName name) of
712       (tidy', occ') -> ((tidy', subst'), tyvar'')
713         where
714           subst' = extendVarEnv subst tyvar tyvar''
715           tyvar' = setTyVarName tyvar name'
716           name'  = tidyNameOcc name occ'
717                 -- Don't forget to tidy the kind for coercions!
718           tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
719                   | otherwise     = tyvar'
720           kind'  = tidyType env (tyVarKind tyvar)
721   where
722     name = tyVarName tyvar
723
724 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
725 -- Add the free tyvars to the env in tidy form,
726 -- so that we can tidy the type they are free in
727 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
728
729 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
730 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
731
732 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
733 -- Treat a new tyvar as a binder, and give it a fresh tidy name
734 tidyOpenTyVar env@(tidy_env, subst) tyvar
735   = case lookupVarEnv subst tyvar of
736         Just tyvar' -> (env, tyvar')            -- Already substituted
737         Nothing     -> tidyTyVarBndr env tyvar  -- Treat it as a binder
738
739 tidyType :: TidyEnv -> Type -> Type
740 tidyType env@(tidy_env, subst) ty
741   = go ty
742   where
743     go (TyVarTy tv)         = case lookupVarEnv subst tv of
744                                 Nothing  -> TyVarTy tv
745                                 Just tv' -> TyVarTy tv'
746     go (TyConApp tycon tys) = let args = map go tys
747                               in args `seqList` TyConApp tycon args
748     go (NoteTy note ty)     = (NoteTy $! (go_note note)) $! (go ty)
749     go (PredTy sty)         = PredTy (tidyPred env sty)
750     go (AppTy fun arg)      = (AppTy $! (go fun)) $! (go arg)
751     go (FunTy fun arg)      = (FunTy $! (go fun)) $! (go arg)
752     go (ForAllTy tv ty)     = ForAllTy tvp $! (tidyType envp ty)
753                               where
754                                 (envp, tvp) = tidyTyVarBndr env tv
755
756     go_note note@(FTVNote ftvs) = note  -- No need to tidy the free tyvars
757
758 tidyTypes env tys = map (tidyType env) tys
759
760 tidyPred :: TidyEnv -> PredType -> PredType
761 tidyPred env (IParam n ty)     = IParam n (tidyType env ty)
762 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
763 tidyPred env (EqPred ty1 ty2)  = EqPred (tidyType env ty1) (tidyType env ty2)
764 \end{code}
765
766
767 @tidyOpenType@ grabs the free type variables, tidies them
768 and then uses @tidyType@ to work over the type itself
769
770 \begin{code}
771 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
772 tidyOpenType env ty
773   = (env', tidyType env' ty)
774   where
775     env' = tidyFreeTyVars env (tyVarsOfType ty)
776
777 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
778 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
779
780 tidyTopType :: Type -> Type
781 tidyTopType ty = tidyType emptyTidyEnv ty
782 \end{code}
783
784 \begin{code}
785
786 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
787 tidyKind env k = tidyOpenType env k
788
789 \end{code}
790
791
792 %************************************************************************
793 %*                                                                      *
794 \subsection{Liftedness}
795 %*                                                                      *
796 %************************************************************************
797
798 \begin{code}
799 isUnLiftedType :: Type -> Bool
800         -- isUnLiftedType returns True for forall'd unlifted types:
801         --      x :: forall a. Int#
802         -- I found bindings like these were getting floated to the top level.
803         -- They are pretty bogus types, mind you.  It would be better never to
804         -- construct them
805
806 isUnLiftedType ty | Just ty' <- coreView ty = isUnLiftedType ty'
807 isUnLiftedType (ForAllTy tv ty)  = isUnLiftedType ty
808 isUnLiftedType (TyConApp tc _)   = isUnLiftedTyCon tc
809 isUnLiftedType other             = False        
810
811 isUnboxedTupleType :: Type -> Bool
812 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
813                            Just (tc, ty_args) -> isUnboxedTupleTyCon tc
814                            other              -> False
815
816 -- Should only be applied to *types*; hence the assert
817 isAlgType :: Type -> Bool
818 isAlgType ty = case splitTyConApp_maybe ty of
819                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
820                                               isAlgTyCon tc
821                         other              -> False
822 \end{code}
823
824 @isStrictType@ computes whether an argument (or let RHS) should
825 be computed strictly or lazily, based only on its type.
826 Works just like isUnLiftedType, except that it has a special case 
827 for dictionaries.  Since it takes account of ClassP, you might think
828 this function should be in TcType, but isStrictType is used by DataCon,
829 which is below TcType in the hierarchy, so it's convenient to put it here.
830
831 \begin{code}
832 isStrictType (PredTy pred)     = isStrictPred pred
833 isStrictType ty | Just ty' <- coreView ty = isStrictType ty'
834 isStrictType (ForAllTy tv ty)  = isStrictType ty
835 isStrictType (TyConApp tc _)   = isUnLiftedTyCon tc
836 isStrictType other             = False  
837
838 isStrictPred (ClassP clas _) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
839 isStrictPred other           = False
840         -- We may be strict in dictionary types, but only if it 
841         -- has more than one component.
842         -- [Being strict in a single-component dictionary risks
843         --  poking the dictionary component, which is wrong.]
844 \end{code}
845
846 \begin{code}
847 isPrimitiveType :: Type -> Bool
848 -- Returns types that are opaque to Haskell.
849 -- Most of these are unlifted, but now that we interact with .NET, we
850 -- may have primtive (foreign-imported) types that are lifted
851 isPrimitiveType ty = case splitTyConApp_maybe ty of
852                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
853                                               isPrimTyCon tc
854                         other              -> False
855 \end{code}
856
857
858 %************************************************************************
859 %*                                                                      *
860 \subsection{Sequencing on types
861 %*                                                                      *
862 %************************************************************************
863
864 \begin{code}
865 seqType :: Type -> ()
866 seqType (TyVarTy tv)      = tv `seq` ()
867 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
868 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
869 seqType (NoteTy note t2)  = seqNote note `seq` seqType t2
870 seqType (PredTy p)        = seqPred p
871 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
872 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
873
874 seqTypes :: [Type] -> ()
875 seqTypes []       = ()
876 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
877
878 seqNote :: TyNote -> ()
879 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
880
881 seqPred :: PredType -> ()
882 seqPred (ClassP c tys)   = c `seq` seqTypes tys
883 seqPred (IParam n ty)    = n `seq` seqType ty
884 seqPred (EqPred ty1 ty2) = seqType ty1 `seq` seqType ty2
885 \end{code}
886
887
888 %************************************************************************
889 %*                                                                      *
890                 Equality for Core types 
891         (We don't use instances so that we know where it happens)
892 %*                                                                      *
893 %************************************************************************
894
895 Note that eqType works right even for partial applications of newtypes.
896 See Note [Newtype eta] in TyCon.lhs
897
898 \begin{code}
899 coreEqType :: Type -> Type -> Bool
900 coreEqType t1 t2
901   = eq rn_env t1 t2
902   where
903     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
904
905     eq env (TyVarTy tv1)       (TyVarTy tv2)     = rnOccL env tv1 == rnOccR env tv2
906     eq env (ForAllTy tv1 t1)   (ForAllTy tv2 t2) = eq (rnBndr2 env tv1 tv2) t1 t2
907     eq env (AppTy s1 t1)       (AppTy s2 t2)     = eq env s1 s2 && eq env t1 t2
908     eq env (FunTy s1 t1)       (FunTy s2 t2)     = eq env s1 s2 && eq env t1 t2
909     eq env (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
910         | tc1 == tc2, all2 (eq env) tys1 tys2 = True
911                         -- The lengths should be equal because
912                         -- the two types have the same kind
913         -- NB: if the type constructors differ that does not 
914         --     necessarily mean that the types aren't equal
915         --     (synonyms, newtypes)
916         -- Even if the type constructors are the same, but the arguments
917         -- differ, the two types could be the same (e.g. if the arg is just
918         -- ignored in the RHS).  In both these cases we fall through to an 
919         -- attempt to expand one side or the other.
920
921         -- Now deal with newtypes, synonyms, pred-tys
922     eq env t1 t2 | Just t1' <- coreView t1 = eq env t1' t2 
923                  | Just t2' <- coreView t2 = eq env t1 t2' 
924
925         -- Fall through case; not equal!
926     eq env t1 t2 = False
927 \end{code}
928
929
930 %************************************************************************
931 %*                                                                      *
932                 Comparision for source types 
933         (We don't use instances so that we know where it happens)
934 %*                                                                      *
935 %************************************************************************
936
937 Note that 
938         tcEqType, tcCmpType 
939 do *not* look through newtypes, PredTypes
940
941 \begin{code}
942 tcEqType :: Type -> Type -> Bool
943 tcEqType t1 t2 = isEqual $ cmpType t1 t2
944
945 tcEqTypes :: [Type] -> [Type] -> Bool
946 tcEqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
947
948 tcCmpType :: Type -> Type -> Ordering
949 tcCmpType t1 t2 = cmpType t1 t2
950
951 tcCmpTypes :: [Type] -> [Type] -> Ordering
952 tcCmpTypes tys1 tys2 = cmpTypes tys1 tys2
953
954 tcEqPred :: PredType -> PredType -> Bool
955 tcEqPred p1 p2 = isEqual $ cmpPred p1 p2
956
957 tcCmpPred :: PredType -> PredType -> Ordering
958 tcCmpPred p1 p2 = cmpPred p1 p2
959
960 tcEqTypeX :: RnEnv2 -> Type -> Type -> Bool
961 tcEqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
962 \end{code}
963
964 Now here comes the real worker
965
966 \begin{code}
967 cmpType :: Type -> Type -> Ordering
968 cmpType t1 t2 = cmpTypeX rn_env t1 t2
969   where
970     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfType t1 `unionVarSet` tyVarsOfType t2))
971
972 cmpTypes :: [Type] -> [Type] -> Ordering
973 cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
974   where
975     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfTypes ts1 `unionVarSet` tyVarsOfTypes ts2))
976
977 cmpPred :: PredType -> PredType -> Ordering
978 cmpPred p1 p2 = cmpPredX rn_env p1 p2
979   where
980     rn_env = mkRnEnv2 (mkInScopeSet (tyVarsOfPred p1 `unionVarSet` tyVarsOfPred p2))
981
982 cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering  -- Main workhorse
983 cmpTypeX env t1 t2 | Just t1' <- tcView t1 = cmpTypeX env t1' t2
984                    | Just t2' <- tcView t2 = cmpTypeX env t1 t2'
985
986 cmpTypeX env (TyVarTy tv1)       (TyVarTy tv2)       = rnOccL env tv1 `compare` rnOccR env tv2
987 cmpTypeX env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   = cmpTypeX (rnBndr2 env tv1 tv2) t1 t2
988 cmpTypeX env (AppTy s1 t1)       (AppTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
989 cmpTypeX env (FunTy s1 t1)       (FunTy s2 t2)       = cmpTypeX env s1 s2 `thenCmp` cmpTypeX env t1 t2
990 cmpTypeX env (PredTy p1)         (PredTy p2)         = cmpPredX env p1 p2
991 cmpTypeX env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 `compare` tc2) `thenCmp` cmpTypesX env tys1 tys2
992 cmpTypeX env t1                 (NoteTy _ t2)        = cmpTypeX env t1 t2
993
994     -- Deal with the rest: TyVarTy < AppTy < FunTy < TyConApp < ForAllTy < PredTy
995 cmpTypeX env (AppTy _ _) (TyVarTy _) = GT
996     
997 cmpTypeX env (FunTy _ _) (TyVarTy _) = GT
998 cmpTypeX env (FunTy _ _) (AppTy _ _) = GT
999     
1000 cmpTypeX env (TyConApp _ _) (TyVarTy _) = GT
1001 cmpTypeX env (TyConApp _ _) (AppTy _ _) = GT
1002 cmpTypeX env (TyConApp _ _) (FunTy _ _) = GT
1003     
1004 cmpTypeX env (ForAllTy _ _) (TyVarTy _)    = GT
1005 cmpTypeX env (ForAllTy _ _) (AppTy _ _)    = GT
1006 cmpTypeX env (ForAllTy _ _) (FunTy _ _)    = GT
1007 cmpTypeX env (ForAllTy _ _) (TyConApp _ _) = GT
1008
1009 cmpTypeX env (PredTy _)   t2            = GT
1010
1011 cmpTypeX env _ _ = LT
1012
1013 -------------
1014 cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
1015 cmpTypesX env []        []        = EQ
1016 cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2 `thenCmp` cmpTypesX env tys1 tys2
1017 cmpTypesX env []        tys       = LT
1018 cmpTypesX env ty        []        = GT
1019
1020 -------------
1021 cmpPredX :: RnEnv2 -> PredType -> PredType -> Ordering
1022 cmpPredX env (IParam n1 ty1) (IParam n2 ty2) = (n1 `compare` n2) `thenCmp` cmpTypeX env ty1 ty2
1023         -- Compare names only for implicit parameters
1024         -- This comparison is used exclusively (I believe) 
1025         -- for the Avails finite map built in TcSimplify
1026         -- If the types differ we keep them distinct so that we see 
1027         -- a distinct pair to run improvement on 
1028 cmpPredX env (ClassP c1 tys1) (ClassP c2 tys2) = (c1 `compare` c2) `thenCmp` (cmpTypesX env tys1 tys2)
1029 cmpPredX env (EqPred ty1 ty2) (EqPred ty1' ty2') = (cmpTypeX env ty1 ty1') `thenCmp` (cmpTypeX env ty2 ty2')
1030
1031 -- Constructor order: IParam < ClassP < EqPred
1032 cmpPredX env (IParam {})     _              = LT
1033 cmpPredX env (ClassP {})    (IParam {})     = GT
1034 cmpPredX env (ClassP {})    (EqPred {})     = LT
1035 cmpPredX env (EqPred {})    _               = GT
1036 \end{code}
1037
1038 PredTypes are used as a FM key in TcSimplify, 
1039 so we take the easy path and make them an instance of Ord
1040
1041 \begin{code}
1042 instance Eq  PredType where { (==)    = tcEqPred }
1043 instance Ord PredType where { compare = tcCmpPred }
1044 \end{code}
1045
1046
1047 %************************************************************************
1048 %*                                                                      *
1049                 Type substitutions
1050 %*                                                                      *
1051 %************************************************************************
1052
1053 \begin{code}
1054 data TvSubst            
1055   = TvSubst InScopeSet  -- The in-scope type variables
1056             TvSubstEnv  -- The substitution itself
1057         -- See Note [Apply Once]
1058         -- and Note [Extending the TvSubstEnv]
1059
1060 {- ----------------------------------------------------------
1061
1062 Note [Apply Once]
1063 ~~~~~~~~~~~~~~~~~
1064 We use TvSubsts to instantiate things, and we might instantiate
1065         forall a b. ty
1066 \with the types
1067         [a, b], or [b, a].
1068 So the substition might go [a->b, b->a].  A similar situation arises in Core
1069 when we find a beta redex like
1070         (/\ a /\ b -> e) b a
1071 Then we also end up with a substition that permutes type variables. Other
1072 variations happen to; for example [a -> (a, b)].  
1073
1074         ***************************************************
1075         *** So a TvSubst must be applied precisely once ***
1076         ***************************************************
1077
1078 A TvSubst is not idempotent, but, unlike the non-idempotent substitution
1079 we use during unifications, it must not be repeatedly applied.
1080
1081 Note [Extending the TvSubst]
1082 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1083 The following invariant should hold of a TvSubst
1084
1085         The in-scope set is needed *only* to
1086         guide the generation of fresh uniques
1087
1088         In particular, the *kind* of the type variables in 
1089         the in-scope set is not relevant
1090
1091 This invariant allows a short-cut when the TvSubstEnv is empty:
1092 if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
1093 then (substTy subst ty) does nothing.
1094
1095 For example, consider:
1096         (/\a. /\b:(a~Int). ...b..) Int
1097 We substitute Int for 'a'.  The Unique of 'b' does not change, but
1098 nevertheless we add 'b' to the TvSubstEnv, because b's type does change
1099
1100 This invariant has several crucial consequences:
1101
1102 * In substTyVarBndr, we need extend the TvSubstEnv 
1103         - if the unique has changed
1104         - or if the kind has changed
1105
1106 * In substTyVar, we do not need to consult the in-scope set;
1107   the TvSubstEnv is enough
1108
1109 * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
1110   
1111
1112 -------------------------------------------------------------- -}
1113
1114
1115 type TvSubstEnv = TyVarEnv Type
1116         -- A TvSubstEnv is used both inside a TvSubst (with the apply-once
1117         -- invariant discussed in Note [Apply Once]), and also independently
1118         -- in the middle of matching, and unification (see Types.Unify)
1119         -- So you have to look at the context to know if it's idempotent or
1120         -- apply-once or whatever
1121 emptyTvSubstEnv :: TvSubstEnv
1122 emptyTvSubstEnv = emptyVarEnv
1123
1124 composeTvSubst :: InScopeSet -> TvSubstEnv -> TvSubstEnv -> TvSubstEnv
1125 -- (compose env1 env2)(x) is env1(env2(x)); i.e. apply env2 then env1
1126 -- It assumes that both are idempotent
1127 -- Typically, env1 is the refinement to a base substitution env2
1128 composeTvSubst in_scope env1 env2
1129   = env1 `plusVarEnv` mapVarEnv (substTy subst1) env2
1130         -- First apply env1 to the range of env2
1131         -- Then combine the two, making sure that env1 loses if
1132         -- both bind the same variable; that's why env1 is the
1133         --  *left* argument to plusVarEnv, because the right arg wins
1134   where
1135     subst1 = TvSubst in_scope env1
1136
1137 emptyTvSubst = TvSubst emptyInScopeSet emptyVarEnv
1138
1139 isEmptyTvSubst :: TvSubst -> Bool
1140          -- See Note [Extending the TvSubstEnv]
1141 isEmptyTvSubst (TvSubst _ env) = isEmptyVarEnv env
1142
1143 mkTvSubst :: InScopeSet -> TvSubstEnv -> TvSubst
1144 mkTvSubst = TvSubst
1145
1146 getTvSubstEnv :: TvSubst -> TvSubstEnv
1147 getTvSubstEnv (TvSubst _ env) = env
1148
1149 getTvInScope :: TvSubst -> InScopeSet
1150 getTvInScope (TvSubst in_scope _) = in_scope
1151
1152 isInScope :: Var -> TvSubst -> Bool
1153 isInScope v (TvSubst in_scope _) = v `elemInScopeSet` in_scope
1154
1155 notElemTvSubst :: TyVar -> TvSubst -> Bool
1156 notElemTvSubst tv (TvSubst _ env) = not (tv `elemVarEnv` env)
1157
1158 setTvSubstEnv :: TvSubst -> TvSubstEnv -> TvSubst
1159 setTvSubstEnv (TvSubst in_scope _) env = TvSubst in_scope env
1160
1161 extendTvInScope :: TvSubst -> [Var] -> TvSubst
1162 extendTvInScope (TvSubst in_scope env) vars = TvSubst (extendInScopeSetList in_scope vars) env
1163
1164 extendTvSubst :: TvSubst -> TyVar -> Type -> TvSubst
1165 extendTvSubst (TvSubst in_scope env) tv ty = TvSubst in_scope (extendVarEnv env tv ty)
1166
1167 extendTvSubstList :: TvSubst -> [TyVar] -> [Type] -> TvSubst
1168 extendTvSubstList (TvSubst in_scope env) tvs tys 
1169   = TvSubst in_scope (extendVarEnvList env (tvs `zip` tys))
1170
1171 -- mkOpenTvSubst and zipOpenTvSubst generate the in-scope set from
1172 -- the types given; but it's just a thunk so with a bit of luck
1173 -- it'll never be evaluated
1174
1175 mkOpenTvSubst :: TvSubstEnv -> TvSubst
1176 mkOpenTvSubst env = TvSubst (mkInScopeSet (tyVarsOfTypes (varEnvElts env))) env
1177
1178 zipOpenTvSubst :: [TyVar] -> [Type] -> TvSubst
1179 zipOpenTvSubst tyvars tys 
1180 #ifdef DEBUG
1181   | length tyvars /= length tys
1182   = pprTrace "zipOpenTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1183   | otherwise
1184 #endif
1185   = TvSubst (mkInScopeSet (tyVarsOfTypes tys)) (zipTyEnv tyvars tys)
1186
1187 -- mkTopTvSubst is called when doing top-level substitutions.
1188 -- Here we expect that the free vars of the range of the
1189 -- substitution will be empty.
1190 mkTopTvSubst :: [(TyVar, Type)] -> TvSubst
1191 mkTopTvSubst prs = TvSubst emptyInScopeSet (mkVarEnv prs)
1192
1193 zipTopTvSubst :: [TyVar] -> [Type] -> TvSubst
1194 zipTopTvSubst tyvars tys 
1195 #ifdef DEBUG
1196   | length tyvars /= length tys
1197   = pprTrace "zipTopTvSubst" (ppr tyvars $$ ppr tys) emptyTvSubst
1198   | otherwise
1199 #endif
1200   = TvSubst emptyInScopeSet (zipTyEnv tyvars tys)
1201
1202 zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv
1203 zipTyEnv tyvars tys
1204 #ifdef DEBUG
1205   | length tyvars /= length tys
1206   = pprTrace "mkTopTvSubst" (ppr tyvars $$ ppr tys) emptyVarEnv
1207   | otherwise
1208 #endif
1209   = zip_ty_env tyvars tys emptyVarEnv
1210
1211 -- Later substitutions in the list over-ride earlier ones, 
1212 -- but there should be no loops
1213 zip_ty_env []       []       env = env
1214 zip_ty_env (tv:tvs) (ty:tys) env = zip_ty_env tvs tys (extendVarEnv env tv ty)
1215         -- There used to be a special case for when 
1216         --      ty == TyVarTy tv
1217         -- (a not-uncommon case) in which case the substitution was dropped.
1218         -- But the type-tidier changes the print-name of a type variable without
1219         -- changing the unique, and that led to a bug.   Why?  Pre-tidying, we had 
1220         -- a type {Foo t}, where Foo is a one-method class.  So Foo is really a newtype.
1221         -- And it happened that t was the type variable of the class.  Post-tiding, 
1222         -- it got turned into {Foo t2}.  The ext-core printer expanded this using
1223         -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique,
1224         -- and so generated a rep type mentioning t not t2.  
1225         --
1226         -- Simplest fix is to nuke the "optimisation"
1227 zip_ty_env tvs      tys      env   = pprTrace "Var/Type length mismatch: " (ppr tvs $$ ppr tys) env
1228 -- zip_ty_env _ _ env = env
1229
1230 instance Outputable TvSubst where
1231   ppr (TvSubst ins env) 
1232     = brackets $ sep[ ptext SLIT("TvSubst"),
1233                       nest 2 (ptext SLIT("In scope:") <+> ppr ins), 
1234                       nest 2 (ptext SLIT("Env:") <+> ppr env) ]
1235 \end{code}
1236
1237 %************************************************************************
1238 %*                                                                      *
1239                 Performing type substitutions
1240 %*                                                                      *
1241 %************************************************************************
1242
1243 \begin{code}
1244 substTyWith :: [TyVar] -> [Type] -> Type -> Type
1245 substTyWith tvs tys = ASSERT( length tvs == length tys )
1246                       substTy (zipOpenTvSubst tvs tys)
1247
1248 substTy :: TvSubst -> Type  -> Type
1249 substTy subst ty | isEmptyTvSubst subst = ty
1250                  | otherwise            = subst_ty subst ty
1251
1252 substTys :: TvSubst -> [Type] -> [Type]
1253 substTys subst tys | isEmptyTvSubst subst = tys
1254                    | otherwise            = map (subst_ty subst) tys
1255
1256 substTheta :: TvSubst -> ThetaType -> ThetaType
1257 substTheta subst theta
1258   | isEmptyTvSubst subst = theta
1259   | otherwise            = map (substPred subst) theta
1260
1261 substPred :: TvSubst -> PredType -> PredType
1262 substPred subst (IParam n ty)     = IParam n (subst_ty subst ty)
1263 substPred subst (ClassP clas tys) = ClassP clas (map (subst_ty subst) tys)
1264 substPred subst (EqPred ty1 ty2)  = EqPred (subst_ty subst ty1) (subst_ty subst ty2)
1265
1266 deShadowTy :: TyVarSet -> Type -> Type  -- Remove any nested binders mentioning tvs
1267 deShadowTy tvs ty 
1268   = subst_ty (mkTvSubst in_scope emptyTvSubstEnv) ty
1269   where
1270     in_scope = mkInScopeSet tvs
1271
1272 subst_ty :: TvSubst -> Type -> Type
1273 -- subst_ty is the main workhorse for type substitution
1274 --
1275 -- Note that the in_scope set is poked only if we hit a forall
1276 -- so it may often never be fully computed 
1277 subst_ty subst ty
1278    = go ty
1279   where
1280     go (TyVarTy tv)                = substTyVar subst tv
1281     go (TyConApp tc tys)           = let args = map go tys
1282                                      in  args `seqList` TyConApp tc args
1283
1284     go (PredTy p)                  = PredTy $! (substPred subst p)
1285
1286     go (NoteTy (FTVNote _) ty2)    = go ty2             -- Discard the free tyvar note
1287
1288     go (FunTy arg res)             = (FunTy $! (go arg)) $! (go res)
1289     go (AppTy fun arg)             = mkAppTy (go fun) $! (go arg)
1290                 -- The mkAppTy smart constructor is important
1291                 -- we might be replacing (a Int), represented with App
1292                 -- by [Int], represented with TyConApp
1293     go (ForAllTy tv ty)            = case substTyVarBndr subst tv of
1294                                         (subst', tv') -> ForAllTy tv' $! (subst_ty subst' ty)
1295
1296 substTyVar :: TvSubst -> TyVar  -> Type
1297 substTyVar subst@(TvSubst in_scope env) tv
1298   = case lookupTyVar subst tv of {
1299         Nothing -> TyVarTy tv;
1300         Just ty -> ty   -- See Note [Apply Once]
1301     } 
1302
1303 substTyVars :: TvSubst -> [TyVar] -> [Type]
1304 substTyVars subst tvs = map (substTyVar subst) tvs
1305
1306 lookupTyVar :: TvSubst -> TyVar  -> Maybe Type
1307         -- See Note [Extending the TvSubst]
1308 lookupTyVar (TvSubst in_scope env) tv = lookupVarEnv env tv
1309
1310 substTyVarBndr :: TvSubst -> TyVar -> (TvSubst, TyVar)  
1311 substTyVarBndr subst@(TvSubst in_scope env) old_var
1312   = (TvSubst (in_scope `extendInScopeSet` new_var) new_env, new_var)
1313   where
1314     is_co_var = isCoVar old_var
1315
1316     new_env | no_change = delVarEnv env old_var
1317             | otherwise = extendVarEnv env old_var (TyVarTy new_var)
1318
1319     no_change = new_var == old_var && not is_co_var
1320         -- no_change means that the new_var is identical in
1321         -- all respects to the old_var (same unique, same kind)
1322         -- See Note [Extending the TvSubst]
1323         --
1324         -- In that case we don't need to extend the substitution
1325         -- to map old to new.  But instead we must zap any 
1326         -- current substitution for the variable. For example:
1327         --      (\x.e) with id_subst = [x |-> e']
1328         -- Here we must simply zap the substitution for x
1329
1330     new_var = uniqAway in_scope subst_old_var
1331         -- The uniqAway part makes sure the new variable is not already in scope
1332
1333     subst_old_var -- subst_old_var is old_var with the substitution applied to its kind
1334                   -- It's only worth doing the substitution for coercions,
1335                   -- becuase only they can have free type variables
1336         | is_co_var = setTyVarKind old_var (substTy subst (tyVarKind old_var))
1337         | otherwise = old_var
1338 \end{code}
1339
1340 ----------------------------------------------------
1341 -- Kind Stuff
1342
1343 Kinds
1344 ~~~~~
1345 There's a little subtyping at the kind level:  
1346
1347                  ?
1348                 / \
1349                /   \
1350               ??   (#)
1351              /  \
1352             *   #
1353
1354 where   *    [LiftedTypeKind]   means boxed type
1355         #    [UnliftedTypeKind] means unboxed type
1356         (#)  [UbxTupleKind]     means unboxed tuple
1357         ??   [ArgTypeKind]      is the lub of *,#
1358         ?    [OpenTypeKind]     means any type at all
1359
1360 In particular:
1361
1362         error :: forall a:?. String -> a
1363         (->)  :: ?? -> ? -> *
1364         (\(x::t) -> ...)        Here t::?? (i.e. not unboxed tuple)
1365
1366 \begin{code}
1367 type KindVar = TyVar  -- invariant: KindVar will always be a 
1368                       -- TcTyVar with details MetaTv TauTv ...
1369 -- kind var constructors and functions are in TcType
1370
1371 type SimpleKind = Kind
1372 \end{code}
1373
1374 Kind inference
1375 ~~~~~~~~~~~~~~
1376 During kind inference, a kind variable unifies only with 
1377 a "simple kind", sk
1378         sk ::= * | sk1 -> sk2
1379 For example 
1380         data T a = MkT a (T Int#)
1381 fails.  We give T the kind (k -> *), and the kind variable k won't unify
1382 with # (the kind of Int#).
1383
1384 Type inference
1385 ~~~~~~~~~~~~~~
1386 When creating a fresh internal type variable, we give it a kind to express 
1387 constraints on it.  E.g. in (\x->e) we make up a fresh type variable for x, 
1388 with kind ??.  
1389
1390 During unification we only bind an internal type variable to a type
1391 whose kind is lower in the sub-kind hierarchy than the kind of the tyvar.
1392
1393 When unifying two internal type variables, we collect their kind constraints by
1394 finding the GLB of the two.  Since the partial order is a tree, they only
1395 have a glb if one is a sub-kind of the other.  In that case, we bind the
1396 less-informative one to the more informative one.  Neat, eh?
1397
1398
1399 \begin{code}
1400
1401 \end{code}
1402
1403 %************************************************************************
1404 %*                                                                      *
1405         Functions over Kinds            
1406 %*                                                                      *
1407 %************************************************************************
1408
1409 \begin{code}
1410 kindFunResult :: Kind -> Kind
1411 kindFunResult k = funResultTy k
1412
1413 splitKindFunTys :: Kind -> ([Kind],Kind)
1414 splitKindFunTys k = splitFunTys k
1415
1416 splitKindFunTysN :: Int -> Kind -> ([Kind],Kind)
1417 splitKindFunTysN k = splitFunTysN k
1418
1419 isUbxTupleKind, isOpenTypeKind, isArgTypeKind, isUnliftedTypeKind :: Kind -> Bool
1420
1421 isOpenTypeKindCon tc    = tyConUnique tc == openTypeKindTyConKey
1422
1423 isOpenTypeKind (TyConApp tc _) = isOpenTypeKindCon tc
1424 isOpenTypeKind other           = False
1425
1426 isUbxTupleKindCon tc = tyConUnique tc == ubxTupleKindTyConKey
1427
1428 isUbxTupleKind (TyConApp tc _) = isUbxTupleKindCon tc
1429 isUbxTupleKind other           = False
1430
1431 isArgTypeKindCon tc = tyConUnique tc == argTypeKindTyConKey
1432
1433 isArgTypeKind (TyConApp tc _) = isArgTypeKindCon tc
1434 isArgTypeKind other = False
1435
1436 isUnliftedTypeKindCon tc = tyConUnique tc == unliftedTypeKindTyConKey
1437
1438 isUnliftedTypeKind (TyConApp tc _) = isUnliftedTypeKindCon tc
1439 isUnliftedTypeKind other           = False
1440
1441 isSubOpenTypeKind :: Kind -> Bool
1442 -- True of any sub-kind of OpenTypeKind (i.e. anything except arrow)
1443 isSubOpenTypeKind (FunTy k1 k2)    = ASSERT2 ( isKind k1, text "isSubOpenTypeKind" <+> ppr k1 <+> text "::" <+> ppr (typeKind k1) ) 
1444                                      ASSERT2 ( isKind k2, text "isSubOpenTypeKind" <+> ppr k2 <+> text "::" <+> ppr (typeKind k2) ) 
1445                                      False
1446 isSubOpenTypeKind (TyConApp kc []) = ASSERT( isKind (TyConApp kc []) ) True
1447 isSubOpenTypeKind other            = ASSERT( isKind other ) False
1448          -- This is a conservative answer
1449          -- It matters in the call to isSubKind in
1450          -- checkExpectedKind.
1451
1452 isSubArgTypeKindCon kc
1453   | isUnliftedTypeKindCon kc = True
1454   | isLiftedTypeKindCon kc   = True
1455   | isArgTypeKindCon kc      = True
1456   | otherwise                = False
1457
1458 isSubArgTypeKind :: Kind -> Bool
1459 -- True of any sub-kind of ArgTypeKind 
1460 isSubArgTypeKind (TyConApp kc []) = isSubArgTypeKindCon kc
1461 isSubArgTypeKind other            = False
1462
1463 isSuperKind :: Type -> Bool
1464 isSuperKind (TyConApp (skc) []) = isSuperKindTyCon skc
1465 isSuperKind other = False
1466
1467 isKind :: Kind -> Bool
1468 isKind k = isSuperKind (typeKind k)
1469
1470 isSubKind :: Kind -> Kind -> Bool
1471 -- (k1 `isSubKind` k2) checks that k1 <: k2
1472 isSubKind (TyConApp kc1 []) (TyConApp kc2 []) = kc1 `isSubKindCon` kc2
1473 isSubKind (FunTy a1 r1) (FunTy a2 r2)         = (a2 `isSubKind` a1) && (r1 `isSubKind` r2)
1474 isSubKind (PredTy (EqPred ty1 ty2)) (PredTy (EqPred ty1' ty2')) 
1475   = ty1 `tcEqType` ty1' && ty2 `tcEqType` ty2'
1476 isSubKind k1            k2                    = False
1477
1478 eqKind :: Kind -> Kind -> Bool
1479 eqKind = tcEqType
1480
1481 isSubKindCon :: TyCon -> TyCon -> Bool
1482 -- (kc1 `isSubKindCon` kc2) checks that kc1 <: kc2
1483 isSubKindCon kc1 kc2
1484   | isLiftedTypeKindCon kc1   && isLiftedTypeKindCon kc2   = True
1485   | isUnliftedTypeKindCon kc1 && isUnliftedTypeKindCon kc2 = True
1486   | isUbxTupleKindCon kc1     && isUbxTupleKindCon kc2     = True
1487   | isOpenTypeKindCon kc2                                  = True 
1488                            -- we already know kc1 is not a fun, its a TyCon
1489   | isArgTypeKindCon kc2      && isSubArgTypeKindCon kc1   = True
1490   | otherwise                                              = False
1491
1492 defaultKind :: Kind -> Kind
1493 -- Used when generalising: default kind '?' and '??' to '*'
1494 -- 
1495 -- When we generalise, we make generic type variables whose kind is
1496 -- simple (* or *->* etc).  So generic type variables (other than
1497 -- built-in constants like 'error') always have simple kinds.  This is important;
1498 -- consider
1499 --      f x = True
1500 -- We want f to get type
1501 --      f :: forall (a::*). a -> Bool
1502 -- Not 
1503 --      f :: forall (a::??). a -> Bool
1504 -- because that would allow a call like (f 3#) as well as (f True),
1505 --and the calling conventions differ.  This defaulting is done in TcMType.zonkTcTyVarBndr.
1506 defaultKind k 
1507   | isSubOpenTypeKind k = liftedTypeKind
1508   | isSubArgTypeKind k  = liftedTypeKind
1509   | otherwise        = k
1510
1511 isEqPred :: PredType -> Bool
1512 isEqPred (EqPred _ _) = True
1513 isEqPred other        = False
1514 \end{code}