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