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