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