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