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