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