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