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