[project @ 2001-12-20 11:19:05 by simonpj]
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsTypes.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsTypes]{Abstract syntax: user-defined types}
5
6 \begin{code}
7 module HsTypes (
8           HsType(..), HsTyVarBndr(..),
9         , HsContext, HsPred(..)
10         , HsTupCon(..), hsTupParens, mkHsTupCon,
11         , hsUsOnce, hsUsMany
12
13         , mkHsForAllTy, mkHsDictTy, mkHsIParamTy
14         , hsTyVarName, hsTyVarNames, replaceTyVarName
15         , getHsInstHead
16         
17         -- Type place holder
18         , PostTcType, placeHolderType,
19
20         -- Printing
21         , pprParendHsType, pprHsForAll, pprHsContext, ppr_hs_context, pprHsTyVarBndr
22
23         -- Equality over Hs things
24         , EqHsEnv, emptyEqHsEnv, extendEqHsEnv,
25         , eqWithHsTyVars, eq_hsVar, eq_hsVars, eq_hsTyVars, eq_hsType, eq_hsContext, eqListBy
26
27         -- Converting from Type to HsType
28         , toHsType, toHsTyVar, toHsTyVars, toHsContext, toHsFDs
29     ) where
30
31 #include "HsVersions.h"
32
33 import Class            ( FunDep )
34 import TcType           ( Type, Kind, ThetaType, SourceType(..), 
35                           tcSplitSigmaTy, liftedTypeKind, eqKind, tcEqType
36                         )
37 import TypeRep          ( Type(..), TyNote(..) )        -- toHsType sees the representation
38 import TyCon            ( isTupleTyCon, tupleTyConBoxity, tyConArity, isNewTyCon, getSynTyConDefn )
39 import RdrName          ( RdrName, mkUnqual )
40 import Name             ( Name, getName )
41 import OccName          ( NameSpace, tvName )
42 import Var              ( TyVar, tyVarKind )
43 import Subst            ( substTyWith )
44 import PprType          ( {- instance Outputable Kind -}, pprParendKind )
45 import BasicTypes       ( Boxity(..), Arity, IPName, tupleParens )
46 import PrelNames        ( mkTupConRdrName, listTyConKey, usOnceTyConKey, usManyTyConKey, hasKey,
47                           usOnceTyConName, usManyTyConName
48                         )
49 import FiniteMap
50 import Util             ( eqListBy, lengthIs )
51 import Outputable
52 \end{code}
53
54
55 %************************************************************************
56 %*                                                                      *
57 \subsection{Annotating the syntax}
58 %*                                                                      *
59 %************************************************************************
60
61 \begin{code}
62 type PostTcType = Type          -- Used for slots in the abstract syntax
63                                 -- where we want to keep slot for a type
64                                 -- to be added by the type checker...but
65                                 -- before typechecking it's just bogus
66
67 placeHolderType :: PostTcType   -- Used before typechecking
68 placeHolderType  = panic "Evaluated the place holder for a PostTcType"
69 \end{code}
70
71
72 %************************************************************************
73 %*                                                                      *
74 \subsection{Data types}
75 %*                                                                      *
76 %************************************************************************
77
78 This is the syntax for types as seen in type signatures.
79
80 \begin{code}
81 type HsContext name = [HsPred name]
82
83 data HsPred name = HsClassP name [HsType name]
84                  | HsIParam (IPName name) (HsType name)
85
86 data HsType name
87   = HsForAllTy  (Maybe [HsTyVarBndr name])      -- Nothing for implicitly quantified signatures
88                 (HsContext name)
89                 (HsType name)
90
91   | HsTyVar             name            -- Type variable or type constructor
92
93   | HsAppTy             (HsType name)
94                         (HsType name)
95
96   | HsFunTy             (HsType name) -- function type
97                         (HsType name)
98
99   | HsListTy            (HsType name)   -- Element type
100
101   | HsTupleTy           (HsTupCon name)
102                         [HsType name]   -- Element types (length gives arity)
103   -- Generics
104   | HsOpTy              (HsType name) name (HsType name)
105   | HsNumTy             Integer
106
107   -- these next two are only used in interfaces
108   | HsPredTy            (HsPred name)
109   
110   | HsUsageTy           (HsType name)   -- Usage annotation
111                         (HsType name)   -- Annotated type
112
113
114 -----------------------
115 hsUsOnce, hsUsMany :: HsType RdrName
116 hsUsOnce = HsTyVar (mkUnqual tvName SLIT("."))  -- deep magic
117 hsUsMany = HsTyVar (mkUnqual tvName SLIT("!"))  -- deep magic
118
119 hsUsOnce_Name, hsUsMany_Name :: HsType Name
120 hsUsOnce_Name = HsTyVar usOnceTyConName
121 hsUsMany_Name = HsTyVar usManyTyConName
122
123 -----------------------
124 data HsTupCon name = HsTupCon name Boxity Arity
125
126 instance Eq name => Eq (HsTupCon name) where
127   (HsTupCon _ b1 a1) == (HsTupCon _ b2 a2) = b1==b2 && a1==a2
128    
129 mkHsTupCon :: NameSpace -> Boxity -> [a] -> HsTupCon RdrName
130 mkHsTupCon space boxity args = HsTupCon (mkTupConRdrName space boxity arity) boxity arity
131                              where
132                                arity = length args
133
134 hsTupParens :: HsTupCon name -> SDoc -> SDoc
135 hsTupParens (HsTupCon _ b _) p = tupleParens b p
136
137 -----------------------
138 -- Combine adjacent for-alls. 
139 -- The following awkward situation can happen otherwise:
140 --      f :: forall a. ((Num a) => Int)
141 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
142 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
143 -- but the export list abstracts f wrt [a].  Disaster.
144 --
145 -- A valid type must have one for-all at the top of the type, or of the fn arg types
146
147 mkHsForAllTy (Just []) [] ty = ty       -- Explicit for-all with no tyvars
148 mkHsForAllTy mtvs1     [] (HsForAllTy mtvs2 ctxt ty) = mkHsForAllTy (mtvs1 `plus` mtvs2) ctxt ty
149                                                      where
150                                                        mtvs1       `plus` Nothing     = mtvs1
151                                                        Nothing     `plus` mtvs2       = mtvs2 
152                                                        (Just tvs1) `plus` (Just tvs2) = Just (tvs1 ++ tvs2)
153 mkHsForAllTy tvs ctxt ty = HsForAllTy tvs ctxt ty
154
155 mkHsDictTy cls tys = HsPredTy (HsClassP cls tys)
156 mkHsIParamTy v ty  = HsPredTy (HsIParam v ty)
157
158 data HsTyVarBndr name
159   = UserTyVar name
160   | IfaceTyVar name Kind
161         -- *** NOTA BENE *** A "monotype" in a pragma can have
162         -- for-alls in it, (mostly to do with dictionaries).  These
163         -- must be explicitly Kinded.
164
165 hsTyVarName (UserTyVar n)    = n
166 hsTyVarName (IfaceTyVar n _) = n
167
168 hsTyVarNames tvs = map hsTyVarName tvs
169
170 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
171 replaceTyVarName (UserTyVar n)    n' = UserTyVar n'
172 replaceTyVarName (IfaceTyVar n k) n' = IfaceTyVar n' k
173 \end{code}
174
175
176 \begin{code}
177 getHsInstHead :: HsType name -> ([HsTyVarBndr name], (name, [HsType name]))
178         -- Split up an instance decl type, returning the 'head' part
179
180 -- In interface fiels, the type of the decl is held like this:
181 --      forall a. Foo a -> Baz (T a)
182 -- so we have to strip off function argument types,
183 -- as well as the bit before the '=>' (which is always 
184 -- empty in interface files)
185 --
186 -- The parser ensures the type will have the right shape.
187 -- (e.g. see ParseUtil.checkInstType)
188
189 getHsInstHead  (HsForAllTy (Just tvs) _ tau) = (tvs, get_head1 tau)
190 getHsInstHead  tau                           = ([],  get_head1 tau)
191
192 get_head1 (HsFunTy _ ty)                = get_head1 ty
193 get_head1 (HsPredTy (HsClassP cls tys)) = (cls,tys)
194 \end{code}
195
196
197 %************************************************************************
198 %*                                                                      *
199 \subsection{Pretty printing}
200 %*                                                                      *
201 %************************************************************************
202
203 NB: these types get printed into interface files, so 
204     don't change the printing format lightly
205
206 \begin{code}
207 instance (Outputable name) => Outputable (HsType name) where
208     ppr ty = pprHsType ty
209
210 instance (Outputable name) => Outputable (HsTyVarBndr name) where
211     ppr (UserTyVar name)       = ppr name
212     ppr (IfaceTyVar name kind) = pprHsTyVarBndr name kind
213
214 instance Outputable name => Outputable (HsPred name) where
215     ppr (HsClassP clas tys) = ppr clas <+> hsep (map pprParendHsType tys)
216     ppr (HsIParam n ty)    = hsep [ppr n, dcolon, ppr ty]
217
218 pprHsTyVarBndr :: Outputable name => name -> Kind -> SDoc
219 pprHsTyVarBndr name kind | kind `eqKind` liftedTypeKind = ppr name
220                          | otherwise                    = hsep [ppr name, dcolon, pprParendKind kind]
221
222 pprHsForAll []  []  = empty
223 pprHsForAll tvs cxt 
224         -- This printer is used for both interface files and
225         -- printing user types in error messages; and alas the
226         -- two use slightly different syntax.  Ah well.
227   = getPprStyle $ \ sty ->
228     if userStyle sty then
229         ptext SLIT("forall") <+> interppSP tvs <> dot <+> 
230               -- **! ToDo: want to hide uvars from user, but not enough info
231               -- in a HsTyVarBndr name (see PprType).  KSW 2000-10.
232         pprHsContext cxt
233     else        -- Used in interfaces
234         ptext SLIT("__forall") <+> interppSP tvs <+> 
235         ppr_hs_context cxt <+> ptext SLIT("=>")
236
237 pprHsContext :: (Outputable name) => HsContext name -> SDoc
238 pprHsContext []  = empty
239 pprHsContext cxt = ppr_hs_context cxt <+> ptext SLIT("=>")
240
241 ppr_hs_context []  = empty
242 ppr_hs_context cxt = parens (interpp'SP cxt)
243 \end{code}
244
245 \begin{code}
246 pREC_TOP = (0 :: Int)  -- type   in ParseIface.y
247 pREC_FUN = (1 :: Int)  -- btype  in ParseIface.y
248 pREC_CON = (2 :: Int)  -- atype  in ParseIface.y
249
250 maybeParen :: Bool -> SDoc -> SDoc
251 maybeParen True  p = parens p
252 maybeParen False p = p
253         
254 -- printing works more-or-less as for Types
255
256 pprHsType, pprParendHsType :: (Outputable name) => HsType name -> SDoc
257
258 pprHsType ty       = ppr_mono_ty pREC_TOP ty
259 pprParendHsType ty = ppr_mono_ty pREC_CON ty
260
261 ppr_mono_ty ctxt_prec (HsForAllTy maybe_tvs ctxt ty)
262   = maybeParen (ctxt_prec >= pREC_FUN) $
263     sep [pp_header, pprHsType ty]
264   where
265     pp_header = case maybe_tvs of
266                   Just tvs -> pprHsForAll tvs ctxt
267                   Nothing  -> pprHsContext ctxt
268
269 ppr_mono_ty ctxt_prec (HsTyVar name)
270   = ppr name
271
272 ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2)
273   = let p1 = ppr_mono_ty pREC_FUN ty1
274         p2 = ppr_mono_ty pREC_TOP ty2
275     in
276     maybeParen (ctxt_prec >= pREC_FUN)
277                (sep [p1, (<>) (ptext SLIT("-> ")) p2])
278
279 ppr_mono_ty ctxt_prec (HsTupleTy con tys) = hsTupParens con (interpp'SP tys)
280 ppr_mono_ty ctxt_prec (HsListTy ty)       = brackets (ppr_mono_ty pREC_TOP ty)
281
282 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
283   = maybeParen (ctxt_prec >= pREC_CON)
284                (hsep [ppr_mono_ty pREC_FUN fun_ty, ppr_mono_ty pREC_CON arg_ty])
285
286 ppr_mono_ty ctxt_prec (HsPredTy pred) 
287   = braces (ppr pred)
288
289 ppr_mono_ty ctxt_prec (HsUsageTy u ty)
290   = maybeParen (ctxt_prec >= pREC_CON)
291                (sep [ptext SLIT("__u") <+> ppr_mono_ty pREC_CON u,
292                      ppr_mono_ty pREC_CON ty])
293     -- pREC_FUN would be logical for u, but it yields a reduce/reduce conflict with AppTy
294
295 -- Generics
296 ppr_mono_ty ctxt_prec (HsNumTy n) = integer  n
297 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2) = ppr ty1 <+> ppr op <+> ppr ty2
298 \end{code}
299
300
301 %************************************************************************
302 %*                                                                      *
303 \subsection{Converting from Type to HsType}
304 %*                                                                      *
305 %************************************************************************
306
307 @toHsType@ converts from a Type to a HsType, making the latter look as
308 user-friendly as possible.  Notably, it uses synonyms where possible, and
309 expresses overloaded functions using the '=>' context part of a HsForAllTy.
310
311 \begin{code}
312 toHsTyVar :: TyVar -> HsTyVarBndr Name
313 toHsTyVar tv = IfaceTyVar (getName tv) (tyVarKind tv)
314
315 toHsTyVars tvs = map toHsTyVar tvs
316
317 toHsType :: Type -> HsType Name
318 -- This function knows the representation of types
319 toHsType (TyVarTy tv)    = HsTyVar (getName tv)
320 toHsType (FunTy arg res) = HsFunTy (toHsType arg) (toHsType res)
321 toHsType (AppTy fun arg) = HsAppTy (toHsType fun) (toHsType arg) 
322
323 toHsType (NoteTy (SynNote ty@(TyConApp tycon tyargs)) real_ty)
324   | isNewTyCon tycon = toHsType ty
325   | syn_matches      = toHsType ty             -- Use synonyms if possible!!
326   | otherwise        = 
327 #ifdef DEBUG
328                        pprTrace "WARNING: synonym info lost in .hi file for " (ppr syn_ty) $
329 #endif
330                        toHsType real_ty              -- but drop it if not.
331   where
332     syn_matches      = ty_from_syn `tcEqType` real_ty
333     (tyvars,syn_ty)  = getSynTyConDefn tycon
334     ty_from_syn      = substTyWith tyvars tyargs syn_ty
335
336     -- We only use the type synonym in the file if this doesn't cause
337     -- us to lose important information.  This matters for usage
338     -- annotations.  It's an issue if some of the args to the synonym
339     -- have arrows in them, or if the synonym's RHS has an arrow; for
340     -- example, with nofib/real/ebnf2ps/ in Parsers.using.
341
342     -- **! It would be nice if when this test fails we could still
343     -- write the synonym in as a Note, so we don't lose the info for
344     -- error messages, but it's too much work for right now.
345     -- KSW 2000-07.
346
347 toHsType (NoteTy _ ty)         = toHsType ty
348
349 toHsType (SourceTy (NType tc tys)) = foldl HsAppTy (HsTyVar (getName tc)) (map toHsType tys)
350 toHsType (SourceTy pred)           = HsPredTy (toHsPred pred)
351
352 toHsType ty@(TyConApp tc tys)   -- Must be saturated because toHsType's arg is of kind *
353   | not saturated              = generic_case
354   | isTupleTyCon tc            = HsTupleTy (HsTupCon (getName tc) (tupleTyConBoxity tc) (tyConArity tc)) tys'
355   | tc `hasKey` listTyConKey   = HsListTy (head tys')
356   | tc `hasKey` usOnceTyConKey = hsUsOnce_Name           -- must print !, . unqualified
357   | tc `hasKey` usManyTyConKey = hsUsMany_Name           -- must print !, . unqualified
358   | otherwise                  = generic_case
359   where
360      generic_case = foldl HsAppTy (HsTyVar (getName tc)) tys'
361      tys'         = map toHsType tys
362      saturated    = tys `lengthIs` tyConArity tc
363
364 toHsType ty@(ForAllTy _ _) = case tcSplitSigmaTy ty of
365                                 (tvs, preds, tau) -> HsForAllTy (Just (map toHsTyVar tvs))
366                                                                 (map toHsPred preds)
367                                                                 (toHsType tau)
368
369 toHsType (UsageTy u ty) = HsUsageTy (toHsType u) (toHsType ty)
370                           -- **! consider dropping usMany annotations ToDo KSW 2000-10
371
372
373 toHsPred (ClassP cls tys) = HsClassP (getName cls) (map toHsType tys)
374 toHsPred (IParam n ty)    = HsIParam n             (toHsType ty)
375
376 toHsContext :: ThetaType -> HsContext Name
377 toHsContext theta = map toHsPred theta
378
379 toHsFDs :: [FunDep TyVar] -> [FunDep Name]
380 toHsFDs fds = [(map getName ns, map getName ms) | (ns,ms) <- fds]
381 \end{code}
382
383
384 %************************************************************************
385 %*                                                                      *
386 \subsection{Comparison}
387 %*                                                                      *
388 %************************************************************************
389
390 \begin{code}
391 instance Ord a => Eq (HsType a) where
392         -- The Ord is needed because we keep a
393         -- finite map of variables to variables
394    (==) a b = eq_hsType emptyEqHsEnv a b
395
396 instance Ord a => Eq (HsPred a) where
397    (==) a b = eq_hsPred emptyEqHsEnv a b
398
399 eqWithHsTyVars :: Ord name =>
400                   [HsTyVarBndr name] -> [HsTyVarBndr name]
401                -> (EqHsEnv name -> Bool) -> Bool
402 eqWithHsTyVars = eq_hsTyVars emptyEqHsEnv
403 \end{code}
404
405 \begin{code}
406 type EqHsEnv n = FiniteMap n n
407 -- Tracks the mapping from L-variables to R-variables
408
409 eq_hsVar :: Ord n => EqHsEnv n -> n -> n -> Bool
410 eq_hsVar env n1 n2 = case lookupFM env n1 of
411                       Just n1 -> n1 == n2
412                       Nothing -> n1 == n2
413
414 extendEqHsEnv env n1 n2 
415   | n1 == n2  = env
416   | otherwise = addToFM env n1 n2
417
418 emptyEqHsEnv :: EqHsEnv n
419 emptyEqHsEnv = emptyFM
420 \end{code}
421
422 We do define a specialised equality for these \tr{*Type} types; used
423 in checking interfaces.
424
425 \begin{code}
426 -------------------
427 eq_hsTyVars env []          []         k = k env
428 eq_hsTyVars env (tv1:tvs1) (tv2:tvs2)  k = eq_hsTyVar env tv1 tv2 $ \ env ->
429                                            eq_hsTyVars env tvs1 tvs2 k
430 eq_hsTyVars env _ _ _ = False
431
432 eq_hsTyVar env (UserTyVar v1)     (UserTyVar v2)     k = k (extendEqHsEnv env v1 v2)
433 eq_hsTyVar env (IfaceTyVar v1 k1) (IfaceTyVar v2 k2) k = k1 `eqKind` k2 && k (extendEqHsEnv env v1 v2)
434 eq_hsTyVar env _ _ _ = False
435
436 eq_hsVars env []       []       k = k env
437 eq_hsVars env (v1:bs1) (v2:bs2) k = eq_hsVars (extendEqHsEnv env v1 v2) bs1 bs2 k
438 eq_hsVars env _ _ _ = False
439 \end{code}
440
441 \begin{code}
442 -------------------
443 eq_hsTypes env = eqListBy (eq_hsType env)
444
445 -------------------
446 eq_hsType env (HsForAllTy tvs1 c1 t1) (HsForAllTy tvs2 c2 t2)
447   = eq_tvs tvs1 tvs2            $ \env ->
448     eq_hsContext env c1 c2      &&
449     eq_hsType env t1 t2
450   where
451     eq_tvs Nothing     (Just _) k    = False
452     eq_tvs Nothing     Nothing  k    = k env
453     eq_tvs (Just _)    Nothing  k    = False
454     eq_tvs (Just tvs1) (Just tvs2) k = eq_hsTyVars env tvs1 tvs2 k
455
456 eq_hsType env (HsTyVar n1) (HsTyVar n2)
457   = eq_hsVar env n1 n2
458
459 eq_hsType env (HsTupleTy c1 tys1) (HsTupleTy c2 tys2)
460   = (c1 == c2) && eq_hsTypes env tys1 tys2
461
462 eq_hsType env (HsListTy ty1) (HsListTy ty2)
463   = eq_hsType env ty1 ty2
464
465 eq_hsType env (HsAppTy fun_ty1 arg_ty1) (HsAppTy fun_ty2 arg_ty2)
466   = eq_hsType env fun_ty1 fun_ty2 && eq_hsType env arg_ty1 arg_ty2
467
468 eq_hsType env (HsFunTy a1 b1) (HsFunTy a2 b2)
469   = eq_hsType env a1 a2 && eq_hsType env b1 b2
470
471 eq_hsType env (HsPredTy p1) (HsPredTy p2)
472   = eq_hsPred env p1 p2
473
474 eq_hsType env (HsUsageTy u1 ty1) (HsUsageTy u2 ty2)
475   = eq_hsType env u1 u2 && eq_hsType env ty1 ty2
476
477 eq_hsType env (HsOpTy lty1 op1 rty1) (HsOpTy lty2 op2 rty2)
478   = eq_hsVar env op1 op2 && eq_hsType env lty1 lty2 && eq_hsType env rty1 rty2
479
480 eq_hsType env ty1 ty2 = False
481
482
483 -------------------
484 eq_hsContext env a b = eqListBy (eq_hsPred env) a b
485
486 -------------------
487 eq_hsPred env (HsClassP c1 tys1) (HsClassP c2 tys2)
488   = c1 == c2 &&  eq_hsTypes env tys1 tys2
489 eq_hsPred env (HsIParam n1 ty1) (HsIParam n2 ty2)
490   = n1 == n2 && eq_hsType env ty1 ty2
491 eq_hsPred env _ _ = False
492 \end{code}