[project @ 2000-03-24 17:49:29 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,
10         Kind, TyVarSubst,
11
12         superKind, superBoxity,                         -- :: SuperKind
13
14         boxedKind,                                      -- :: Kind :: BX
15         anyBoxKind,                                     -- :: Kind :: BX
16         typeCon,                                        -- :: KindCon :: BX -> KX
17         anyBoxCon,                                      -- :: KindCon :: BX
18
19         boxedTypeKind, unboxedTypeKind, openTypeKind,   -- Kind :: superKind
20
21         mkArrowKind, mkArrowKinds, -- mentioned below: hasMoreBoxityInfo,
22
23         funTyCon,
24
25         -- exports from this module:
26         hasMoreBoxityInfo,
27
28         mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, isTyVarTy,
29
30         mkAppTy, mkAppTys, splitAppTy, splitAppTys, splitAppTy_maybe,
31
32         mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe, splitFunTys, splitFunTysN,
33         funResultTy, funArgTy, zipFunTys,
34
35         mkTyConApp, mkTyConTy, splitTyConApp_maybe,
36         splitAlgTyConApp_maybe, splitAlgTyConApp, 
37         mkDictTy, mkPredTy, splitPredTy_maybe, splitDictTy_maybe, isDictTy,
38
39         mkSynTy, isSynTy, deNoteType, 
40
41         repType, splitRepFunTys, splitNewType_maybe, typePrimRep,
42
43         UsageAnn(..), mkUsgTy, isUsgTy{- dont use -}, isNotUsgTy, splitUsgTy, unUsgTy, tyUsg,
44         mkUsForAllTy, mkUsForAllTys, splitUsForAllTys, substUsTy, 
45
46         mkForAllTy, mkForAllTys, splitForAllTy_maybe, splitForAllTys, 
47         isForAllTy, applyTy, applyTys, mkPiType, hoistForAllTys,
48
49         TauType, RhoType, SigmaType, PredType(..), ThetaType,
50         ClassPred, ClassContext, mkClassPred,
51         getClassTys_maybe, ipName_maybe, classesToPreds, classesOfPreds,
52         isTauTy, mkRhoTy, splitRhoTy,
53         mkSigmaTy, splitSigmaTy,
54
55         -- Lifting and boxity
56         isUnLiftedType, isUnboxedType, isUnboxedTupleType, isAlgType, isDataType, isNewType,
57
58         -- Free variables
59         tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
60         namesOfType, typeKind, addFreeTyVars,
61
62         -- Tidying up for printing
63         tidyType,     tidyTypes,
64         tidyOpenType, tidyOpenTypes,
65         tidyTyVar,    tidyTyVars,
66         tidyTopType,
67
68         -- Seq
69         seqType, seqTypes
70
71     ) where
72
73 #include "HsVersions.h"
74
75 -- We import the representation and primitive functions from TypeRep.
76 -- Many things are reexported, but not the representation!
77
78 import TypeRep
79
80 -- Other imports:
81
82 import {-# SOURCE #-}   DataCon( DataCon, dataConRepType )
83 import {-# SOURCE #-}   PprType( pprType, pprPred )     -- Only called in debug messages
84 import {-# SOURCE #-}   Subst  ( mkTyVarSubst, substTy )
85
86 -- friends:
87 import Var      ( TyVar, Var, UVar,
88                   tyVarKind, tyVarName, setTyVarName, isId, idType,
89                 )
90 import VarEnv
91 import VarSet
92
93 import Name     ( Name, NamedThing(..), mkLocalName, tidyOccName
94                 )
95 import NameSet
96 import Class    ( classTyCon, Class )
97 import TyCon    ( TyCon,
98                   isUnboxedTupleTyCon, isUnLiftedTyCon,
99                   isFunTyCon, isDataTyCon, isNewTyCon,
100                   isAlgTyCon, isSynTyCon, tyConArity,
101                   tyConKind, tyConDataCons, getSynTyConDefn,
102                   tyConPrimRep, tyConClass_maybe
103                 )
104
105 -- others
106 import SrcLoc           ( noSrcLoc )
107 import Maybes           ( maybeToBool )
108 import PrimRep          ( PrimRep(..), isFollowableRep )
109 import Unique           ( Uniquable(..) )
110 import Util             ( mapAccumL, seqList )
111 import Outputable
112 import UniqSet          ( sizeUniqSet )         -- Should come via VarSet
113 \end{code}
114
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection{Stuff to do with kinds.}
119 %*                                                                      *
120 %************************************************************************
121
122 \begin{code}
123 hasMoreBoxityInfo :: Kind -> Kind -> Bool
124 hasMoreBoxityInfo k1 k2
125   | k2 == openTypeKind = ASSERT( is_type_kind k1) True
126   | otherwise          = k1 == k2
127   where
128         -- Returns true for things of form (Type x)
129     is_type_kind k = case splitTyConApp_maybe k of
130                         Just (tc,[_]) -> tc == typeCon
131                         Nothing       -> False
132 \end{code}
133
134
135 %************************************************************************
136 %*                                                                      *
137 \subsection{Constructor-specific functions}
138 %*                                                                      *
139 %************************************************************************
140
141
142 ---------------------------------------------------------------------
143                                 TyVarTy
144                                 ~~~~~~~
145 \begin{code}
146 mkTyVarTy  :: TyVar   -> Type
147 mkTyVarTy  = TyVarTy
148
149 mkTyVarTys :: [TyVar] -> [Type]
150 mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
151
152 getTyVar :: String -> Type -> TyVar
153 getTyVar msg (TyVarTy tv) = tv
154 getTyVar msg (NoteTy _ t) = getTyVar msg t
155 getTyVar msg other        = panic ("getTyVar: " ++ msg)
156
157 getTyVar_maybe :: Type -> Maybe TyVar
158 getTyVar_maybe (TyVarTy tv) = Just tv
159 getTyVar_maybe (NoteTy _ t) = getTyVar_maybe t
160 getTyVar_maybe other        = Nothing
161
162 isTyVarTy :: Type -> Bool
163 isTyVarTy (TyVarTy tv)  = True
164 isTyVarTy (NoteTy _ ty) = isTyVarTy ty
165 isTyVarTy other         = False
166 \end{code}
167
168
169 ---------------------------------------------------------------------
170                                 AppTy
171                                 ~~~~~
172 We need to be pretty careful with AppTy to make sure we obey the 
173 invariant that a TyConApp is always visibly so.  mkAppTy maintains the
174 invariant: use it.
175
176 \begin{code}
177 mkAppTy orig_ty1 orig_ty2 = ASSERT2( isNotUsgTy orig_ty1 && isNotUsgTy orig_ty2, pprType orig_ty1 <+> text "to" <+> pprType orig_ty2 )
178                             mk_app orig_ty1
179   where
180     mk_app (NoteTy _ ty1)    = mk_app ty1
181     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ [orig_ty2])
182     mk_app ty1               = AppTy orig_ty1 orig_ty2
183
184 mkAppTys :: Type -> [Type] -> Type
185 mkAppTys orig_ty1 []        = orig_ty1
186         -- This check for an empty list of type arguments
187         -- avoids the needless of a type synonym constructor.
188         -- For example: mkAppTys Rational []
189         --   returns to (Ratio Integer), which has needlessly lost
190         --   the Rational part.
191 mkAppTys orig_ty1 orig_tys2 = ASSERT2( isNotUsgTy orig_ty1, pprType orig_ty1 )
192                               mk_app orig_ty1
193   where
194     mk_app (NoteTy _ ty1)    = mk_app ty1
195     mk_app (TyConApp tc tys) = mkTyConApp tc (tys ++ orig_tys2)
196     mk_app ty1               = ASSERT2( all isNotUsgTy orig_tys2, pprType orig_ty1 <+> text "to" <+> hsep (map pprType orig_tys2) )
197                                foldl AppTy orig_ty1 orig_tys2
198
199 splitAppTy_maybe :: Type -> Maybe (Type, Type)
200 splitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
201 splitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
202 splitAppTy_maybe (NoteTy _ ty)     = splitAppTy_maybe ty
203 splitAppTy_maybe (TyConApp tc [])  = Nothing
204 splitAppTy_maybe (TyConApp tc tys) = split tys []
205                             where
206                                split [ty2]    acc = Just (TyConApp tc (reverse acc), ty2)
207                                split (ty:tys) acc = split tys (ty:acc)
208
209 splitAppTy_maybe other            = Nothing
210
211 splitAppTy :: Type -> (Type, Type)
212 splitAppTy ty = case splitAppTy_maybe ty of
213                         Just pr -> pr
214                         Nothing -> panic "splitAppTy"
215
216 splitAppTys :: Type -> (Type, [Type])
217 splitAppTys ty = split ty ty []
218   where
219     split orig_ty (AppTy ty arg)        args = split ty ty (arg:args)
220     split orig_ty (NoteTy _ ty)         args = split orig_ty ty args
221     split orig_ty (FunTy ty1 ty2)       args = ASSERT( null args )
222                                                (TyConApp funTyCon [], [ty1,ty2])
223     split orig_ty (TyConApp tc tc_args) args = (TyConApp tc [], tc_args ++ args)
224     split orig_ty ty                    args = (orig_ty, args)
225 \end{code}
226
227
228 ---------------------------------------------------------------------
229                                 FunTy
230                                 ~~~~~
231
232 \begin{code}
233 mkFunTy :: Type -> Type -> Type
234 mkFunTy arg res = FunTy arg res
235
236 mkFunTys :: [Type] -> Type -> Type
237 mkFunTys tys ty = foldr FunTy ty tys
238
239 splitFunTy :: Type -> (Type, Type)
240 splitFunTy (FunTy arg res) = (arg, res)
241 splitFunTy (NoteTy _ ty)   = splitFunTy ty
242
243 splitFunTy_maybe :: Type -> Maybe (Type, Type)
244 splitFunTy_maybe (FunTy arg res) = Just (arg, res)
245 splitFunTy_maybe (NoteTy _ ty)   = splitFunTy_maybe ty
246 splitFunTy_maybe other           = Nothing
247
248 splitFunTys :: Type -> ([Type], Type)
249 splitFunTys ty = split [] ty ty
250   where
251     split args orig_ty (FunTy arg res) = split (arg:args) res res
252     split args orig_ty (NoteTy _ ty)   = split args orig_ty ty
253     split args orig_ty ty              = (reverse args, orig_ty)
254
255 splitFunTysN :: String -> Int -> Type -> ([Type], Type)
256 splitFunTysN msg orig_n orig_ty = split orig_n [] orig_ty orig_ty
257   where
258     split 0 args syn_ty ty              = (reverse args, syn_ty) 
259     split n args syn_ty (FunTy arg res) = split (n-1) (arg:args) res    res
260     split n args syn_ty (NoteTy _ ty)   = split n     args       syn_ty ty
261     split n args syn_ty ty              = pprPanic ("splitFunTysN: " ++ msg) (int orig_n <+> pprType orig_ty)
262
263 zipFunTys :: Outputable a => [a] -> Type -> ([(a,Type)], Type)
264 zipFunTys orig_xs orig_ty = split [] orig_xs orig_ty orig_ty
265   where
266     split acc []     nty ty              = (reverse acc, nty)
267     split acc (x:xs) nty (FunTy arg res) = split ((x,arg):acc) xs res res
268     split acc xs     nty (NoteTy _ ty)   = split acc           xs nty ty
269     split acc (x:xs) nty ty              = pprPanic "zipFunTys" (ppr orig_xs <+> pprType orig_ty)
270     
271 funResultTy :: Type -> Type
272 funResultTy (FunTy arg res) = res
273 funResultTy (NoteTy _ ty)   = funResultTy ty
274 funResultTy ty              = pprPanic "funResultTy" (pprType ty)
275
276 funArgTy :: Type -> Type
277 funArgTy (FunTy arg res) = arg
278 funArgTy (NoteTy _ ty)   = funArgTy ty
279 funArgTy ty              = pprPanic "funArgTy" (pprType ty)
280 \end{code}
281
282
283 ---------------------------------------------------------------------
284                                 TyConApp
285                                 ~~~~~~~~
286
287 \begin{code}
288 mkTyConApp :: TyCon -> [Type] -> Type
289 mkTyConApp tycon tys
290   | isFunTyCon tycon && length tys == 2
291   = case tys of 
292         (ty1:ty2:_) -> FunTy ty1 ty2
293
294   | otherwise
295   = ASSERT(not (isSynTyCon tycon))
296     TyConApp tycon tys
297
298 mkTyConTy :: TyCon -> Type
299 mkTyConTy tycon = ASSERT( not (isSynTyCon tycon) ) 
300                   TyConApp tycon []
301
302 -- splitTyConApp "looks through" synonyms, because they don't
303 -- mean a distinct type, but all other type-constructor applications
304 -- including functions are returned as Just ..
305
306 splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
307 splitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
308 splitTyConApp_maybe (FunTy arg res)   = Just (funTyCon, [arg,res])
309 splitTyConApp_maybe (NoteTy _ ty)     = splitTyConApp_maybe ty
310 splitTyConApp_maybe other             = Nothing
311
312 -- splitAlgTyConApp_maybe looks for 
313 --      *saturated* applications of *algebraic* data types
314 -- "Algebraic" => newtype, data type, or dictionary (not function types)
315 -- We return the constructors too.
316
317 splitAlgTyConApp_maybe :: Type -> Maybe (TyCon, [Type], [DataCon])
318 splitAlgTyConApp_maybe (TyConApp tc tys) 
319   | isAlgTyCon tc &&
320     tyConArity tc == length tys      = Just (tc, tys, tyConDataCons tc)
321 splitAlgTyConApp_maybe (NoteTy _ ty) = splitAlgTyConApp_maybe ty
322 splitAlgTyConApp_maybe other         = Nothing
323
324 splitAlgTyConApp :: Type -> (TyCon, [Type], [DataCon])
325         -- Here the "algebraic" property is an *assertion*
326 splitAlgTyConApp (TyConApp tc tys) = ASSERT( isAlgTyCon tc && tyConArity tc == length tys )
327                                      (tc, tys, tyConDataCons tc)
328 splitAlgTyConApp (NoteTy _ ty)     = splitAlgTyConApp ty
329 \end{code}
330
331 "Dictionary" types are just ordinary data types, but you can
332 tell from the type constructor whether it's a dictionary or not.
333
334 \begin{code}
335 mkDictTy :: Class -> [Type] -> Type
336 mkDictTy clas tys = TyConApp (classTyCon clas) tys
337
338 mkPredTy :: PredType -> Type
339 mkPredTy (Class clas tys) = TyConApp (classTyCon clas) tys
340 mkPredTy (IParam n ty)    = NoteTy (IPNote n) ty
341
342 {-
343 splitDictTy_maybe :: Type -> Maybe (Class, [Type])
344 splitDictTy_maybe (TyConApp tc tys) 
345   |  maybeToBool maybe_class
346   && tyConArity tc == length tys = Just (clas, tys)
347   where
348      maybe_class = tyConClass_maybe tc
349      Just clas   = maybe_class
350
351 splitDictTy_maybe (NoteTy _ ty) = splitDictTy_maybe ty
352 splitDictTy_maybe other         = Nothing
353 -}
354
355 splitPredTy_maybe :: Type -> Maybe PredType
356 splitPredTy_maybe (TyConApp tc tys) 
357   |  maybeToBool maybe_class
358   && tyConArity tc == length tys = Just (Class clas tys)
359   where
360      maybe_class = tyConClass_maybe tc
361      Just clas   = maybe_class
362
363 splitPredTy_maybe (NoteTy (IPNote n) ty)
364                                 = Just (IParam n ty)
365 splitPredTy_maybe (NoteTy _ ty) = splitPredTy_maybe ty
366 splitPredTy_maybe other         = Nothing
367
368 splitDictTy_maybe :: Type -> Maybe (Class, [Type])
369 splitDictTy_maybe ty
370   = case splitPredTy_maybe ty of
371     Just p -> getClassTys_maybe p
372     Nothing -> Nothing
373
374 isDictTy :: Type -> Bool
375         -- This version is slightly more efficient than (maybeToBool . splitDictTy)
376 isDictTy (TyConApp tc tys) 
377   |  maybeToBool (tyConClass_maybe tc)
378   && tyConArity tc == length tys
379   = True
380 isDictTy (NoteTy _ ty)  = isDictTy ty
381 isDictTy other          = False
382 \end{code}
383
384 ---------------------------------------------------------------------
385                                 SynTy
386                                 ~~~~~
387
388 \begin{code}
389 mkSynTy syn_tycon tys
390   = ASSERT( isSynTyCon syn_tycon )
391     ASSERT( isNotUsgTy body )
392     ASSERT( length tyvars == length tys )
393     NoteTy (SynNote (TyConApp syn_tycon tys))
394            (substTy (mkTyVarSubst tyvars tys) body)
395   where
396     (tyvars, body) = getSynTyConDefn syn_tycon
397
398 isSynTy (NoteTy (SynNote _) _) = True
399 isSynTy other                  = False
400
401 deNoteType :: Type -> Type
402         -- Sorry for the cute name
403 deNoteType ty@(TyVarTy tyvar)   = ty
404 deNoteType (TyConApp tycon tys) = TyConApp tycon (map deNoteType tys)
405 deNoteType (NoteTy _ ty)        = deNoteType ty
406 deNoteType (AppTy fun arg)      = AppTy (deNoteType fun) (deNoteType arg)
407 deNoteType (FunTy fun arg)      = FunTy (deNoteType fun) (deNoteType arg)
408 deNoteType (ForAllTy tv ty)     = ForAllTy tv (deNoteType ty)
409 \end{code}
410
411 Notes on type synonyms
412 ~~~~~~~~~~~~~~~~~~~~~~
413 The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
414 to return type synonyms whereever possible. Thus
415
416         type Foo a = a -> a
417
418 we want 
419         splitFunTys (a -> Foo a) = ([a], Foo a)
420 not                                ([a], a -> a)
421
422 The reason is that we then get better (shorter) type signatures in 
423 interfaces.  Notably this plays a role in tcTySigs in TcBinds.lhs.
424
425
426                 Representation types
427                 ~~~~~~~~~~~~~~~~~~~~
428
429 repType looks through 
430         (a) for-alls, and
431         (b) newtypes
432 in addition to synonyms.  It's useful in the back end where we're not
433 interested in newtypes anymore.
434
435 \begin{code}
436 repType :: Type -> Type
437 repType (NoteTy _ ty)                     = repType ty
438 repType (ForAllTy _ ty)                   = repType ty
439 repType (TyConApp tc tys) | isNewTyCon tc = repType (new_type_rep tc tys)
440 repType other_ty                          = other_ty
441
442
443 typePrimRep :: Type -> PrimRep
444 typePrimRep ty = case splitTyConApp_maybe (repType ty) of
445                    Just (tc, ty_args) -> tyConPrimRep tc
446                    other              -> PtrRep
447
448 splitNewType_maybe :: Type -> Maybe Type
449 -- Find the representation of a newtype, if it is one
450 -- Looks through multiple levels of newtype
451 splitNewType_maybe (NoteTy _ ty)                     = splitNewType_maybe ty
452 splitNewType_maybe (TyConApp tc tys) | isNewTyCon tc = case splitNewType_maybe rep_ty of
453                                                                 Just rep_ty' -> Just rep_ty'
454                                                                 Nothing      -> Just rep_ty
455                                                      where
456                                                        rep_ty = new_type_rep tc tys
457
458 splitNewType_maybe other                             = Nothing                                          
459
460 new_type_rep :: TyCon -> [Type] -> Type
461 -- The representation type for (T t1 .. tn), where T is a newtype 
462 -- Looks through one layer only
463 new_type_rep tc tys 
464   = ASSERT( isNewTyCon tc )
465     case splitFunTy_maybe (applyTys (dataConRepType (head (tyConDataCons tc))) tys) of
466         Just (rep_ty, _) -> rep_ty
467
468 splitRepFunTys :: Type -> ([Type], Type)
469 -- Like splitFunTys, but looks through newtypes and for-alls
470 splitRepFunTys ty = split [] (repType ty)
471   where
472     split args (FunTy arg res)  = split (arg:args) (repType res)
473     split args ty               = (reverse args, ty)
474 \end{code}
475
476
477
478 ---------------------------------------------------------------------
479                                 UsgNote
480                                 ~~~~~~~
481
482 NB: Invariant: if present, usage note is at the very top of the type.
483 This should be carefully preserved.
484
485 In some parts of the compiler, comments use the _Once Upon a
486 Polymorphic Type_ (POPL'99) usage of "rho = generalised
487 usage-annotated type; sigma = usage-annotated type; tau =
488 usage-annotated type except on top"; unfortunately this conflicts with
489 the rho/tau/theta/sigma usage in the rest of the compiler.  (KSW
490 1999-07)
491
492 \begin{code}
493 mkUsgTy :: UsageAnn -> Type -> Type
494 #ifndef USMANY
495 mkUsgTy UsMany ty = ASSERT2( isNotUsgTy ty, pprType ty )
496                     ty
497 #endif
498 mkUsgTy usg    ty = ASSERT2( isNotUsgTy ty, pprType ty )
499                     NoteTy (UsgNote usg) ty
500
501 -- The isUsgTy function is utterly useless if UsManys are omitted.
502 -- Be warned!  KSW 1999-04.
503 isUsgTy :: Type -> Bool
504 #ifndef USMANY
505 isUsgTy _ = True
506 #else
507 isUsgTy (NoteTy (UsgForAll _) ty) = isUsgTy ty
508 isUsgTy (NoteTy (UsgNote   _) _ ) = True
509 isUsgTy other                     = False
510 #endif
511
512 -- The isNotUsgTy function may return a false True if UsManys are omitted;
513 -- in other words, A SSERT( isNotUsgTy ty ) may be useful but
514 -- A SSERT( not (isNotUsg ty) ) is asking for trouble.  KSW 1999-04.
515 isNotUsgTy :: Type -> Bool
516 isNotUsgTy (NoteTy (UsgForAll _) _) = False
517 isNotUsgTy (NoteTy (UsgNote   _) _) = False
518 isNotUsgTy other                    = True
519
520 -- splitUsgTy_maybe is not exported, since it is meaningless if
521 -- UsManys are omitted.  It is used in several places in this module,
522 -- however.  KSW 1999-04.
523 splitUsgTy_maybe :: Type -> Maybe (UsageAnn,Type)
524 splitUsgTy_maybe (NoteTy (UsgNote usg) ty2) = ASSERT( isNotUsgTy ty2 )
525                                               Just (usg,ty2)
526 splitUsgTy_maybe ty@(NoteTy (UsgForAll _) _) = pprPanic "splitUsgTy_maybe:" $ pprType ty
527 splitUsgTy_maybe ty                          = Nothing
528
529 splitUsgTy :: Type -> (UsageAnn,Type)
530 splitUsgTy ty = case splitUsgTy_maybe ty of
531                   Just ans -> ans
532                   Nothing  -> 
533 #ifndef USMANY
534                               (UsMany,ty)
535 #else
536                               pprPanic "splitUsgTy: no usage annot:" $ pprType ty
537 #endif
538
539 tyUsg :: Type -> UsageAnn
540 tyUsg = fst . splitUsgTy
541
542 unUsgTy :: Type -> Type
543 -- strip outer usage annotation if present
544 unUsgTy ty = case splitUsgTy_maybe ty of
545                Just (_,ty1) -> ASSERT2( isNotUsgTy ty1, pprType ty )
546                                ty1
547                Nothing      -> ty
548
549 mkUsForAllTy :: UVar -> Type -> Type
550 mkUsForAllTy uv ty = NoteTy (UsgForAll uv) ty
551
552 mkUsForAllTys :: [UVar] -> Type -> Type
553 mkUsForAllTys uvs ty = foldr (NoteTy . UsgForAll) ty uvs
554
555 splitUsForAllTys :: Type -> ([UVar],Type)
556 splitUsForAllTys ty = split ty []
557   where split (NoteTy (UsgForAll u) ty) uvs = split ty (u:uvs)
558         split other_ty                  uvs = (reverse uvs, other_ty)
559
560 substUsTy :: VarEnv UsageAnn -> Type -> Type
561 -- assumes range is fresh uvars, so no conflicts
562 substUsTy ve    (NoteTy  note@(UsgNote (UsVar u))
563                                             ty ) = NoteTy (case lookupVarEnv ve u of
564                                                              Just ua -> UsgNote ua
565                                                              Nothing -> note)
566                                                           (substUsTy ve ty)
567 substUsTy ve    (NoteTy  note@(UsgNote   _) ty ) = NoteTy note (substUsTy ve ty)
568 substUsTy ve    (NoteTy  note@(UsgForAll _) ty ) = NoteTy note (substUsTy ve ty)
569 substUsTy ve    (NoteTy  (SynNote ty1)      ty2) = NoteTy (SynNote (substUsTy ve ty1))
570                                                           (substUsTy ve ty2)
571 substUsTy ve    (NoteTy  note@(FTVNote _)   ty ) = NoteTy note (substUsTy ve ty)
572 substUsTy ve ty@(TyVarTy _                     ) = ty
573 substUsTy ve    (AppTy   ty1                ty2) = AppTy (substUsTy ve ty1)
574                                                          (substUsTy ve ty2)
575 substUsTy ve    (FunTy   ty1                ty2) = FunTy (substUsTy ve ty1)
576                                                          (substUsTy ve ty2)
577 substUsTy ve    (TyConApp tyc               tys) = TyConApp tyc (map (substUsTy ve) tys)
578 substUsTy ve    (ForAllTy yv                ty ) = ForAllTy yv (substUsTy ve ty)
579 \end{code}
580
581
582 ---------------------------------------------------------------------
583                                 ForAllTy
584                                 ~~~~~~~~
585
586 We need to be clever here with usage annotations; they need to be
587 lifted or lowered through the forall as appropriate.
588
589 \begin{code}
590 mkForAllTy :: TyVar -> Type -> Type
591 mkForAllTy tyvar ty = case splitUsgTy_maybe ty of
592                         Just (usg,ty') -> NoteTy (UsgNote usg)
593                                                  (ForAllTy tyvar ty')
594                         Nothing        -> ForAllTy tyvar ty
595
596 mkForAllTys :: [TyVar] -> Type -> Type
597 mkForAllTys tyvars ty = case splitUsgTy_maybe ty of
598                           Just (usg,ty') -> NoteTy (UsgNote usg)
599                                                    (foldr ForAllTy ty' tyvars)
600                           Nothing        -> foldr ForAllTy ty tyvars
601
602 splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
603 splitForAllTy_maybe ty = case splitUsgTy_maybe ty of
604                            Just (usg,ty') -> do (tyvar,ty'') <- splitFAT_m ty'
605                                                 return (tyvar, NoteTy (UsgNote usg) ty'')
606                            Nothing        -> splitFAT_m ty
607   where
608     splitFAT_m (NoteTy _ ty)       = splitFAT_m ty
609     splitFAT_m (ForAllTy tyvar ty) = Just(tyvar, ty)
610     splitFAT_m _                   = Nothing
611
612 isForAllTy :: Type -> Bool
613 isForAllTy (NoteTy _ ty)       = isForAllTy ty
614 isForAllTy (ForAllTy tyvar ty) = True
615 isForAllTy _                 = False
616
617 splitForAllTys :: Type -> ([TyVar], Type)
618 splitForAllTys ty = case splitUsgTy_maybe ty of
619                       Just (usg,ty') -> let (tvs,ty'') = split ty' ty' []
620                                         in  (tvs, NoteTy (UsgNote usg) ty'')
621                       Nothing        -> split ty ty []
622    where
623      split orig_ty (ForAllTy tv ty) tvs = split ty ty (tv:tvs)
624      split orig_ty (NoteTy _ ty)    tvs = split orig_ty ty tvs
625      split orig_ty t                tvs = (reverse tvs, orig_ty)
626 \end{code}
627
628 @mkPiType@ makes a (->) type or a forall type, depending on whether
629 it is given a type variable or a term variable.
630
631 \begin{code}
632 mkPiType :: Var -> Type -> Type         -- The more polymorphic version doesn't work...
633 mkPiType v ty | isId v    = mkFunTy (idType v) ty
634               | otherwise = mkForAllTy v ty
635 \end{code}
636
637 Applying a for-all to its arguments
638
639 \begin{code}
640 applyTy :: Type -> Type -> Type
641 applyTy (NoteTy note@(UsgNote   _) fun) arg = NoteTy note (applyTy fun arg)
642 applyTy (NoteTy note@(UsgForAll _) fun) arg = NoteTy note (applyTy fun arg)
643 applyTy (NoteTy _ fun)                  arg = applyTy fun arg
644 applyTy (ForAllTy tv ty)                arg = ASSERT( isNotUsgTy arg )
645                                               substTy (mkTyVarSubst [tv] [arg]) ty
646 applyTy other                           arg = panic "applyTy"
647
648 applyTys :: Type -> [Type] -> Type
649 applyTys fun_ty arg_tys
650  = substTy (mkTyVarSubst tvs arg_tys) ty
651  where
652    (tvs, ty) = split fun_ty arg_tys
653    
654    split fun_ty               []         = ([], fun_ty)
655    split (NoteTy note@(UsgNote   _) fun_ty)
656                               args       = case split fun_ty args of
657                                              (tvs, ty) -> (tvs, NoteTy note ty)
658    split (NoteTy note@(UsgForAll _) fun_ty)
659                               args       = case split fun_ty args of
660                                              (tvs, ty) -> (tvs, NoteTy note ty)
661    split (NoteTy _ fun_ty)    args       = split fun_ty args
662    split (ForAllTy tv fun_ty) (arg:args) = ASSERT2( isNotUsgTy arg, vcat (map pprType arg_tys) $$
663                                                                     text "in application of" <+> pprType fun_ty)
664                                            case split fun_ty args of
665                                                   (tvs, ty) -> (tv:tvs, ty)
666    split other_ty             args       = panic "applyTys"
667 \end{code}
668
669 Note that we allow applications to be of usage-annotated- types, as an
670 extension: we handle them by lifting the annotation outside.  The
671 argument, however, must still be unannotated.
672
673 \begin{code}
674 hoistForAllTys :: Type -> Type
675         -- Move all the foralls to the top
676         -- e.g.  T -> forall a. a  ==>   forall a. T -> a
677 hoistForAllTys ty
678   = case hoist ty of { (tvs, body) -> mkForAllTys tvs body }
679   where
680     hoist :: Type -> ([TyVar], Type)
681     hoist ty = case splitFunTys    ty  of { (args, res) -> 
682                case splitForAllTys res of {
683                   ([], body)  -> ([], ty) ;
684                   (tvs1, body1) -> case hoist body1 of { (tvs2,body2) ->
685                                    (tvs1 ++ tvs2, mkFunTys args body2)
686                }}}
687 \end{code}
688
689
690 %************************************************************************
691 %*                                                                      *
692 \subsection{Stuff to do with the source-language types}
693
694 PredType and ThetaType are used in types for expressions and bindings.
695 ClassPred and ClassContext are used in class and instance declarations.
696 %*                                                                      *
697 %************************************************************************
698
699 \begin{code}
700 type RhoType   = Type
701 type TauType   = Type
702 data PredType  = Class  Class [Type]
703                | IParam Name  Type
704 type ThetaType = [PredType]
705 type ClassPred = (Class, [Type])
706 type ClassContext = [ClassPred]
707 type SigmaType = Type
708 \end{code}
709
710 \begin{code}
711 instance Outputable PredType where
712     ppr = pprPred
713 \end{code}
714
715 \begin{code}
716 mkClassPred clas tys = Class clas tys
717
718 getClassTys_maybe :: PredType -> Maybe ClassPred
719 getClassTys_maybe (Class clas tys) = Just (clas, tys)
720 getClassTys_maybe _                 = Nothing
721
722 ipName_maybe :: PredType -> Maybe Name
723 ipName_maybe (IParam n _) = Just n
724 ipName_maybe _            = Nothing
725
726 classesToPreds cts = map (uncurry Class) cts
727
728 classesOfPreds theta = concatMap cvt theta
729     where cvt (Class clas tys) = [(clas, tys)]
730           cvt (IParam _   _  ) = []
731 \end{code}
732
733 @isTauTy@ tests for nested for-alls.
734
735 \begin{code}
736 isTauTy :: Type -> Bool
737 isTauTy (TyVarTy v)      = True
738 isTauTy (TyConApp _ tys) = all isTauTy tys
739 isTauTy (AppTy a b)      = isTauTy a && isTauTy b
740 isTauTy (FunTy a b)      = isTauTy a && isTauTy b
741 isTauTy (NoteTy _ ty)    = isTauTy ty
742 isTauTy other            = False
743 \end{code}
744
745 \begin{code}
746 mkRhoTy :: [PredType] -> Type -> Type
747 mkRhoTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
748
749 splitRhoTy :: Type -> ([PredType], Type)
750 splitRhoTy ty = split ty ty []
751  where
752   split orig_ty (FunTy arg res) ts = case splitPredTy_maybe arg of
753                                         Just p -> split res res (p:ts)
754                                         Nothing   -> (reverse ts, orig_ty)
755   split orig_ty (NoteTy _ ty) ts   = split orig_ty ty ts
756   split orig_ty ty ts              = (reverse ts, orig_ty)
757 \end{code}
758
759
760
761 \begin{code}
762 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkRhoTy theta tau)
763
764 splitSigmaTy :: Type -> ([TyVar], [PredType], Type)
765 splitSigmaTy ty =
766   (tyvars, theta, tau)
767  where
768   (tyvars,rho) = splitForAllTys ty
769   (theta,tau)  = splitRhoTy rho
770 \end{code}
771
772
773 %************************************************************************
774 %*                                                                      *
775 \subsection{Kinds and free variables}
776 %*                                                                      *
777 %************************************************************************
778
779 ---------------------------------------------------------------------
780                 Finding the kind of a type
781                 ~~~~~~~~~~~~~~~~~~~~~~~~~~
782 \begin{code}
783 typeKind :: Type -> Kind
784
785 typeKind (TyVarTy tyvar)        = tyVarKind tyvar
786 typeKind (TyConApp tycon tys)   = foldr (\_ k -> funResultTy k) (tyConKind tycon) tys
787 typeKind (NoteTy _ ty)          = typeKind ty
788 typeKind (AppTy fun arg)        = funResultTy (typeKind fun)
789
790 typeKind (FunTy arg res)        = boxedTypeKind -- A function is boxed regardless of its result type
791                                                 -- No functions at the type level, hence we don't need
792                                                 -- to say (typeKind res).
793
794 typeKind (ForAllTy tv ty)       = typeKind ty
795 \end{code}
796
797
798 ---------------------------------------------------------------------
799                 Free variables of a type
800                 ~~~~~~~~~~~~~~~~~~~~~~~~
801 \begin{code}
802 tyVarsOfType :: Type -> TyVarSet
803
804 tyVarsOfType (TyVarTy tv)               = unitVarSet tv
805 tyVarsOfType (TyConApp tycon tys)       = tyVarsOfTypes tys
806 tyVarsOfType (NoteTy (FTVNote tvs) ty2) = tvs
807 tyVarsOfType (NoteTy (SynNote ty1) ty2) = tyVarsOfType ty1
808 tyVarsOfType (NoteTy (UsgNote _) ty)    = tyVarsOfType ty
809 tyVarsOfType (NoteTy (UsgForAll _) ty)  = tyVarsOfType ty
810 tyVarsOfType (NoteTy (IPNote _) ty)     = tyVarsOfType ty
811 tyVarsOfType (FunTy arg res)            = tyVarsOfType arg `unionVarSet` tyVarsOfType res
812 tyVarsOfType (AppTy fun arg)            = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
813 tyVarsOfType (ForAllTy tyvar ty)        = tyVarsOfType ty `minusVarSet` unitVarSet tyvar
814
815 tyVarsOfTypes :: [Type] -> TyVarSet
816 tyVarsOfTypes tys = foldr (unionVarSet.tyVarsOfType) emptyVarSet tys
817
818 tyVarsOfPred :: PredType -> TyVarSet
819 tyVarsOfPred (Class clas tys) = tyVarsOfTypes tys
820 tyVarsOfPred (IParam n ty)    = tyVarsOfType ty
821
822 tyVarsOfTheta :: ThetaType -> TyVarSet
823 tyVarsOfTheta = foldr (unionVarSet . tyVarsOfPred) emptyVarSet
824
825 -- Add a Note with the free tyvars to the top of the type
826 -- (but under a usage if there is one)
827 addFreeTyVars :: Type -> Type
828 addFreeTyVars (NoteTy note@(UsgNote   _) ty) = NoteTy note (addFreeTyVars ty)
829 addFreeTyVars (NoteTy note@(UsgForAll _) ty) = NoteTy note (addFreeTyVars ty)
830 addFreeTyVars ty@(NoteTy (FTVNote _) _)      = ty
831 addFreeTyVars ty                             = NoteTy (FTVNote (tyVarsOfType ty)) ty
832
833 -- Find the free names of a type, including the type constructors and classes it mentions
834 namesOfType :: Type -> NameSet
835 namesOfType (TyVarTy tv)                = unitNameSet (getName tv)
836 namesOfType (TyConApp tycon tys)        = unitNameSet (getName tycon) `unionNameSets`
837                                           namesOfTypes tys
838 namesOfType (NoteTy (SynNote ty1) ty2)  = namesOfType ty1
839 namesOfType (NoteTy other_note    ty2)  = namesOfType ty2
840 namesOfType (FunTy arg res)             = namesOfType arg `unionNameSets` namesOfType res
841 namesOfType (AppTy fun arg)             = namesOfType fun `unionNameSets` namesOfType arg
842 namesOfType (ForAllTy tyvar ty)         = namesOfType ty `minusNameSet` unitNameSet (getName tyvar)
843
844 namesOfTypes tys = foldr (unionNameSets . namesOfType) emptyNameSet tys
845 \end{code}
846
847
848 %************************************************************************
849 %*                                                                      *
850 \subsection{TidyType}
851 %*                                                                      *
852 %************************************************************************
853
854 tidyTy tidies up a type for printing in an error message, or in
855 an interface file.
856
857 It doesn't change the uniques at all, just the print names.
858
859 \begin{code}
860 tidyTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
861 tidyTyVar env@(tidy_env, subst) tyvar
862   = case lookupVarEnv subst tyvar of
863
864         Just tyvar' ->  -- Already substituted
865                 (env, tyvar')
866
867         Nothing ->      -- Make a new nice name for it
868
869                 case tidyOccName tidy_env (getOccName name) of
870                     (tidy', occ') ->    -- New occname reqd
871                                 ((tidy', subst'), tyvar')
872                               where
873                                 subst' = extendVarEnv subst tyvar tyvar'
874                                 tyvar' = setTyVarName tyvar name'
875                                 name'  = mkLocalName (getUnique name) occ' noSrcLoc
876                                         -- Note: make a *user* tyvar, so it printes nicely
877                                         -- Could extract src loc, but no need.
878   where
879     name = tyVarName tyvar
880
881 tidyTyVars env tyvars = mapAccumL tidyTyVar env tyvars
882
883 tidyType :: TidyEnv -> Type -> Type
884 tidyType env@(tidy_env, subst) ty
885   = go ty
886   where
887     go (TyVarTy tv)         = case lookupVarEnv subst tv of
888                                 Nothing  -> TyVarTy tv
889                                 Just tv' -> TyVarTy tv'
890     go (TyConApp tycon tys) = let args = map go tys
891                               in args `seqList` TyConApp tycon args
892     go (NoteTy note ty)     = (NoteTy SAPPLY (go_note note)) SAPPLY (go ty)
893     go (AppTy fun arg)      = (AppTy SAPPLY (go fun)) SAPPLY (go arg)
894     go (FunTy fun arg)      = (FunTy SAPPLY (go fun)) SAPPLY (go arg)
895     go (ForAllTy tv ty)     = ForAllTy tvp SAPPLY (tidyType envp ty)
896                               where
897                                 (envp, tvp) = tidyTyVar env tv
898
899     go_note (SynNote ty)        = SynNote SAPPLY (go ty)
900     go_note note@(FTVNote ftvs) = note  -- No need to tidy the free tyvars
901     go_note note@(UsgNote _)    = note  -- Usage annotation is already tidy
902     go_note note@(UsgForAll _)  = note  -- Uvar binder is already tidy
903     go_note (IPNote n)          = IPNote (tidyIPName n)
904
905 tidyTypes  env tys    = map (tidyType env) tys
906 \end{code}
907
908
909 @tidyOpenType@ grabs the free type variables, tidies them
910 and then uses @tidyType@ to work over the type itself
911
912 \begin{code}
913 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
914 tidyOpenType env ty
915   = (env', tidyType env' ty)
916   where
917     env'         = foldl go env (varSetElems (tyVarsOfType ty))
918     go env tyvar = fst (tidyTyVar env tyvar)
919
920 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
921 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
922
923 tidyTopType :: Type -> Type
924 tidyTopType ty = tidyType emptyTidyEnv ty
925 \end{code}
926
927 \begin{code}
928 tidyIPName :: Name -> Name
929 tidyIPName name
930   = mkLocalName (getUnique name) (getOccName name) noSrcLoc
931 \end{code}
932
933
934 %************************************************************************
935 %*                                                                      *
936 \subsection{Boxedness and liftedness}
937 %*                                                                      *
938 %************************************************************************
939
940 \begin{code}
941 isUnboxedType :: Type -> Bool
942 isUnboxedType ty = not (isFollowableRep (typePrimRep ty))
943
944 isUnLiftedType :: Type -> Bool
945         -- isUnLiftedType returns True for forall'd unlifted types:
946         --      x :: forall a. Int#
947         -- I found bindings like these were getting floated to the top level.
948         -- They are pretty bogus types, mind you.  It would be better never to
949         -- construct them
950
951 isUnLiftedType (ForAllTy tv ty) = isUnLiftedType ty
952 isUnLiftedType (NoteTy _ ty)    = isUnLiftedType ty
953 isUnLiftedType (TyConApp tc _)  = isUnLiftedTyCon tc
954 isUnLiftedType other            = False
955
956 isUnboxedTupleType :: Type -> Bool
957 isUnboxedTupleType ty = case splitTyConApp_maybe ty of
958                            Just (tc, ty_args) -> isUnboxedTupleTyCon tc
959                            other              -> False
960
961 -- Should only be applied to *types*; hence the assert
962 isAlgType :: Type -> Bool
963 isAlgType ty = case splitTyConApp_maybe ty of
964                         Just (tc, ty_args) -> ASSERT( length ty_args == tyConArity tc )
965                                               isAlgTyCon tc
966                         other              -> False
967
968 -- Should only be applied to *types*; hence the assert
969 isDataType :: Type -> Bool
970 isDataType ty = case splitTyConApp_maybe ty of
971                         Just (tc, ty_args) -> ASSERT( length ty_args == tyConArity tc )
972                                               isDataTyCon tc
973                         other              -> False
974
975 isNewType :: Type -> Bool
976 isNewType ty = case splitTyConApp_maybe ty of
977                         Just (tc, ty_args) -> ASSERT( length ty_args == tyConArity tc )
978                                               isNewTyCon tc
979                         other              -> False
980 \end{code}
981
982
983 %************************************************************************
984 %*                                                                      *
985 \subsection{Sequencing on types
986 %*                                                                      *
987 %************************************************************************
988
989 \begin{code}
990 seqType :: Type -> ()
991 seqType (TyVarTy tv)      = tv `seq` ()
992 seqType (AppTy t1 t2)     = seqType t1 `seq` seqType t2
993 seqType (FunTy t1 t2)     = seqType t1 `seq` seqType t2
994 seqType (NoteTy note t2)  = seqNote note `seq` seqType t2
995 seqType (TyConApp tc tys) = tc `seq` seqTypes tys
996 seqType (ForAllTy tv ty)  = tv `seq` seqType ty
997
998 seqTypes :: [Type] -> ()
999 seqTypes []       = ()
1000 seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
1001
1002 seqNote :: TyNote -> ()
1003 seqNote (SynNote ty)  = seqType ty
1004 seqNote (FTVNote set) = sizeUniqSet set `seq` ()
1005 seqNote (UsgNote usg) = usg `seq` ()
1006 seqNote (IPNote nm)    = nm `seq` ()
1007 \end{code}
1008