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