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