[project @ 2001-07-12 16:21:22 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(..), HsTyVarBndr(..),
9         , HsContext, HsPred(..)
10         , HsTupCon(..), hsTupParens, mkHsTupCon,
11         , hsUsOnce, hsUsMany
12
13         , mkHsForAllTy, mkHsDictTy, mkHsIParamTy
14         , hsTyVarName, hsTyVarNames, replaceTyVarName,
15         
16         -- Type place holder
17         PostTcType, placeHolderType,
18
19         -- Printing
20         , pprParendHsType, pprHsForAll, pprHsContext, pprHsTyVarBndr
21
22         -- Equality over Hs things
23         , EqHsEnv, emptyEqHsEnv, extendEqHsEnv,
24         , eqWithHsTyVars, eq_hsVar, eq_hsVars, eq_hsTyVars, eq_hsType, eq_hsContext, eqListBy
25
26         -- Converting from Type to HsType
27         , toHsType, toHsTyVar, toHsTyVars, toHsContext, toHsFDs
28     ) where
29
30 #include "HsVersions.h"
31
32 import Class            ( FunDep )
33 import TcType           ( Type, Kind, ThetaType, SourceType(..), 
34                           tcSplitSigmaTy, liftedTypeKind, eqKind, tcEqType
35                         )
36 import TypeRep          ( Type(..), TyNote(..) )        -- toHsType sees the representation
37 import TyCon            ( isTupleTyCon, tupleTyConBoxity, tyConArity, isNewTyCon, getSynTyConDefn )
38 import RdrName          ( RdrName, mkUnqual )
39 import Name             ( Name, getName )
40 import OccName          ( NameSpace, tvName )
41 import Var              ( TyVar, tyVarKind )
42 import Subst            ( mkTyVarSubst, substTy )
43 import PprType          ( {- instance Outputable Kind -}, pprParendKind )
44 import BasicTypes       ( Boxity(..), Arity, tupleParens )
45 import PrelNames        ( mkTupConRdrName, listTyConKey, usOnceTyConKey, usManyTyConKey, hasKey,
46                           usOnceTyConName, usManyTyConName
47                         )
48 import FiniteMap
49 import Outputable
50 \end{code}
51
52
53 %************************************************************************
54 %*                                                                      *
55 \subsection{Annotating the syntax}
56 %*                                                                      *
57 %************************************************************************
58
59 \begin{code}
60 type PostTcType = Type          -- Used for slots in the abstract syntax
61                                 -- where we want to keep slot for a type
62                                 -- to be added by the type checker...but
63                                 -- before typechecking it's just bogus
64
65 placeHolderType :: PostTcType   -- Used before typechecking
66 placeHolderType  = panic "Evaluated the place holder for a PostTcType"
67 \end{code}
68
69
70 %************************************************************************
71 %*                                                                      *
72 \subsection{Data types}
73 %*                                                                      *
74 %************************************************************************
75
76 This is the syntax for types as seen in type signatures.
77
78 \begin{code}
79 type HsContext name = [HsPred name]
80
81 data HsPred name = HsClassP name [HsType name]
82                  | HsIParam name (HsType name)
83
84 data HsType name
85   = HsForAllTy  (Maybe [HsTyVarBndr name])      -- Nothing for implicitly quantified signatures
86                 (HsContext name)
87                 (HsType name)
88
89   | HsTyVar             name            -- Type variable or type constructor
90
91   | HsAppTy             (HsType name)
92                         (HsType name)
93
94   | HsFunTy             (HsType name) -- function type
95                         (HsType name)
96
97   | HsListTy            (HsType name)   -- Element type
98
99   | HsTupleTy           (HsTupCon name)
100                         [HsType name]   -- Element types (length gives arity)
101   -- Generics
102   | HsOpTy              (HsType name) name (HsType name)
103   | HsNumTy             Integer
104
105   -- these next two are only used in interfaces
106   | HsPredTy            (HsPred name)
107   
108   | HsUsageTy           (HsType name)   -- Usage annotation
109                         (HsType name)   -- Annotated type
110
111
112 -----------------------
113 hsUsOnce, hsUsMany :: HsType RdrName
114 hsUsOnce = HsTyVar (mkUnqual tvName SLIT("."))  -- deep magic
115 hsUsMany = HsTyVar (mkUnqual tvName SLIT("!"))  -- deep magic
116
117 hsUsOnce_Name, hsUsMany_Name :: HsType Name
118 hsUsOnce_Name = HsTyVar usOnceTyConName
119 hsUsMany_Name = HsTyVar usManyTyConName
120
121 -----------------------
122 data HsTupCon name = HsTupCon name Boxity Arity
123
124 instance Eq name => Eq (HsTupCon name) where
125   (HsTupCon _ b1 a1) == (HsTupCon _ b2 a2) = b1==b2 && a1==a2
126    
127 mkHsTupCon :: NameSpace -> Boxity -> [a] -> HsTupCon RdrName
128 mkHsTupCon space boxity args = HsTupCon (mkTupConRdrName space boxity arity) boxity arity
129                              where
130                                arity = length args
131
132 hsTupParens :: HsTupCon name -> SDoc -> SDoc
133 hsTupParens (HsTupCon _ b _) p = tupleParens b p
134
135 -----------------------
136 -- Combine adjacent for-alls. 
137 -- The following awkward situation can happen otherwise:
138 --      f :: forall a. ((Num a) => Int)
139 -- might generate HsForAll (Just [a]) [] (HsForAll Nothing [Num a] t)
140 -- Then a isn't discovered as ambiguous, and we abstract the AbsBinds wrt []
141 -- but the export list abstracts f wrt [a].  Disaster.
142 --
143 -- A valid type must have one for-all at the top of the type, or of the fn arg types
144
145 mkHsForAllTy (Just []) [] ty = ty       -- Explicit for-all with no tyvars
146 mkHsForAllTy mtvs1     [] (HsForAllTy mtvs2 ctxt ty) = mkHsForAllTy (mtvs1 `plus` mtvs2) ctxt ty
147                                                      where
148                                                        mtvs1       `plus` Nothing     = mtvs1
149                                                        Nothing     `plus` mtvs2       = mtvs2 
150                                                        (Just tvs1) `plus` (Just tvs2) = Just (tvs1 ++ tvs2)
151 mkHsForAllTy tvs ctxt ty = HsForAllTy tvs ctxt ty
152
153 mkHsDictTy cls tys = HsPredTy (HsClassP cls tys)
154 mkHsIParamTy v ty  = HsPredTy (HsIParam v ty)
155
156 data HsTyVarBndr name
157   = UserTyVar name
158   | IfaceTyVar name Kind
159         -- *** NOTA BENE *** A "monotype" in a pragma can have
160         -- for-alls in it, (mostly to do with dictionaries).  These
161         -- must be explicitly Kinded.
162
163 hsTyVarName (UserTyVar n)    = n
164 hsTyVarName (IfaceTyVar n _) = n
165
166 hsTyVarNames tvs = map hsTyVarName tvs
167
168 replaceTyVarName :: HsTyVarBndr name1 -> name2 -> HsTyVarBndr name2
169 replaceTyVarName (UserTyVar n)    n' = UserTyVar n'
170 replaceTyVarName (IfaceTyVar n k) n' = IfaceTyVar n' k
171 \end{code}
172
173
174 %************************************************************************
175 %*                                                                      *
176 \subsection{Pretty printing}
177 %*                                                                      *
178 %************************************************************************
179
180 NB: these types get printed into interface files, so 
181     don't change the printing format lightly
182
183 \begin{code}
184 instance (Outputable name) => Outputable (HsType name) where
185     ppr ty = pprHsType ty
186
187 instance (Outputable name) => Outputable (HsTyVarBndr name) where
188     ppr (UserTyVar name)       = ppr name
189     ppr (IfaceTyVar name kind) = pprHsTyVarBndr name kind
190
191 instance Outputable name => Outputable (HsPred name) where
192     ppr (HsClassP clas tys) = ppr clas <+> hsep (map pprParendHsType tys)
193     ppr (HsIParam n ty)    = hsep [char '?' <> ppr n, text "::", ppr ty]
194
195 pprHsTyVarBndr :: Outputable name => name -> Kind -> SDoc
196 pprHsTyVarBndr name kind | kind `eqKind` liftedTypeKind = ppr name
197                          | otherwise                    = hsep [ppr name, dcolon, pprParendKind kind]
198
199 pprHsForAll []  []  = empty
200 pprHsForAll tvs cxt 
201         -- This printer is used for both interface files and
202         -- printing user types in error messages; and alas the
203         -- two use slightly different syntax.  Ah well.
204   = getPprStyle $ \ sty ->
205     if userStyle sty then
206         ptext SLIT("forall") <+> interppSP tvs <> dot <+> 
207               -- **! ToDo: want to hide uvars from user, but not enough info
208               -- in a HsTyVarBndr name (see PprType).  KSW 2000-10.
209         (if null cxt then 
210                 empty 
211          else 
212                 ppr_context cxt <+> ptext SLIT("=>")
213         )
214     else        -- Used in interfaces
215         ptext SLIT("__forall") <+> interppSP tvs <+> 
216         ppr_context cxt <+> ptext SLIT("=>")
217
218 pprHsContext :: (Outputable name) => HsContext name -> SDoc
219 pprHsContext []  = empty
220 pprHsContext cxt = ppr_context cxt <+> ptext SLIT("=>")
221
222 ppr_context []  = empty
223 ppr_context cxt = parens (interpp'SP cxt)
224 \end{code}
225
226 \begin{code}
227 pREC_TOP = (0 :: Int)  -- type   in ParseIface.y
228 pREC_FUN = (1 :: Int)  -- btype  in ParseIface.y
229 pREC_CON = (2 :: Int)  -- atype  in ParseIface.y
230
231 maybeParen :: Bool -> SDoc -> SDoc
232 maybeParen True  p = parens p
233 maybeParen False p = p
234         
235 -- printing works more-or-less as for Types
236
237 pprHsType, pprParendHsType :: (Outputable name) => HsType name -> SDoc
238
239 pprHsType ty       = ppr_mono_ty pREC_TOP ty
240 pprParendHsType ty = ppr_mono_ty pREC_CON ty
241
242 ppr_mono_ty ctxt_prec (HsForAllTy maybe_tvs ctxt ty)
243   = maybeParen (ctxt_prec >= pREC_FUN) $
244     sep [pp_header, pprHsType ty]
245   where
246     pp_header = case maybe_tvs of
247                   Just tvs -> pprHsForAll tvs ctxt
248                   Nothing  -> pprHsContext ctxt
249
250 ppr_mono_ty ctxt_prec (HsTyVar name)
251   = ppr name
252
253 ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2)
254   = let p1 = ppr_mono_ty pREC_FUN ty1
255         p2 = ppr_mono_ty pREC_TOP ty2
256     in
257     maybeParen (ctxt_prec >= pREC_FUN)
258                (sep [p1, (<>) (ptext SLIT("-> ")) p2])
259
260 ppr_mono_ty ctxt_prec (HsTupleTy con tys) = hsTupParens con (interpp'SP tys)
261 ppr_mono_ty ctxt_prec (HsListTy ty)       = brackets (ppr_mono_ty pREC_TOP ty)
262
263 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
264   = maybeParen (ctxt_prec >= pREC_CON)
265                (hsep [ppr_mono_ty pREC_FUN fun_ty, ppr_mono_ty pREC_CON arg_ty])
266
267 ppr_mono_ty ctxt_prec (HsPredTy pred) 
268   = braces (ppr pred)
269
270 ppr_mono_ty ctxt_prec (HsUsageTy u ty)
271   = maybeParen (ctxt_prec >= pREC_CON)
272                (sep [ptext SLIT("__u") <+> ppr_mono_ty pREC_CON u,
273                      ppr_mono_ty pREC_CON ty])
274     -- pREC_FUN would be logical for u, but it yields a reduce/reduce conflict with AppTy
275
276 -- Generics
277 ppr_mono_ty ctxt_prec (HsNumTy n) = integer  n
278 ppr_mono_ty ctxt_prec (HsOpTy ty1 op ty2) = ppr ty1 <+> ppr op <+> ppr ty2
279 \end{code}
280
281
282 %************************************************************************
283 %*                                                                      *
284 \subsection{Converting from Type to HsType}
285 %*                                                                      *
286 %************************************************************************
287
288 @toHsType@ converts from a Type to a HsType, making the latter look as
289 user-friendly as possible.  Notably, it uses synonyms where possible, and
290 expresses overloaded functions using the '=>' context part of a HsForAllTy.
291
292 \begin{code}
293 toHsTyVar :: TyVar -> HsTyVarBndr Name
294 toHsTyVar tv = IfaceTyVar (getName tv) (tyVarKind tv)
295
296 toHsTyVars tvs = map toHsTyVar tvs
297
298 toHsType :: Type -> HsType Name
299 -- This function knows the representation of types
300 toHsType (TyVarTy tv)    = HsTyVar (getName tv)
301 toHsType (FunTy arg res) = HsFunTy (toHsType arg) (toHsType res)
302 toHsType (AppTy fun arg) = HsAppTy (toHsType fun) (toHsType arg) 
303
304 toHsType (NoteTy (SynNote ty@(TyConApp tycon tyargs)) real_ty)
305   | isNewTyCon tycon = toHsType ty
306   | syn_matches      = toHsType ty             -- Use synonyms if possible!!
307   | otherwise        = 
308 #ifdef DEBUG
309                        pprTrace "WARNING: synonym info lost in .hi file for " (ppr syn_ty) $
310 #endif
311                        toHsType real_ty              -- but drop it if not.
312   where
313     syn_matches      = ty_from_syn `tcEqType` real_ty
314     (tyvars,syn_ty)  = getSynTyConDefn tycon
315     ty_from_syn      = substTy (mkTyVarSubst tyvars tyargs) syn_ty
316
317     -- We only use the type synonym in the file if this doesn't cause
318     -- us to lose important information.  This matters for usage
319     -- annotations.  It's an issue if some of the args to the synonym
320     -- have arrows in them, or if the synonym's RHS has an arrow; for
321     -- example, with nofib/real/ebnf2ps/ in Parsers.using.
322
323     -- **! It would be nice if when this test fails we could still
324     -- write the synonym in as a Note, so we don't lose the info for
325     -- error messages, but it's too much work for right now.
326     -- KSW 2000-07.
327
328 toHsType (NoteTy _ ty)         = toHsType ty
329
330 toHsType (SourceTy (NType tc tys)) = foldl HsAppTy (HsTyVar (getName tc)) (map toHsType tys)
331 toHsType (SourceTy pred)           = HsPredTy (toHsPred pred)
332
333 toHsType ty@(TyConApp tc tys)   -- Must be saturated because toHsType's arg is of kind *
334   | not saturated              = generic_case
335   | isTupleTyCon tc            = HsTupleTy (HsTupCon (getName tc) (tupleTyConBoxity tc) (tyConArity tc)) tys'
336   | tc `hasKey` listTyConKey   = HsListTy (head tys')
337   | tc `hasKey` usOnceTyConKey = hsUsOnce_Name           -- must print !, . unqualified
338   | tc `hasKey` usManyTyConKey = hsUsMany_Name           -- must print !, . unqualified
339   | otherwise                  = generic_case
340   where
341      generic_case = foldl HsAppTy (HsTyVar (getName tc)) tys'
342      tys'         = map toHsType tys
343      saturated    = length tys == tyConArity tc
344
345 toHsType ty@(ForAllTy _ _) = case tcSplitSigmaTy ty of
346                                 (tvs, preds, tau) -> HsForAllTy (Just (map toHsTyVar tvs))
347                                                                 (map toHsPred preds)
348                                                                 (toHsType tau)
349
350 toHsType (UsageTy u ty) = HsUsageTy (toHsType u) (toHsType ty)
351                           -- **! consider dropping usMany annotations ToDo KSW 2000-10
352
353
354 toHsPred (ClassP cls tys) = HsClassP (getName cls) (map toHsType tys)
355 toHsPred (IParam n ty)    = HsIParam (getName n)  (toHsType ty)
356
357 toHsContext :: ThetaType -> HsContext Name
358 toHsContext theta = map toHsPred theta
359
360 toHsFDs :: [FunDep TyVar] -> [FunDep Name]
361 toHsFDs fds = [(map getName ns, map getName ms) | (ns,ms) <- fds]
362 \end{code}
363
364
365 %************************************************************************
366 %*                                                                      *
367 \subsection{Comparison}
368 %*                                                                      *
369 %************************************************************************
370
371 \begin{code}
372 instance Ord a => Eq (HsType a) where
373         -- The Ord is needed because we keep a
374         -- finite map of variables to variables
375    (==) a b = eq_hsType emptyEqHsEnv a b
376
377 instance Ord a => Eq (HsPred a) where
378    (==) a b = eq_hsPred emptyEqHsEnv a b
379
380 eqWithHsTyVars :: Ord name =>
381                   [HsTyVarBndr name] -> [HsTyVarBndr name]
382                -> (EqHsEnv name -> Bool) -> Bool
383 eqWithHsTyVars = eq_hsTyVars emptyEqHsEnv
384 \end{code}
385
386 \begin{code}
387 type EqHsEnv n = FiniteMap n n
388 -- Tracks the mapping from L-variables to R-variables
389
390 eq_hsVar :: Ord n => EqHsEnv n -> n -> n -> Bool
391 eq_hsVar env n1 n2 = case lookupFM env n1 of
392                       Just n1 -> n1 == n2
393                       Nothing -> n1 == n2
394
395 extendEqHsEnv env n1 n2 
396   | n1 == n2  = env
397   | otherwise = addToFM env n1 n2
398
399 emptyEqHsEnv :: EqHsEnv n
400 emptyEqHsEnv = emptyFM
401 \end{code}
402
403 We do define a specialised equality for these \tr{*Type} types; used
404 in checking interfaces.
405
406 \begin{code}
407 -------------------
408 eq_hsTyVars env []          []         k = k env
409 eq_hsTyVars env (tv1:tvs1) (tv2:tvs2)  k = eq_hsTyVar env tv1 tv2 $ \ env ->
410                                            eq_hsTyVars env tvs1 tvs2 k
411 eq_hsTyVars env _ _ _ = False
412
413 eq_hsTyVar env (UserTyVar v1)     (UserTyVar v2)     k = k (extendEqHsEnv env v1 v2)
414 eq_hsTyVar env (IfaceTyVar v1 k1) (IfaceTyVar v2 k2) k = k1 `eqKind` k2 && k (extendEqHsEnv env v1 v2)
415 eq_hsTyVar env _ _ _ = False
416
417 eq_hsVars env []       []       k = k env
418 eq_hsVars env (v1:bs1) (v2:bs2) k = eq_hsVars (extendEqHsEnv env v1 v2) bs1 bs2 k
419 eq_hsVars env _ _ _ = False
420 \end{code}
421
422 \begin{code}
423 -------------------
424 eq_hsTypes env = eqListBy (eq_hsType env)
425
426 -------------------
427 eq_hsType env (HsForAllTy tvs1 c1 t1) (HsForAllTy tvs2 c2 t2)
428   = eq_tvs tvs1 tvs2            $ \env ->
429     eq_hsContext env c1 c2      &&
430     eq_hsType env t1 t2
431   where
432     eq_tvs Nothing     (Just _) k    = False
433     eq_tvs Nothing     Nothing  k    = k env
434     eq_tvs (Just _)    Nothing  k    = False
435     eq_tvs (Just tvs1) (Just tvs2) k = eq_hsTyVars env tvs1 tvs2 k
436
437 eq_hsType env (HsTyVar n1) (HsTyVar n2)
438   = eq_hsVar env n1 n2
439
440 eq_hsType env (HsTupleTy c1 tys1) (HsTupleTy c2 tys2)
441   = (c1 == c2) && eq_hsTypes env tys1 tys2
442
443 eq_hsType env (HsListTy ty1) (HsListTy ty2)
444   = eq_hsType env ty1 ty2
445
446 eq_hsType env (HsAppTy fun_ty1 arg_ty1) (HsAppTy fun_ty2 arg_ty2)
447   = eq_hsType env fun_ty1 fun_ty2 && eq_hsType env arg_ty1 arg_ty2
448
449 eq_hsType env (HsFunTy a1 b1) (HsFunTy a2 b2)
450   = eq_hsType env a1 a2 && eq_hsType env b1 b2
451
452 eq_hsType env (HsPredTy p1) (HsPredTy p2)
453   = eq_hsPred env p1 p2
454
455 eq_hsType env (HsUsageTy u1 ty1) (HsUsageTy u2 ty2)
456   = eq_hsType env u1 u2 && eq_hsType env ty1 ty2
457
458 eq_hsType env (HsOpTy lty1 op1 rty1) (HsOpTy lty2 op2 rty2)
459   = eq_hsVar env op1 op2 && eq_hsType env lty1 lty2 && eq_hsType env rty1 rty2
460
461 eq_hsType env ty1 ty2 = False
462
463
464 -------------------
465 eq_hsContext env a b = eqListBy (eq_hsPred env) a b
466
467 -------------------
468 eq_hsPred env (HsClassP c1 tys1) (HsClassP c2 tys2)
469   = c1 == c2 &&  eq_hsTypes env tys1 tys2
470 eq_hsPred env (HsIParam n1 ty1) (HsIParam n2 ty2)
471   = n1 == n2 && eq_hsType env ty1 ty2
472 eq_hsPred env _ _ = False
473
474 -------------------
475 eqListBy :: (a->a->Bool) -> [a] -> [a] -> Bool
476 eqListBy eq []     []     = True
477 eqListBy eq (x:xs) (y:ys) = eq x y && eqListBy eq xs ys
478 eqListBy eq xs     ys     = False
479 \end{code}