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