[project @ 2003-07-28 12:04:27 by simonpj]
[ghc-hetmet.git] / ghc / compiler / types / Type.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1998
3 %
4 \section[Type]{Type - public interface}
5
6 \begin{code}
7 module Type (
8         -- re-exports from TypeRep:
9         Type, PredType, ThetaType,
10         Kind, TyVarSubst, 
11
12         superKind, superBoxity,                         -- KX and BX respectively
13         liftedBoxity, unliftedBoxity,                   -- :: BX
14         openKindCon,                                    -- :: KX
15         typeCon,                                        -- :: BX -> KX
16         liftedTypeKind, unliftedTypeKind, openTypeKind, -- :: KX
17         mkArrowKind, mkArrowKinds,                      -- :: KX -> KX -> KX
18         isTypeKind, isAnyTypeKind,
19         funTyCon,
20
21         -- exports from this module:
22         hasMoreBoxityInfo, defaultKind,
23
24         mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
25
26         mkAppTy, mkAppTys, splitAppTy, splitAppTys, splitAppTy_maybe,
27
28         mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, splitFunTys, 
29         funResultTy, funArgTy, zipFunTys, isFunTy,
30
31         mkGenTyConApp, mkTyConApp, mkTyConTy, 
32         tyConAppTyCon, tyConAppArgs, 
33         splitTyConApp_maybe, splitTyConApp,
34
35         mkSynTy, 
36
37         repType, typePrimRep,
38
39         mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
40         applyTy, applyTys, isForAllTy, dropForAlls,
41
42         -- Source types
43         SourceType(..), sourceTypeRep, mkPredTy, mkPredTys,
44
45         -- Newtypes
46         splitNewType_maybe,
47
48         -- Lifting and boxity
49         isUnLiftedType, isUnboxedTupleType, isAlgType, isStrictType, isPrimitiveType,
50
51         -- Free variables
52         tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
53         typeKind, addFreeTyVars,
54
55         -- Tidying up for printing
56         tidyType,      tidyTypes,
57         tidyOpenType,  tidyOpenTypes,
58         tidyTyVarBndr, tidyFreeTyVars,
59         tidyOpenTyVar, tidyOpenTyVars,
60         tidyTopType,   tidyPred,
61
62         -- Comparison
63         eqType, eqKind, 
64
65         -- Seq
66         seqType, seqTypes
67
68     ) where
69
70 #include "HsVersions.h"
71
72 -- We import the representation and primitive functions from TypeRep.
73 -- Many things are reexported, but not the representation!
74
75 import TypeRep
76
77 -- Other imports:
78
79 import {-# SOURCE #-}   PprType( pprType )      -- Only called in debug messages
80 import {-# SOURCE #-}   Subst  ( substTyWith )
81
82 -- friends:
83 import Var      ( Id, TyVar, tyVarKind, tyVarName, setTyVarName )
84 import VarEnv
85 import VarSet
86
87 import Name     ( NamedThing(..), mkInternalName, tidyOccName )
88 import Class    ( Class, classTyCon )
89 import TyCon    ( TyCon, isRecursiveTyCon, isPrimTyCon,
90                   isUnboxedTupleTyCon, isUnLiftedTyCon,
91                   isFunTyCon, isNewTyCon, newTyConRep,
92                   isAlgTyCon, isSynTyCon, tyConArity, 
93                   tyConKind, getSynTyConDefn,
94                   tyConPrimRep, 
95                 )
96
97 -- others
98 import CmdLineOpts      ( opt_DictsStrict )
99 import SrcLoc           ( noSrcLoc )
100 import PrimRep          ( PrimRep(..) )
101 import Unique           ( Uniquable(..) )
102 import Util             ( mapAccumL, seqList, lengthIs, snocView )
103 import Outputable
104 import UniqSet          ( sizeUniqSet )         -- Should come via VarSet
105 import Maybe            ( isJust )
106 \end{code}
107
108
109 %************************************************************************
110 %*                                                                      *
111 \subsection{Stuff to do with kinds.}
112 %*                                                                      *
113 %************************************************************************
114
115 \begin{code}
116 hasMoreBoxityInfo :: Kind -> Kind -> Bool
117 -- (k1 `hasMoreBoxityInfo` k2) checks that k1 <: k2
118 hasMoreBoxityInfo k1 k2
119   | k2 `eqKind` openTypeKind = isAnyTypeKind k1
120   | otherwise                = k1 `eqKind` k2
121   where
122
123 isAnyTypeKind :: Kind -> Bool
124 -- True of kind * and *# and ?
125 isAnyTypeKind (TyConApp tc _) = tc == typeCon || tc == openKindCon
126 isAnyTypeKind (NoteTy _ k)    = isAnyTypeKind k
127 isAnyTypeKind other           = False
128
129 isTypeKind :: Kind -> Bool
130 -- True of kind * and *#
131 isTypeKind (TyConApp tc _) = tc == typeCon
132 isTypeKind (NoteTy _ k)    = isTypeKind k
133 isTypeKind other           = False
134
135 defaultKind :: Kind -> Kind
136 -- Used when generalising: default kind '?' to '*'
137 defaultKind kind | kind `eqKind` openTypeKind = liftedTypeKind
138                  | otherwise                  = kind
139 \end{code}
140
141
142 %************************************************************************
143 %*                                                                      *
144 \subsection{Constructor-specific functions}
145 %*                                                                      *
146 %************************************************************************
147
148
149 ---------------------------------------------------------------------
150                                 TyVarTy
151                                 ~~~~~~~
152 \begin{code}
153 mkTyVarTy  :: TyVar   -> Type
154 mkTyVarTy  = TyVarTy
155
156 mkTyVarTys :: [TyVar] -> [Type]
157 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
158
159 getTyVar :: String -> Type -> TyVar
160 getTyVar msg (TyVarTy tv)     = tv
161 getTyVar msg (SourceTy p)     = getTyVar msg (sourceTypeRep p)
162 getTyVar msg (NoteTy _ t)     = getTyVar msg t
163 getTyVar msg other            = panic ("getTyVar: " ++ msg)
164
165 getTyVar_maybe :: Type -> Maybe TyVar
166 getTyVar_maybe (TyVarTy tv)     = Just tv
167 getTyVar_maybe (NoteTy _ t)     = getTyVar_maybe t
168 getTyVar_maybe (SourceTy p)     = getTyVar_maybe (sourceTypeRep p)
169 getTyVar_maybe other            = Nothing
170
171 isTyVarTy :: Type -> Bool
172 isTyVarTy (TyVarTy tv)     = True
173 isTyVarTy (NoteTy _ ty)    = isTyVarTy ty
174 isTyVarTy (SourceTy p)     = isTyVarTy (sourceTypeRep p)
175 isTyVarTy other            = False
176 \end{code}
177
178
179 ---------------------------------------------------------------------
180                                 AppTy
181                                 ~~~~~
182 We need to be pretty careful with AppTy to make sure we obey the 
183 invariant that a TyConApp is always visibly so.  mkAppTy maintains the
184 invariant: use it.
185
186 \begin{code}
187 mkAppTy orig_ty1 orig_ty2
188   = ASSERT( not (isSourceTy orig_ty1) ) -- Source types are of kind *
189     mk_app orig_ty1
190   where
191     mk_app (NoteTy _ ty1)    = mk_app ty1
192     mk_app (TyConApp tc tys) = mkGenTyConApp tc (tys ++ [orig_ty2])
193     mk_app ty1               = AppTy orig_ty1 orig_ty2
194         -- We call mkGenTyConApp because the TyConApp could be an 
195         -- under-saturated type synonym.  GHC allows that; e.g.
196         --      type Foo k = k a -> k a
197         --      type Id x = x
198         --      foo :: Foo Id -> Foo Id
199         --
200         -- Here Id is partially applied in the type sig for Foo,
201         -- but once the type synonyms are expanded all is well
202
203 mkAppTys :: Type -> [Type] -> Type
204 mkAppTys orig_ty1 []        = orig_ty1
205         -- This check for an empty list of type arguments
206         -- avoids the needless loss of a type synonym constructor.
207         -- For example: mkAppTys Rational []
208         --   returns to (Ratio Integer), which has needlessly lost
209         --   the Rational part.
210 mkAppTys orig_ty1 orig_tys2
211   = ASSERT( not (isSourceTy orig_ty1) ) -- Source types are of kind *
212     mk_app orig_ty1
213   where
214     mk_app (NoteTy _ ty1)    = mk_app ty1
215     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
216     mk_app ty1               = foldl AppTy orig_ty1 orig_tys2
217
218 splitAppTy_maybe :: Type -> Maybe (Type, Type)
219 splitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
220 splitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
221 splitAppTy_maybe (NoteTy _ ty)     = splitAppTy_maybe ty
222 splitAppTy_maybe (SourceTy p)      = splitAppTy_maybe (sourceTypeRep p)
223 splitAppTy_maybe (TyConApp tc tys) = case snocView tys of
224                                         Nothing -> Nothing
225                                         Just (tys',ty') -> Just (TyConApp tc tys', ty')
226 splitAppTy_maybe other             = Nothing
227
228 splitAppTy :: Type -> (Type, Type)
229 splitAppTy ty = case splitAppTy_maybe ty of
230                         Just pr -> pr
231                         Nothing -> panic "splitAppTy"
232
233 splitAppTys :: Type -> (Type, [Type])
234 splitAppTys ty = split ty ty []
235   where
236     split orig_ty (AppTy ty arg)        args = split ty ty (arg:args)
237     split orig_ty (NoteTy _ ty)         args = split orig_ty ty args
238     split orig_ty (SourceTy p)          args = split orig_ty (sourceTypeRep p) args
239     split orig_ty (FunTy ty1 ty2)       args = ASSERT( null args )
240                                                (TyConApp funTyCon [], [ty1,ty2])
241     split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
242     split orig_ty ty                    args = (orig_ty, args)
243 \end{code}
244
245
246 ---------------------------------------------------------------------
247                                 FunTy
248                                 ~~~~~
249
250 \begin{code}
251 mkFunTy :: Type -> Type -> Type
252 mkFunTy arg res = FunTy arg res
253
254 mkFunTys :: [Type] -> Type -> Type
255 mkFunTys tys ty = foldr FunTy ty tys
256
257 isFunTy :: Type -> Bool 
258 isFunTy ty = isJust (splitFunTy_maybe ty)
259
260 splitFunTy :: Type -> (Type, Type)
261 splitFunTy (FunTy arg res) = (arg, res)
262 splitFunTy (NoteTy _ ty)   = splitFunTy ty
263 splitFunTy (SourceTy p)    = splitFunTy (sourceTypeRep p)
264
265 splitFunTy_maybe :: Type -> Maybe (Type, Type)
266 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
267 splitFunTy_maybe (NoteTy _ ty)   = splitFunTy_maybe ty
268 splitFunTy_maybe (SourceTy p)    = splitFunTy_maybe (sourceTypeRep p)
269 splitFunTy_maybe other           = Nothing
270
271 splitFunTys :: Type -> ([Type], Type)
272 splitFunTys ty = split [] ty ty
273   where
274     split args orig_ty (FunTy arg res) = split (arg:args) res res
275     split args orig_ty (NoteTy _ ty)   = split args orig_ty ty
276     split args orig_ty (SourceTy p)    = split args orig_ty (sourceTypeRep p)
277     split args orig_ty ty              = (reverse args, orig_ty)
278
279 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
280 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
281   where
282     split acc []     nty ty              = (reverse acc, nty)
283     split acc (x:xs) nty (FunTy arg res) = split ((x,arg):acc) xs res res
284     split acc xs     nty (NoteTy _ ty)   = split acc           xs nty ty
285     split acc xs     nty (SourceTy p)    = split acc           xs nty (sourceTypeRep p)
286     split acc (x:xs) nty ty              = pprPanic "zipFunTys" (ppr orig_xs <+> pprType orig_ty)
287     
288 funResultTy :: Type -> Type
289 funResultTy (FunTy arg res) = res
290 funResultTy (NoteTy _ ty)   = funResultTy ty
291 funResultTy (SourceTy p)    = funResultTy (sourceTypeRep p)
292 funResultTy ty              = pprPanic "funResultTy" (pprType ty)
293
294 funArgTy :: Type -> Type
295 funArgTy (FunTy arg res) = arg
296 funArgTy (NoteTy _ ty)   = funArgTy ty
297 funArgTy (SourceTy p)    = funArgTy (sourceTypeRep p)
298 funArgTy ty              = pprPanic "funArgTy" (pprType ty)
299 \end{code}
300
301
302 ---------------------------------------------------------------------
303                                 TyConApp
304                                 ~~~~~~~~
305 @mkTyConApp@ is a key function, because it builds a TyConApp, FunTy or SourceTy,
306 as apppropriate.
307
308 \begin{code}
309 mkGenTyConApp :: TyCon -> [Type] -> Type
310 mkGenTyConApp tc tys
311   | isSynTyCon tc = mkSynTy tc tys
312   | otherwise     = mkTyConApp tc tys
313
314 mkTyConApp :: TyCon -> [Type] -> Type
315 -- Assumes TyCon is not a SynTyCon; use mkSynTy instead for those
316 mkTyConApp tycon tys
317   | isFunTyCon tycon, [ty1,ty2] <- tys
318   = FunTy ty1 ty2
319
320   | isNewTyCon tycon,                   -- A saturated newtype application;
321     not (isRecursiveTyCon tycon),       -- Not recursive (we don't use SourceTypes for them)
322     tys `lengthIs` tyConArity tycon     -- use the SourceType form
323   = SourceTy (NType tycon tys)
324
325   | otherwise
326   = ASSERT(not (isSynTyCon tycon))
327     TyConApp tycon tys
328
329 mkTyConTy :: TyCon -> Type
330 mkTyConTy tycon = ASSERT( not (isSynTyCon tycon) ) 
331                   TyConApp tycon []
332
333 -- splitTyConApp "looks through" synonyms, because they don't
334 -- mean a distinct type, but all other type-constructor applications
335 -- including functions are returned as Just ..
336
337 tyConAppTyCon :: Type -> TyCon
338 tyConAppTyCon ty = fst (splitTyConApp ty)
339
340 tyConAppArgs :: Type -> [Type]
341 tyConAppArgs ty = snd (splitTyConApp ty)
342
343 splitTyConApp :: Type -> (TyCon, [Type])
344 splitTyConApp ty = case splitTyConApp_maybe ty of
345                         Just stuff -> stuff
346                         Nothing    -> pprPanic "splitTyConApp" (pprType ty)
347
348 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
349 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
350 splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
351 splitTyConApp_maybe (NoteTy _ ty)     = splitTyConApp_maybe ty
352 splitTyConApp_maybe (SourceTy p)      = splitTyConApp_maybe (sourceTypeRep p)
353 splitTyConApp_maybe other             = Nothing
354 \end{code}
355
356
357 ---------------------------------------------------------------------
358                                 SynTy
359                                 ~~~~~
360
361 \begin{code}
362 mkSynTy tycon tys
363   | n_args == arity     -- Exactly saturated
364   = mk_syn tys
365   | n_args >  arity     -- Over-saturated
366   = case splitAt arity tys of { (as,bs) -> mkAppTys (mk_syn as) bs }
367         -- Its important to use mkAppTys, rather than (foldl AppTy),
368         -- because (mk_syn as) might well return a partially-applied
369         -- type constructor; indeed, usually will!
370   | otherwise           -- Un-saturated
371   = TyConApp tycon tys
372         -- For the un-saturated case we build TyConApp directly
373         -- (mkTyConApp ASSERTs that the tc isn't a SynTyCon).
374         -- Here we are relying on checkValidType to find
375         -- the error.  What we can't do is use mkSynTy with
376         -- too few arg tys, because that is utterly bogus.
377
378   where
379     mk_syn tys = NoteTy (SynNote (TyConApp tycon tys))
380                         (substTyWith tyvars tys body)
381
382     (tyvars, body) = ASSERT( isSynTyCon tycon ) getSynTyConDefn tycon
383     arity          = tyConArity tycon
384     n_args         = length tys
385 \end{code}
386
387 Notes on type synonyms
388 ~~~~~~~~~~~~~~~~~~~~~~
389 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
390 to return type synonyms whereever possible. Thus
391
392         type Foo a = a -> a
393
394 we want 
395         splitFunTys (a -> Foo a) = ([a], Foo a)
396 not                                ([a], a -> a)
397
398 The reason is that we then get better (shorter) type signatures in 
399 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
400
401
402                 Representation types
403                 ~~~~~~~~~~~~~~~~~~~~
404 repType looks through 
405         (a) for-alls, and
406         (b) synonyms
407         (c) predicates
408         (d) usage annotations
409         (e) [recursive] newtypes
410 It's useful in the back end.
411
412 Remember, non-recursive newtypes get expanded as part of the SourceTy case,
413 but recursive ones are represented by TyConApps and have to be expanded
414 by steam.
415
416 \begin{code}
417 repType :: Type -> Type
418 repType (ForAllTy _ ty)   = repType ty
419 repType (NoteTy   _ ty)   = repType ty
420 repType (SourceTy  p)     = repType (sourceTypeRep p)
421 repType (TyConApp tc tys) | isNewTyCon tc && tys `lengthIs` tyConArity tc
422                           = repType (newTypeRep tc tys)
423 repType ty                = ty
424
425
426 typePrimRep :: Type -> PrimRep
427 typePrimRep ty = case repType ty of
428                    TyConApp tc _ -> tyConPrimRep tc
429                    FunTy _ _     -> PtrRep
430                    AppTy _ _     -> PtrRep      -- ??
431                    TyVarTy _     -> PtrRep
432 \end{code}
433
434
435
436 ---------------------------------------------------------------------
437                                 ForAllTy
438                                 ~~~~~~~~
439
440 \begin{code}
441 mkForAllTy :: TyVar -> Type -> Type
442 mkForAllTy tyvar ty
443   = mkForAllTys [tyvar] ty
444
445 mkForAllTys :: [TyVar] -> Type -> Type
446 mkForAllTys tyvars ty = foldr ForAllTy ty tyvars
447
448 isForAllTy :: Type -> Bool
449 isForAllTy (NoteTy _ ty)  = isForAllTy ty
450 isForAllTy (ForAllTy _ _) = True
451 isForAllTy other_ty       = False
452
453 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
454 splitForAllTy_maybe ty = splitFAT_m ty
455   where
456     splitFAT_m (NoteTy _ ty)            = splitFAT_m ty
457     splitFAT_m (SourceTy p)             = splitFAT_m (sourceTypeRep p)
458     splitFAT_m (ForAllTy tyvar ty)      = Just(tyvar, ty)
459     splitFAT_m _                        = Nothing
460
461 splitForAllTys :: Type -> ([TyVar], Type)
462 splitForAllTys ty = split ty ty []
463    where
464      split orig_ty (ForAllTy tv ty)       tvs = split ty ty (tv:tvs)
465      split orig_ty (NoteTy _ ty)          tvs = split orig_ty ty tvs
466      split orig_ty (SourceTy p)           tvs = split orig_ty (sourceTypeRep p) tvs
467      split orig_ty t                      tvs = (reverse tvs, orig_ty)
468
469 dropForAlls :: Type -> Type
470 dropForAlls ty = snd (splitForAllTys ty)
471 \end{code}
472
473 -- (mkPiType now in CoreUtils)
474
475 applyTy, applyTys
476 ~~~~~~~~~~~~~~~~~
477 Instantiate a for-all type with one or more type arguments.
478 Used when we have a polymorphic function applied to type args:
479         f t1 t2
480 Then we use (applyTys type-of-f [t1,t2]) to compute the type of
481 the expression. 
482
483 \begin{code}
484 applyTy :: Type -> Type -> Type
485 applyTy (SourceTy p)     arg = applyTy (sourceTypeRep p) arg
486 applyTy (NoteTy _ fun)   arg = applyTy fun arg
487 applyTy (ForAllTy tv ty) arg = substTyWith [tv] [arg] ty
488 applyTy other            arg = panic "applyTy"
489
490 applyTys :: Type -> [Type] -> Type
491 -- This function is interesting because 
492 --      a) the function may have more for-alls than there are args
493 --      b) less obviously, it may have fewer for-alls
494 -- For case (b) think of 
495 --      applyTys (forall a.a) [forall b.b, Int]
496 -- This really can happen, via dressing up polymorphic types with newtype
497 -- clothing.  Here's an example:
498 --      newtype R = R (forall a. a->a)
499 --      foo = case undefined :: R of
500 --              R f -> f ()
501
502 applyTys orig_fun_ty []      = orig_fun_ty
503 applyTys orig_fun_ty arg_tys 
504   | n_tvs == n_args     -- The vastly common case
505   = substTyWith tvs arg_tys rho_ty
506   | n_tvs > n_args      -- Too many for-alls
507   = substTyWith (take n_args tvs) arg_tys 
508                 (mkForAllTys (drop n_args tvs) rho_ty)
509   | otherwise           -- Too many type args
510   = ASSERT2( n_tvs > 0, pprType orig_fun_ty )   -- Zero case gives infnite loop!
511     applyTys (substTyWith tvs (take n_tvs arg_tys) rho_ty)
512              (drop n_tvs arg_tys)
513   where
514     (tvs, rho_ty) = splitForAllTys orig_fun_ty 
515     n_tvs = length tvs
516     n_args = length arg_tys     
517 \end{code}
518
519
520 %************************************************************************
521 %*                                                                      *
522 \subsection{Source types}
523 %*                                                                      *
524 %************************************************************************
525
526 A "source type" is a type that is a separate type as far as the type checker is
527 concerned, but which has low-level representation as far as the back end is concerned.
528
529 Source types are always lifted.
530
531 The key function is sourceTypeRep which gives the representation of a source type:
532
533 \begin{code}
534 mkPredTy :: PredType -> Type
535 mkPredTy pred = SourceTy pred
536
537 mkPredTys :: ThetaType -> [Type]
538 mkPredTys preds = map SourceTy preds
539
540 sourceTypeRep :: SourceType -> Type
541 -- Convert a predicate to its "representation type";
542 -- the type of evidence for that predicate, which is actually passed at runtime
543 sourceTypeRep (IParam _ ty)     = ty
544 sourceTypeRep (ClassP clas tys) = mkTyConApp (classTyCon clas) tys
545         -- Note the mkTyConApp; the classTyCon might be a newtype!
546 sourceTypeRep (NType  tc tys)   = newTypeRep tc tys
547         -- ToDo: Consider caching this substitution in a NType
548
549 isSourceTy :: Type -> Bool
550 isSourceTy (NoteTy _ ty)  = isSourceTy ty
551 isSourceTy (SourceTy sty) = True
552 isSourceTy _              = False
553
554
555 splitNewType_maybe :: Type -> Maybe Type
556 -- Newtypes that are recursive are reprsented by TyConApp, just
557 -- as they always were.  Occasionally we want to find their representation type.
558 -- NB: remember that in this module, non-recursive newtypes are transparent
559
560 splitNewType_maybe ty
561   = case splitTyConApp_maybe ty of
562         Just (tc,tys) | isNewTyCon tc -> ASSERT( tys `lengthIs` tyConArity tc )
563                                                 -- The assert should hold because repType should
564                                                 -- only be applied to *types* (of kind *)
565                                          Just (newTypeRep tc tys)
566         other -> Nothing
567                         
568 -- A local helper function (not exported)
569 newTypeRep new_tycon tys = case newTyConRep new_tycon of
570                              (tvs, rep_ty) -> substTyWith tvs tys rep_ty
571 \end{code}
572
573
574 %************************************************************************
575 %*                                                                      *
576 \subsection{Kinds and free variables}
577 %*                                                                      *
578 %************************************************************************
579
580 ---------------------------------------------------------------------
581                 Finding the kind of a type
582                 ~~~~~~~~~~~~~~~~~~~~~~~~~~
583 \begin{code}
584 typeKind :: Type -> Kind
585
586 typeKind (TyVarTy tyvar)        = tyVarKind tyvar
587 typeKind (TyConApp tycon tys)   = foldr (\_ k -> funResultTy k) (tyConKind tycon) tys
588 typeKind (NoteTy _ ty)          = typeKind ty
589 typeKind (SourceTy _)           = liftedTypeKind -- Predicates are always 
590                                                  -- represented by lifted types
591 typeKind (AppTy fun arg)        = funResultTy (typeKind fun)
592
593 typeKind (FunTy arg res)        = fix_up (typeKind res)
594                                 where
595                                   fix_up (TyConApp tycon _) |  tycon == typeCon
596                                                             || tycon == openKindCon = liftedTypeKind
597                                   fix_up (NoteTy _ kind) = fix_up kind
598                                   fix_up kind            = kind
599                 -- The basic story is 
600                 --      typeKind (FunTy arg res) = typeKind res
601                 -- But a function is lifted regardless of its result type
602                 -- Hence the strange fix-up.
603                 -- Note that 'res', being the result of a FunTy, can't have 
604                 -- a strange kind like (*->*).
605
606 typeKind (ForAllTy tv ty)       = typeKind ty
607 \end{code}
608
609
610 ---------------------------------------------------------------------
611                 Free variables of a type
612                 ~~~~~~~~~~~~~~~~~~~~~~~~
613 \begin{code}
614 tyVarsOfType :: Type -> TyVarSet
615 tyVarsOfType (TyVarTy tv)               = unitVarSet tv
616 tyVarsOfType (TyConApp tycon tys)       = tyVarsOfTypes tys
617 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
618 tyVarsOfType (NoteTy (SynNote ty1) ty2) = tyVarsOfType ty2      -- See note [Syn] below
619 tyVarsOfType (SourceTy sty)             = tyVarsOfSourceType sty
620 tyVarsOfType (FunTy arg res)            = tyVarsOfType arg `unionVarSet` tyVarsOfType res
621 tyVarsOfType (AppTy fun arg)            = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
622 tyVarsOfType (ForAllTy tyvar ty)        = tyVarsOfType ty `minusVarSet` unitVarSet tyvar
623
624 --                      Note [Syn]
625 -- Consider
626 --      type T a = Int
627 -- What are the free tyvars of (T x)?  Empty, of course!  
628 -- Here's the example that Ralf Laemmel showed me:
629 --      foo :: (forall a. C u a -> C u a) -> u
630 --      mappend :: Monoid u => u -> u -> u
631 --
632 --      bar :: Monoid u => u
633 --      bar = foo (\t -> t `mappend` t)
634 -- We have to generalise at the arg to f, and we don't
635 -- want to capture the constraint (Monad (C u a)) because
636 -- it appears to mention a.  Pretty silly, but it was useful to him.
637
638
639 tyVarsOfTypes :: [Type] -> TyVarSet
640 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
641
642 tyVarsOfPred :: PredType -> TyVarSet
643 tyVarsOfPred = tyVarsOfSourceType       -- Just a subtype
644
645 tyVarsOfSourceType :: SourceType -> TyVarSet
646 tyVarsOfSourceType (IParam _ ty)  = tyVarsOfType ty
647 tyVarsOfSourceType (ClassP _ tys) = tyVarsOfTypes tys
648 tyVarsOfSourceType (NType _ tys)  = tyVarsOfTypes tys
649
650 tyVarsOfTheta :: ThetaType -> TyVarSet
651 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfSourceType) emptyVarSet
652
653 -- Add a Note with the free tyvars to the top of the type
654 addFreeTyVars :: Type -> Type
655 addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
656 addFreeTyVars ty                             = NoteTy (FTVNote (tyVarsOfType ty)) ty
657 \end{code}
658
659 %************************************************************************
660 %*                                                                      *
661 \subsection{TidyType}
662 %*                                                                      *
663 %************************************************************************
664
665 tidyTy tidies up a type for printing in an error message, or in
666 an interface file.
667
668 It doesn't change the uniques at all, just the print names.
669
670 \begin{code}
671 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
672 tidyTyVarBndr (tidy_env, subst) tyvar
673   = case tidyOccName tidy_env (getOccName name) of
674       (tidy', occ') ->  -- New occname reqd
675                         ((tidy', subst'), tyvar')
676                     where
677                         subst' = extendVarEnv subst tyvar tyvar'
678                         tyvar' = setTyVarName tyvar name'
679                         name'  = mkInternalName (getUnique name) occ' noSrcLoc
680                                 -- Note: make a *user* tyvar, so it printes nicely
681                                 -- Could extract src loc, but no need.
682   where
683     name = tyVarName tyvar
684
685 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
686 -- Add the free tyvars to the env in tidy form,
687 -- so that we can tidy the type they are free in
688 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
689
690 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
691 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
692
693 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
694 -- Treat a new tyvar as a binder, and give it a fresh tidy name
695 tidyOpenTyVar env@(tidy_env, subst) tyvar
696   = case lookupVarEnv subst tyvar of
697         Just tyvar' -> (env, tyvar')            -- Already substituted
698         Nothing     -> tidyTyVarBndr env tyvar  -- Treat it as a binder
699
700 tidyType :: TidyEnv -> Type -> Type
701 tidyType env@(tidy_env, subst) ty
702   = go ty
703   where
704     go (TyVarTy tv)         = case lookupVarEnv subst tv of
705                                 Nothing  -> TyVarTy tv
706                                 Just tv' -> TyVarTy tv'
707     go (TyConApp tycon tys) = let args = map go tys
708                               in args `seqList` TyConApp tycon args
709     go (NoteTy note ty)     = (NoteTy $! (go_note note)) $! (go ty)
710     go (SourceTy sty)       = SourceTy (tidySourceType env sty)
711     go (AppTy fun arg)      = (AppTy $! (go fun)) $! (go arg)
712     go (FunTy fun arg)      = (FunTy $! (go fun)) $! (go arg)
713     go (ForAllTy tv ty)     = ForAllTy tvp $! (tidyType envp ty)
714                               where
715                                 (envp, tvp) = tidyTyVarBndr env tv
716
717     go_note (SynNote ty)        = SynNote $! (go ty)
718     go_note note@(FTVNote ftvs) = note  -- No need to tidy the free tyvars
719
720 tidyTypes env tys = map (tidyType env) tys
721
722 tidyPred :: TidyEnv -> SourceType -> SourceType
723 tidyPred = tidySourceType
724
725 tidySourceType :: TidyEnv -> SourceType -> SourceType
726 tidySourceType env (IParam n ty)     = IParam n (tidyType env ty)
727 tidySourceType env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
728 tidySourceType env (NType tc tys)    = NType  tc   (tidyTypes env tys)
729 \end{code}
730
731
732 @tidyOpenType@ grabs the free type variables, tidies them
733 and then uses @tidyType@ to work over the type itself
734
735 \begin{code}
736 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
737 tidyOpenType env ty
738   = (env', tidyType env' ty)
739   where
740     env' = tidyFreeTyVars env (tyVarsOfType ty)
741
742 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
743 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
744
745 tidyTopType :: Type -> Type
746 tidyTopType ty = tidyType emptyTidyEnv ty
747 \end{code}
748
749
750
751 %************************************************************************
752 %*                                                                      *
753 \subsection{Liftedness}
754 %*                                                                      *
755 %************************************************************************
756
757 \begin{code}
758 isUnLiftedType :: Type -> Bool
759         -- isUnLiftedType returns True for forall'd unlifted types:
760         --      x :: forall a. Int#
761         -- I found bindings like these were getting floated to the top level.
762         -- They are pretty bogus types, mind you.  It would be better never to
763         -- construct them
764
765 isUnLiftedType (ForAllTy tv ty) = isUnLiftedType ty
766 isUnLiftedType (NoteTy _ ty)    = isUnLiftedType ty
767 isUnLiftedType (TyConApp tc _)  = isUnLiftedTyCon tc
768 isUnLiftedType (SourceTy _)     = False         -- All source types are lifted
769 isUnLiftedType other            = False 
770
771 isUnboxedTupleType :: Type -> Bool
772 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
773                            Just (tc, ty_args) -> isUnboxedTupleTyCon tc
774                            other              -> False
775
776 -- Should only be applied to *types*; hence the assert
777 isAlgType :: Type -> Bool
778 isAlgType ty = case splitTyConApp_maybe ty of
779                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
780                                               isAlgTyCon tc
781                         other              -> False
782 \end{code}
783
784 @isStrictType@ computes whether an argument (or let RHS) should
785 be computed strictly or lazily, based only on its type.
786 Works just like isUnLiftedType, except that it has a special case 
787 for dictionaries.  Since it takes account of ClassP, you might think
788 this function should be in TcType, but isStrictType is used by DataCon,
789 which is below TcType in the hierarchy, so it's convenient to put it here.
790
791 \begin{code}
792 isStrictType (ForAllTy tv ty)           = isStrictType ty
793 isStrictType (NoteTy _ ty)              = isStrictType ty
794 isStrictType (TyConApp tc _)            = isUnLiftedTyCon tc
795 isStrictType (SourceTy (ClassP clas _)) = opt_DictsStrict && not (isNewTyCon (classTyCon clas))
796         -- We may be strict in dictionary types, but only if it 
797         -- has more than one component.
798         -- [Being strict in a single-component dictionary risks
799         --  poking the dictionary component, which is wrong.]
800 isStrictType other                      = False 
801 \end{code}
802
803 \begin{code}
804 isPrimitiveType :: Type -> Bool
805 -- Returns types that are opaque to Haskell.
806 -- Most of these are unlifted, but now that we interact with .NET, we
807 -- may have primtive (foreign-imported) types that are lifted
808 isPrimitiveType ty = case splitTyConApp_maybe ty of
809                         Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
810                                               isPrimTyCon tc
811                         other              -> False
812 \end{code}
813
814
815 %************************************************************************
816 %*                                                                      *
817 \subsection{Sequencing on types
818 %*                                                                      *
819 %************************************************************************
820
821 \begin{code}
822 seqType :: Type -> ()
823 seqType (TyVarTy tv)      = tv `seq` ()
824 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
825 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
826 seqType (NoteTy note t2)  = seqNote note `seq` seqType t2
827 seqType (SourceTy p)      = seqPred p
828 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
829 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
830
831 seqTypes :: [Type] -> ()
832 seqTypes []       = ()
833 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
834
835 seqNote :: TyNote -> ()
836 seqNote (SynNote ty)  = seqType ty
837 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
838
839 seqPred :: SourceType -> ()
840 seqPred (ClassP c tys) = c  `seq` seqTypes tys
841 seqPred (NType tc tys) = tc `seq` seqTypes tys
842 seqPred (IParam n ty)  = n  `seq` seqType ty
843 \end{code}
844
845
846 %************************************************************************
847 %*                                                                      *
848 \subsection{Equality on types}
849 %*                                                                      *
850 %************************************************************************
851
852 Comparison; don't use instances so that we know where it happens.
853 Look through newtypes but not usage types.
854
855 Note that eqType can respond 'False' for partial applications of newtypes.
856 Consider
857         newtype Parser m a = MkParser (Foogle m a)
858
859 Does    
860         Monad (Parser m) `eqType` Monad (Foogle m)
861
862 Well, yes, but eqType won't see that they are the same. 
863 I don't think this is harmful, but it's soemthing to watch out for.
864
865 \begin{code}
866 eqType t1 t2 = eq_ty emptyVarEnv t1 t2
867 eqKind  = eqType        -- No worries about looking 
868
869 -- Look through Notes
870 eq_ty env (NoteTy _ t1)       t2                  = eq_ty env t1 t2
871 eq_ty env t1                  (NoteTy _ t2)       = eq_ty env t1 t2
872
873 -- Look through SourceTy.  This is where the looping danger comes from
874 eq_ty env (SourceTy sty1)     t2                  = eq_ty env (sourceTypeRep sty1) t2
875 eq_ty env t1                  (SourceTy sty2)     = eq_ty env t1 (sourceTypeRep sty2)
876
877 -- The rest is plain sailing
878 eq_ty env (TyVarTy tv1)       (TyVarTy tv2)       = case lookupVarEnv env tv1 of
879                                                           Just tv1a -> tv1a == tv2
880                                                           Nothing   -> tv1  == tv2
881 eq_ty env (ForAllTy tv1 t1)   (ForAllTy tv2 t2)   
882         | tv1 == tv2                              = eq_ty (delVarEnv env tv1)        t1 t2
883         | otherwise                               = eq_ty (extendVarEnv env tv1 tv2) t1 t2
884 eq_ty env (AppTy s1 t1)       (AppTy s2 t2)       = (eq_ty env s1 s2) && (eq_ty env t1 t2)
885 eq_ty env (FunTy s1 t1)       (FunTy s2 t2)       = (eq_ty env s1 s2) && (eq_ty env t1 t2)
886 eq_ty env (TyConApp tc1 tys1) (TyConApp tc2 tys2) = (tc1 == tc2) && (eq_tys env tys1 tys2)
887 eq_ty env t1                   t2                 = False
888
889 eq_tys env []        []        = True
890 eq_tys env (t1:tys1) (t2:tys2) = (eq_ty env t1 t2) && (eq_tys env tys1 tys2)
891 eq_tys env tys1      tys2      = False
892 \end{code}
893