[project @ 2000-10-03 08:43:00 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(..), HsUsageAnn(..), HsTyVarBndr(..),
9         , HsContext, HsPred(..)
10         , HsTupCon(..), hsTupParens, mkHsTupCon,
11
12         , mkHsForAllTy, mkHsUsForAllTy, mkHsDictTy, mkHsIParamTy
13         , hsTyVarName, hsTyVarNames, replaceTyVarName
14
15         -- Printing
16         , pprParendHsType, pprHsForAll, pprHsContext, pprHsTyVarBndr
17
18         -- Equality over Hs things
19         , EqHsEnv, emptyEqHsEnv, extendEqHsEnv,
20         , eqWithHsTyVars, eq_hsVar, eq_hsVars, eq_hsType, eq_hsContext, eqListBy
21
22         -- Converting from Type to HsType
23         , toHsType, toHsTyVar, toHsTyVars, toHsContext, toHsFDs
24     ) where
25
26 #include "HsVersions.h"
27
28 import {-# SOURCE #-} HsExpr ( HsExpr ) 
29 import Class            ( FunDep )
30 import Type             ( Type, Kind, PredType(..), UsageAnn(..), ClassContext,
31                           getTyVar_maybe, splitSigmaTy, unUsgTy, boxedTypeKind
32                         )
33 import TypeRep          ( Type(..), TyNote(..) )        -- toHsType sees the representation
34 import TyCon            ( isTupleTyCon, tupleTyConBoxity, tyConArity )
35 import RdrName          ( RdrName )
36 import Name             ( toRdrName )
37 import OccName          ( NameSpace )
38 import Var              ( TyVar, tyVarKind )
39 import PprType          ( {- instance Outputable Kind -}, pprParendKind )
40 import BasicTypes       ( Arity, Boxity(..), tupleParens )
41 import PrelNames        ( mkTupConRdrName, listTyConKey, hasKey, Uniquable(..) )
42 import Maybes           ( maybeToBool )
43 import FiniteMap
44 import Outputable
45
46 \end{code}
47
48 This is the syntax for types as seen in type signatures.
49
50 \begin{code}
51 type HsContext name = [HsPred name]
52
53 data HsPred name = HsPClass name [HsType name]
54                  | HsPIParam name (HsType name)
55
56 data HsType name
57   = HsForAllTy  (Maybe [HsTyVarBndr name])      -- Nothing for implicitly quantified signatures
58                 (HsContext name)
59                 (HsType name)
60
61   | HsTyVar             name            -- Type variable or type constructor
62
63   | HsAppTy             (HsType name)
64                         (HsType name)
65
66   | HsFunTy             (HsType name) -- function type
67                         (HsType name)
68
69   | HsListTy            (HsType name)   -- Element type
70
71   | HsTupleTy           (HsTupCon name)
72                         [HsType name]   -- Element types (length gives arity)
73   -- Generics
74   | HsOpTy              (HsType name) name (HsType name)
75   | HsNumTy             Integer
76   -- these next two are only used in interfaces
77   | HsPredTy            (HsPred name)
78
79   | HsUsgTy           (HsUsageAnn name)
80                         (HsType name)
81
82   | HsUsgForAllTy     name
83                         (HsType name)
84
85 data HsUsageAnn name
86   = HsUsOnce
87   | HsUsMany
88   | HsUsVar name
89   
90
91 -----------------------
92 data HsTupCon name = HsTupCon name Boxity
93
94 instance Eq name => Eq (HsTupCon name) where
95   (HsTupCon _ b1) == (HsTupCon _ b2) = b1==b2
96    
97 mkHsTupCon :: NameSpace -> Boxity -> [a] -> HsTupCon RdrName
98 mkHsTupCon space boxity args = HsTupCon (mkTupConRdrName space boxity (length args)) boxity
99
100 hsTupParens :: HsTupCon name -> SDoc -> SDoc
101 hsTupParens (HsTupCon _ b) p = tupleParens b p
102
103 -----------------------
104 -- Combine adjacent for-alls. 
105 -- The following awkward situation can happen otherwise:
106 --      f :: forall a. ((Num a) => Int)
107 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
108 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
109 -- but the export list abstracts f wrt [a].  Disaster.
110 --
111 -- A valid type must have one for-all at the top of the type, or of the fn arg types
112
113 mkHsForAllTy (Just []) [] ty = ty       -- Explicit for-all with no tyvars
114 mkHsForAllTy mtvs1     [] (HsForAllTy mtvs2 ctxt ty) = mkHsForAllTy (mtvs1 `plus` mtvs2) ctxt ty
115                                                      where
116                                                        mtvs1       `plus` Nothing     = mtvs1
117                                                        Nothing     `plus` mtvs2       = mtvs2 
118                                                        (Just tvs1) `plus` (Just tvs2) = Just (tvs1 ++ tvs2)
119 mkHsForAllTy tvs ctxt ty = HsForAllTy tvs ctxt ty
120
121 mkHsUsForAllTy uvs ty = foldr (\ uv ty -> HsUsgForAllTy uv ty)
122                               ty uvs
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         (if null cxt then 
179                 empty 
180          else 
181                 ppr_context cxt <+> ptext SLIT("=>")
182         )
183     else        -- Used in interfaces
184         ptext SLIT("__forall") <+> interppSP tvs <+> 
185         ppr_context cxt <+> ptext SLIT("=>")
186
187 pprHsContext :: (Outputable name) => HsContext name -> SDoc
188 pprHsContext []  = empty
189 pprHsContext cxt = ppr_context cxt <+> ptext SLIT("=>")
190
191 ppr_context []  = empty
192 ppr_context cxt = parens (interpp'SP cxt)
193 \end{code}
194
195 \begin{code}
196 pREC_TOP = (0 :: Int)
197 pREC_FUN = (1 :: Int)
198 pREC_CON = (2 :: Int)
199
200 maybeParen :: Bool -> SDoc -> SDoc
201 maybeParen True  p = parens p
202 maybeParen False p = p
203         
204 -- printing works more-or-less as for Types
205
206 pprHsType, pprParendHsType :: (Outputable name) => HsType name -> SDoc
207
208 pprHsType ty       = ppr_mono_ty pREC_TOP ty
209 pprParendHsType ty = ppr_mono_ty pREC_CON ty
210
211 ppr_mono_ty ctxt_prec (HsForAllTy maybe_tvs ctxt ty)
212   = maybeParen (ctxt_prec >= pREC_FUN) $
213     sep [pp_header, pprHsType ty]
214   where
215     pp_header = case maybe_tvs of
216                   Just tvs -> pprHsForAll tvs ctxt
217                   Nothing  -> pprHsContext ctxt
218
219 ppr_mono_ty ctxt_prec (HsTyVar name)
220   = ppr name
221
222 ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2)
223   = let p1 = ppr_mono_ty pREC_FUN ty1
224         p2 = ppr_mono_ty pREC_TOP ty2
225     in
226     maybeParen (ctxt_prec >= pREC_FUN)
227                (sep [p1, (<>) (ptext SLIT("-> ")) p2])
228
229 ppr_mono_ty ctxt_prec (HsTupleTy con tys) = hsTupParens con (interpp'SP tys)
230 ppr_mono_ty ctxt_prec (HsListTy ty)       = brackets (ppr_mono_ty pREC_TOP ty)
231
232 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
233   = maybeParen (ctxt_prec >= pREC_CON)
234                (hsep [ppr_mono_ty pREC_FUN fun_ty, ppr_mono_ty pREC_CON arg_ty])
235
236 ppr_mono_ty ctxt_prec (HsPredTy pred) 
237   = maybeParen (ctxt_prec >= pREC_FUN) $
238     braces (ppr pred)
239
240 ppr_mono_ty ctxt_prec ty@(HsUsgForAllTy _ _)
241   = 
242     sep [ ptext SLIT("__fuall") <+> brackets pp_uvars <+> ptext SLIT("=>"),
243           ppr_mono_ty pREC_TOP sigma
244         ]
245   where
246     (uvars,sigma) = split [] ty
247     pp_uvars      = interppSP uvars
248
249     split uvs (HsUsgForAllTy uv ty') = split (uv:uvs) ty'
250     split uvs ty'                      = (reverse uvs,ty')
251
252 ppr_mono_ty ctxt_prec (HsUsgTy u ty)
253   = maybeParen (ctxt_prec >= pREC_CON) $
254     ptext SLIT("__u") <+> pp_ua <+> ppr_mono_ty pREC_CON ty
255   where
256     pp_ua = case u of
257               HsUsOnce   -> ptext SLIT("-")
258               HsUsMany   -> ptext SLIT("!")
259               HsUsVar uv -> ppr uv
260 -- Generics
261 ppr_mono_ty ctxt_prec (HsNumTy n) = integer  n
262 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2) = ppr ty1 <+> ppr op <+> ppr ty2
263 \end{code}
264
265
266 %************************************************************************
267 %*                                                                      *
268 \subsection{Converting from Type to HsType}
269 %*                                                                      *
270 %************************************************************************
271
272 @toHsType@ converts from a Type to a HsType, making the latter look as
273 user-friendly as possible.  Notably, it uses synonyms where possible, and
274 expresses overloaded functions using the '=>' context part of a HsForAllTy.
275
276 \begin{code}
277 toHsTyVar :: TyVar -> HsTyVarBndr RdrName
278 toHsTyVar tv = IfaceTyVar (toRdrName tv) (tyVarKind tv)
279
280 toHsTyVars tvs = map toHsTyVar tvs
281
282 toHsType :: Type -> HsType RdrName
283 toHsType ty = toHsType' (unUsgTy ty)
284         -- For now we just discard the usage
285 --  = case splitUsgTy ty of
286 --      (usg, tau) -> HsUsgTy (toHsUsg usg) (toHsType' tau)
287         
288 toHsType' :: Type -> HsType RdrName
289 -- Called after the usage is stripped off
290 -- This function knows the representation of types
291 toHsType' (TyVarTy tv)    = HsTyVar (toRdrName tv)
292 toHsType' (FunTy arg res) = HsFunTy (toHsType arg) (toHsType res)
293 toHsType' (AppTy fun arg) = HsAppTy (toHsType fun) (toHsType arg) 
294
295 toHsType' (NoteTy (SynNote ty) _) = toHsType ty         -- Use synonyms if possible!!
296 toHsType' (NoteTy _ ty)           = toHsType ty
297
298 toHsType' (PredTy p)              = HsPredTy (toHsPred p)
299
300 toHsType' ty@(TyConApp tc tys)  -- Must be saturated because toHsType's arg is of kind *
301   | not saturated            = generic_case
302   | isTupleTyCon tc          = HsTupleTy (HsTupCon (toRdrName tc) (tupleTyConBoxity tc)) tys'
303   | tc `hasKey` listTyConKey = HsListTy (head tys')
304   | otherwise                = generic_case
305   where
306      generic_case = foldl HsAppTy (HsTyVar (toRdrName tc)) tys'
307      tys'         = map toHsType tys
308      saturated    = length tys == tyConArity tc
309
310 toHsType' ty@(ForAllTy _ _) = case splitSigmaTy ty of
311                                 (tvs, preds, tau) -> HsForAllTy (Just (map toHsTyVar tvs))
312                                                                 (map toHsPred preds)
313                                                                 (toHsType tau)
314
315
316 toHsPred (Class cls tys) = HsPClass (toRdrName cls) (map toHsType tys)
317 toHsPred (IParam n ty)   = HsPIParam (toRdrName n)  (toHsType ty)
318
319 toHsContext :: ClassContext -> HsContext RdrName
320 toHsContext cxt = [HsPClass (toRdrName cls) (map toHsType tys) | (cls,tys) <- cxt]
321
322 toHsUsg UsOnce    = HsUsOnce
323 toHsUsg UsMany    = HsUsMany
324 toHsUsg (UsVar v) = HsUsVar (toRdrName v)
325
326 toHsFDs :: [FunDep TyVar] -> [FunDep RdrName]
327 toHsFDs fds = [(map toRdrName ns, map toRdrName ms) | (ns,ms) <- fds]
328 \end{code}
329
330
331 %************************************************************************
332 %*                                                                      *
333 \subsection{Comparison}
334 %*                                                                      *
335 %************************************************************************
336
337 \begin{code}
338 instance Ord a => Eq (HsType a) where
339         -- The Ord is needed because we keep a
340         -- finite map of variables to variables
341    (==) a b = eq_hsType emptyEqHsEnv a b
342
343 instance Ord a => Eq (HsPred a) where
344    (==) a b = eq_hsPred emptyEqHsEnv a b
345
346 eqWithHsTyVars :: Ord name =>
347                   [HsTyVarBndr name] -> [HsTyVarBndr name]
348                -> (EqHsEnv name -> Bool) -> Bool
349 eqWithHsTyVars = eq_hsTyVars emptyEqHsEnv
350 \end{code}
351
352 \begin{code}
353 type EqHsEnv n = FiniteMap n n
354 -- Tracks the mapping from L-variables to R-variables
355
356 eq_hsVar :: Ord n => EqHsEnv n -> n -> n -> Bool
357 eq_hsVar env n1 n2 = case lookupFM env n1 of
358                       Just n1 -> n1 == n2
359                       Nothing -> n1 == n2
360
361 extendEqHsEnv env n1 n2 
362   | n1 == n2  = env
363   | otherwise = addToFM env n1 n2
364
365 emptyEqHsEnv :: EqHsEnv n
366 emptyEqHsEnv = emptyFM
367 \end{code}
368
369 We do define a specialised equality for these \tr{*Type} types; used
370 in checking interfaces.
371
372 \begin{code}
373 -------------------
374 eq_hsTyVars env []          []         k = k env
375 eq_hsTyVars env (tv1:tvs1) (tv2:tvs2)  k = eq_hsTyVar env tv1 tv2 $ \ env ->
376                                            eq_hsTyVars env tvs1 tvs2 k
377 eq_hsTyVars env _ _ _ = False
378
379 eq_hsTyVar env (UserTyVar v1)     (UserTyVar v2)     k = k (extendEqHsEnv env v1 v2)
380 eq_hsTyVar env (IfaceTyVar v1 k1) (IfaceTyVar v2 k2) k = k1 == k2 && k (extendEqHsEnv env v1 v2)
381 eq_hsTyVar env _ _ _ = False
382
383 eq_hsVars env []       []       k = k env
384 eq_hsVars env (v1:bs1) (v2:bs2) k = eq_hsVars (extendEqHsEnv env v1 v2) bs1 bs2 k
385 eq_hsVars env _ _ _ = False
386 \end{code}
387
388 \begin{code}
389 -------------------
390 eq_hsTypes env = eqListBy (eq_hsType env)
391
392 -------------------
393 eq_hsType env (HsForAllTy tvs1 c1 t1) (HsForAllTy tvs2 c2 t2)
394   = eq_tvs tvs1 tvs2            $ \env ->
395     eq_hsContext env c1 c2      &&
396     eq_hsType env t1 t2
397   where
398     eq_tvs Nothing     (Just _) k    = False
399     eq_tvs Nothing     Nothing  k    = k env
400     eq_tvs (Just _)    Nothing  k    = False
401     eq_tvs (Just tvs1) (Just tvs2) k = eq_hsTyVars env tvs1 tvs2 k
402
403 eq_hsType env (HsTyVar n1) (HsTyVar n2)
404   = eq_hsVar env n1 n2
405
406 eq_hsType env (HsTupleTy c1 tys1) (HsTupleTy c2 tys2)
407   = (c1 == c2) && eq_hsTypes env tys1 tys2
408
409 eq_hsType env (HsListTy ty1) (HsListTy ty2)
410   = eq_hsType env ty1 ty2
411
412 eq_hsType env (HsAppTy fun_ty1 arg_ty1) (HsAppTy fun_ty2 arg_ty2)
413   = eq_hsType env fun_ty1 fun_ty2 && eq_hsType env arg_ty1 arg_ty2
414
415 eq_hsType env (HsFunTy a1 b1) (HsFunTy a2 b2)
416   = eq_hsType env a1 a2 && eq_hsType env b1 b2
417
418 eq_hsType env (HsPredTy p1) (HsPredTy p2)
419   = eq_hsPred env p1 p2
420
421 eq_hsType env (HsOpTy lty1 op1 rty1) (HsOpTy lty2 op2 rty2)
422   = eq_hsVar env op1 op2 && eq_hsType env lty1 lty2 && eq_hsType env rty1 rty2
423
424 eq_hsType env (HsUsgTy u1 ty1) (HsUsgTy u2 ty2)
425   = eqUsg u1 u2 && eq_hsType env ty1 ty2
426
427 eq_hsType env ty1 ty2 = False
428
429
430 -------------------
431 eq_hsContext env a b = eqListBy (eq_hsPred env) a b
432
433 -------------------
434 eq_hsPred env (HsPClass c1 tys1) (HsPClass c2 tys2)
435   = c1 == c2 &&  eq_hsTypes env tys1 tys2
436 eq_hsPred env (HsPIParam n1 ty1) (HsPIParam n2 ty2)
437   = n1 == n2 && eq_hsType env ty1 ty2
438 eq_hsPred env _ _ = False
439
440 -------------------
441 eqUsg  HsUsOnce     HsUsOnce    = True
442 eqUsg  HsUsMany     HsUsMany    = True
443 eqUsg (HsUsVar u1) (HsUsVar u2) = u1 == u2
444 eqUsg _ _ = 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}