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