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