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