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