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