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