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