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