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