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