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