[project @ 2000-10-25 07:09:52 by simonpj]
[ghc-hetmet.git] / ghc / compiler / hsSyn / HsDecls.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[HsDecls]{Abstract syntax: global declarations}
5
6 Definitions for: @TyDecl@ and @ConDecl@, @ClassDecl@,
7 @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
8
9 \begin{code}
10 module HsDecls (
11         HsDecl(..), TyClDecl(..), InstDecl(..), RuleDecl(..), RuleBndr(..),
12         DefaultDecl(..), ForeignDecl(..), ForKind(..),
13         ExtName(..), isDynamicExtName, extNameStatic,
14         ConDecl(..), ConDetails(..), 
15         BangType(..), getBangType,
16         DeprecDecl(..), DeprecTxt,
17         hsDeclName, instDeclName, tyClDeclName, tyClDeclNames,
18         isClassDecl, isSynDecl, isDataDecl, countTyClDecls, toHsRule,
19         mkClassDeclSysNames, isIfaceRuleDecl,
20         getClassDeclSysNames
21     ) where
22
23 #include "HsVersions.h"
24
25 -- friends:
26 import HsBinds          ( HsBinds, MonoBinds, Sig(..), FixitySig(..) )
27 import HsExpr           ( HsExpr )
28 import HsTypes
29 import PprCore          ( pprCoreRule )
30 import HsCore           ( UfExpr(UfVar), UfBinder, HsIdInfo, pprHsIdInfo,
31                           eq_ufBinders, eq_ufExpr, pprUfExpr, toUfExpr, toUfBndr
32                         )
33 import CoreSyn          ( CoreRule(..) )
34 import BasicTypes       ( NewOrData(..) )
35 import CallConv         ( CallConv, pprCallConv )
36 import Name             ( getName )
37
38 -- others:
39 import FunDeps          ( pprFundeps )
40 import Class            ( FunDep )
41 import CStrings         ( CLabelString, pprCLabelString )
42 import Outputable       
43 import SrcLoc           ( SrcLoc, noSrcLoc )
44 \end{code}
45
46
47 %************************************************************************
48 %*                                                                      *
49 \subsection[HsDecl]{Declarations}
50 %*                                                                      *
51 %************************************************************************
52
53 \begin{code}
54 data HsDecl name pat
55   = TyClD       (TyClDecl name pat)
56   | InstD       (InstDecl  name pat)
57   | DefD        (DefaultDecl name)
58   | ValD        (HsBinds name pat)
59   | ForD        (ForeignDecl name)
60   | FixD        (FixitySig name)
61   | DeprecD     (DeprecDecl name)
62   | RuleD       (RuleDecl name pat)
63
64 -- NB: all top-level fixity decls are contained EITHER
65 -- EITHER FixDs
66 -- OR     in the ClassDecls in TyClDs
67 --
68 -- The former covers
69 --      a) data constructors
70 --      b) class methods (but they can be also done in the
71 --              signatures of class decls)
72 --      c) imported functions (that have an IfacSig)
73 --      d) top level decls
74 --
75 -- The latter is for class methods only
76 \end{code}
77
78 \begin{code}
79 #ifdef DEBUG
80 hsDeclName :: (Outputable name, Outputable pat)
81            => HsDecl name pat -> name
82 #endif
83 hsDeclName (TyClD decl)                             = tyClDeclName decl
84 hsDeclName (InstD   decl)                           = instDeclName decl
85 hsDeclName (ForD    (ForeignDecl name _ _ _ _ _))   = name
86 hsDeclName (FixD    (FixitySig name _ _))           = name
87 -- Others don't make sense
88 #ifdef DEBUG
89 hsDeclName x                                  = pprPanic "HsDecls.hsDeclName" (ppr x)
90 #endif
91
92
93 instDeclName :: InstDecl name pat -> name
94 instDeclName (InstDecl _ _ _ (Just name) _) = name
95
96 \end{code}
97
98 \begin{code}
99 instance (Outputable name, Outputable pat)
100         => Outputable (HsDecl name pat) where
101
102     ppr (TyClD dcl)  = ppr dcl
103     ppr (ValD binds) = ppr binds
104     ppr (DefD def)   = ppr def
105     ppr (InstD inst) = ppr inst
106     ppr (ForD fd)    = ppr fd
107     ppr (FixD fd)    = ppr fd
108     ppr (RuleD rd)   = ppr rd
109     ppr (DeprecD dd) = ppr dd
110 \end{code}
111
112 \begin{code}
113 instance Ord name => Eq (HsDecl name pat) where
114         -- Used only when comparing interfaces, 
115         -- at which time only signature and type/class decls
116    (TyClD d1) == (TyClD d2) = d1 == d2
117    _          == _          = False
118 \end{code}
119
120
121 %************************************************************************
122 %*                                                                      *
123 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
124 %*                                                                      *
125 %************************************************************************
126
127 Type and class declarations carry 'implicit names'.  In particular:
128
129 Type A.  
130 ~~~~~~~
131   Each data type decl defines 
132         a worker name for each constructor
133         to-T and from-T convertors
134   Each class decl defines
135         a tycon for the class
136         a data constructor for that tycon
137         the worker for that constructor
138         a selector for each superclass
139
140 All have occurrence names that are derived uniquely from their parent declaration.
141
142 None of these get separate definitions in an interface file; they are
143 fully defined by the data or class decl.  But they may *occur* in
144 interface files, of course.  Any such occurrence must haul in the
145 relevant type or class decl.
146
147 Plan of attack:
148  - Make up their occurrence names immediately
149
150  - Ensure they "point to" the parent data/class decl 
151    when loading that decl from an interface file
152
153  - When renaming the decl look them up in the name cache,
154    ensure correct module and provenance is set
155
156 Type B: Default methods and dictionary functions
157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158 Have their own binding in an interface file.
159
160 Default methods : occurrence name is derived uniquely from the class decl.
161 Dict functions  : occurrence name is derived from the instance decl, plus a unique number.
162
163 Plan of attack: 
164   - Do *not* make them point to the parent class decl
165   - Interface-file decls: treat just like Type A
166   - Source-file decls:    the names aren't in the decl at all; 
167                           instead the typechecker makes them up
168
169 \begin{code}
170 data TyClDecl name pat
171   = IfaceSig    name                    -- It may seem odd to classify an interface-file signature
172                 (HsType name)           -- as a 'TyClDecl', but it's very convenient.  These three
173                 [HsIdInfo name]         -- are the kind that appear in interface files.
174                 SrcLoc
175
176   | TyData      NewOrData
177                 (HsContext name) -- context
178                 name             -- type constructor
179                 [HsTyVarBndr name]       -- type variables
180                 [ConDecl name]   -- data constructors (empty if abstract)
181                 Int              -- Number of data constructors (valid even if type is abstract)
182                 (Maybe [name])   -- derivings; Nothing => not specified
183                                  -- (i.e., derive default); Just [] => derive
184                                  -- *nothing*; Just <list> => as you would
185                                  -- expect...
186                 SrcLoc
187                 name             -- generic converter functions
188                 name             -- generic converter functions
189
190   | TySynonym   name                    -- type constructor
191                 [HsTyVarBndr name]      -- type variables
192                 (HsType name)           -- synonym expansion
193                 SrcLoc
194
195   | ClassDecl   (HsContext name)        -- context...
196                 name                    -- name of the class
197                 [HsTyVarBndr name]      -- the class type variables
198                 [FunDep name]           -- functional dependencies
199                 [Sig name]              -- methods' signatures
200                 (MonoBinds name pat)    -- default methods
201                 (ClassDeclSysNames name)
202                 SrcLoc
203
204 tyClDeclName :: TyClDecl name pat -> name
205 tyClDeclName (IfaceSig name _ _ _)           = name
206 tyClDeclName (TyData _ _ name _ _ _ _ _ _ _) = name
207 tyClDeclName (TySynonym name _ _ _)          = name
208 tyClDeclName (ClassDecl _ name _ _ _ _ _ _)  = name
209
210
211 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
212 -- Returns all the binding names of the decl, along with their SrcLocs
213 -- The first one is guaranteed to be the name of the decl
214 -- For record fields, the first one counts as the SrcLoc
215 -- We use the equality to filter out duplicate field names
216
217 tyClDeclNames (TySynonym name _ _ loc)
218   = [(name,loc)]
219
220 tyClDeclNames (ClassDecl _ name _ _ sigs _ _ loc)
221   = (name,loc) : [(name,loc) | ClassOpSig n _ _ loc <- sigs]
222
223 tyClDeclNames (TyData _ _ name _ cons _ _ loc _ _)
224   = (name,loc) : conDeclsNames cons
225
226 tyClDeclNames (IfaceSig _ _ _ _) = []
227
228 type ClassDeclSysNames name = [name]
229         --      [tycon, datacon wrapper, datacon worker, 
230         --       superclass selector 1, ..., superclass selector n]
231         -- They are kept in a list rather than a tuple to make the
232         -- renamer easier.
233
234 mkClassDeclSysNames  :: (name, name, name, [name]) -> [name]
235 getClassDeclSysNames :: [name] -> (name, name, name, [name])
236 mkClassDeclSysNames  (a,b,c,ds) = a:b:c:ds
237 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
238 \end{code}
239
240 \begin{code}
241 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
242
243 isSynDecl (TySynonym _ _ _ _) = True
244 isSynDecl other               = False
245
246 isDataDecl (TyData _ _ _ _ _ _ _ _ _ _) = True
247 isDataDecl other                        = False
248
249 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ ) = True
250 isClassDecl other                        = False
251 \end{code}
252
253 \begin{code}
254 instance Ord name => Eq (TyClDecl name pat) where
255         -- Used only when building interface files
256   (==) (IfaceSig n1 t1 i1 _)
257        (IfaceSig n2 t2 i2 _) = n1==n2 && t1==t2 && i1==i2
258
259   (==) (TyData nd1 cxt1 n1 tvs1 cons1 _ _ _ _ _)
260        (TyData nd2 cxt2 n2 tvs2 cons2 _ _ _ _ _)
261     = n1 == n2 &&
262       nd1 == nd2 &&
263       eqWithHsTyVars tvs1 tvs2 (\ env -> 
264           eq_hsContext env cxt1 cxt2  &&
265           eqListBy (eq_ConDecl env) cons1 cons2
266       )
267
268   (==) (TySynonym n1 tvs1 ty1 _)
269        (TySynonym n2 tvs2 ty2 _)
270     =  n1 == n2 &&
271        eqWithHsTyVars tvs1 tvs2 (\ env -> eq_hsType env ty1 ty2)
272
273   (==) (ClassDecl cxt1 n1 tvs1 fds1 sigs1 _ _ _ )
274        (ClassDecl cxt2 n2 tvs2 fds2 sigs2 _ _ _ )
275     =  n1 == n2 &&
276        eqWithHsTyVars tvs1 tvs2 (\ env -> 
277           eq_hsContext env cxt1 cxt2 &&
278           eqListBy (eq_hsFD env) fds1 fds2 &&
279           eqListBy (eq_cls_sig env) sigs1 sigs2
280        )
281
282   (==) _ _ = False      -- default case
283
284
285 eq_hsFD env (ns1,ms1) (ns2,ms2)
286   = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
287
288 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
289   = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
290   where
291         -- Ignore the name of the default method.
292         -- This is used for comparing declarations before putting
293         -- them into interface files, and the name of the default 
294         -- method isn't relevant
295     (Just (explicit_dm1)) `eq_dm` (Just (explicit_dm2)) = explicit_dm1 == explicit_dm2
296     Nothing                 `eq_dm` Nothing                 = True
297     dm1                     `eq_dm` dm2                     = False
298 \end{code}
299
300 \begin{code}
301 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int, Int)
302         -- class, data, newtype, synonym decls
303 countTyClDecls decls 
304  = (length [() | ClassDecl _ _ _ _ _ _ _ _         <- decls],
305     length [() | TyData DataType _ _ _ _ _ _ _ _ _ <- decls],
306     length [() | TyData NewType  _ _ _ _ _ _ _ _ _ <- decls],
307     length [() | TySynonym _ _ _ _                 <- decls],
308     length [() | IfaceSig _ _ _ _                  <- decls])
309 \end{code}
310
311 \begin{code}
312 instance (Outputable name, Outputable pat)
313               => Outputable (TyClDecl name pat) where
314
315     ppr (IfaceSig var ty info _) = hsep [ppr var, dcolon, ppr ty, pprHsIdInfo info]
316
317     ppr (TySynonym tycon tyvars mono_ty src_loc)
318       = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
319              4 (ppr mono_ty)
320
321     ppr (TyData new_or_data context tycon tyvars condecls ncons 
322                 derivings src_loc gen_conv1 gen_conv2) -- The generic names are not printed out ATM
323       = pp_tydecl
324                   (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
325                   (pp_condecls condecls ncons)
326                   derivings
327       where
328         keyword = case new_or_data of
329                         NewType  -> SLIT("newtype")
330                         DataType -> SLIT("data")
331
332     ppr (ClassDecl context clas tyvars fds sigs methods _ src_loc)
333       | null sigs       -- No "where" part
334       = top_matter
335
336       | otherwise       -- Laid out
337       = sep [hsep [top_matter, ptext SLIT("where {")],
338              nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
339       where
340         top_matter  = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
341         ppr_sig sig = ppr sig <> semi
342         pp_methods = getPprStyle $ \ sty ->
343                      if ifaceStyle sty then empty else ppr methods
344         
345 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
346 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
347
348 pp_condecls []     ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
349 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
350
351 pp_tydecl pp_head pp_decl_rhs derivings
352   = hang pp_head 4 (sep [
353         pp_decl_rhs,
354         case derivings of
355           Nothing          -> empty
356           Just ds          -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
357     ])
358 \end{code}
359
360
361 %************************************************************************
362 %*                                                                      *
363 \subsection[ConDecl]{A data-constructor declaration}
364 %*                                                                      *
365 %************************************************************************
366
367 \begin{code}
368 data ConDecl name
369   = ConDecl     name                    -- Constructor name; this is used for the
370                                         -- DataCon itself, and for the user-callable wrapper Id
371
372                 name                    -- Name of the constructor's 'worker Id'
373                                         -- Filled in as the ConDecl is built
374
375                 [HsTyVarBndr name]      -- Existentially quantified type variables
376                 (HsContext name)        -- ...and context
377                                         -- If both are empty then there are no existentials
378
379                 (ConDetails name)
380                 SrcLoc
381
382 data ConDetails name
383   = VanillaCon                  -- prefix-style con decl
384                 [BangType name]
385
386   | InfixCon                    -- infix-style con decl
387                 (BangType name)
388                 (BangType name)
389
390   | RecCon                      -- record-style con decl
391                 [([name], BangType name)]       -- list of "fields"
392 \end{code}
393
394 \begin{code}
395 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
396   -- See tyClDeclNames for what this does
397   -- The function is boringly complicated because of the records
398   -- And since we only have equality, we have to be a little careful
399 conDeclsNames cons
400   = snd (foldl do_one ([], []) cons)
401   where
402     do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
403         = do_details ((name,loc):acc) details
404         where
405           do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
406           do_details acc other         = (flds_seen, acc)
407
408           do_fld acc (flds, _) = foldl do_fld1 acc flds
409
410           do_fld1 (flds_seen, acc) fld
411                 | fld `elem` flds_seen = (flds_seen,acc)
412                 | otherwise            = (fld:flds_seen, (fld,loc):acc)
413 \end{code}
414
415 \begin{code}
416 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
417                (ConDecl n2 _ tvs2 cxt2 cds2 _)
418   = n1 == n2 &&
419     (eqWithHsTyVars tvs1 tvs2   $ \ env ->
420      eq_hsContext env cxt1 cxt2 &&
421      eq_ConDetails env cds1 cds2)
422
423 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
424   = eqListBy (eq_btype env) bts1 bts2
425 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
426   = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
427 eq_ConDetails env (RecCon fs1) (RecCon fs2)
428   = eqListBy (eq_fld env) fs1 fs2
429 eq_ConDetails env _ _ = False
430
431 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
432 \end{code}
433   
434 \begin{code}
435 data BangType name
436   = Banged   (HsType name)      -- HsType: to allow Haskell extensions
437   | Unbanged (HsType name)      -- (MonoType only needed for straight Haskell)
438   | Unpacked (HsType name)      -- Field is strict and to be unpacked if poss.
439
440 getBangType (Banged ty)   = ty
441 getBangType (Unbanged ty) = ty
442 getBangType (Unpacked ty) = ty
443
444 eq_btype env (Banged t1)   (Banged t2)   = eq_hsType env t1 t2
445 eq_btype env (Unbanged t1) (Unbanged t2) = eq_hsType env t1 t2
446 eq_btype env (Unpacked t1) (Unpacked t2) = eq_hsType env t1 t2
447 eq_btype env _             _             = False
448 \end{code}
449
450 \begin{code}
451 instance (Outputable name) => Outputable (ConDecl name) where
452     ppr (ConDecl con _ tvs cxt con_details  loc)
453       = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
454
455 ppr_con_details con (InfixCon ty1 ty2)
456   = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
457
458 ppr_con_details con (VanillaCon tys)
459   = ppr con <+> hsep (map (ppr_bang) tys)
460
461 ppr_con_details con (RecCon fields)
462   = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
463   where
464     ppr_field (ns, ty) = hsep (map (ppr) ns) <+> 
465                          dcolon <+>
466                          ppr_bang ty
467
468 instance Outputable name => Outputable (BangType name) where
469     ppr = ppr_bang
470
471 ppr_bang (Banged   ty) = ptext SLIT("!") <> pprParendHsType ty
472 ppr_bang (Unbanged ty) = pprParendHsType ty
473 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
474 \end{code}
475
476
477 %************************************************************************
478 %*                                                                      *
479 \subsection[InstDecl]{An instance declaration
480 %*                                                                      *
481 %************************************************************************
482
483 \begin{code}
484 data InstDecl name pat
485   = InstDecl    (HsType name)   -- Context => Class Instance-type
486                                 -- Using a polytype means that the renamer conveniently
487                                 -- figures out the quantified type variables for us.
488
489                 (MonoBinds name pat)
490
491                 [Sig name]              -- User-supplied pragmatic info
492
493                 (Maybe name)            -- Name for the dictionary function
494                                         -- Nothing for source-file instance decls
495
496                 SrcLoc
497 \end{code}
498
499 \begin{code}
500 instance (Outputable name, Outputable pat)
501               => Outputable (InstDecl name pat) where
502
503     ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
504       = getPprStyle $ \ sty ->
505         if ifaceStyle sty then
506            hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
507         else
508            vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
509                  nest 4 (ppr uprags),
510                  nest 4 (ppr binds) ]
511       where
512         pp_dfun = case maybe_dfun_name of
513                     Just df -> ppr df
514                     Nothing -> empty
515 \end{code}
516
517 \begin{code}
518 instance Ord name => Eq (InstDecl name pat) where
519         -- Used for interface comparison only, so don't compare bindings
520   (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
521        = inst_ty1 == inst_ty2 && dfun1 == dfun2
522 \end{code}
523
524
525 %************************************************************************
526 %*                                                                      *
527 \subsection[DefaultDecl]{A @default@ declaration}
528 %*                                                                      *
529 %************************************************************************
530
531 There can only be one default declaration per module, but it is hard
532 for the parser to check that; we pass them all through in the abstract
533 syntax, and that restriction must be checked in the front end.
534
535 \begin{code}
536 data DefaultDecl name
537   = DefaultDecl [HsType name]
538                 SrcLoc
539
540 instance (Outputable name)
541               => Outputable (DefaultDecl name) where
542
543     ppr (DefaultDecl tys src_loc)
544       = ptext SLIT("default") <+> parens (interpp'SP tys)
545 \end{code}
546
547 %************************************************************************
548 %*                                                                      *
549 \subsection{Foreign function interface declaration}
550 %*                                                                      *
551 %************************************************************************
552
553 \begin{code}
554 data ForeignDecl name = 
555    ForeignDecl 
556         name 
557         ForKind   
558         (HsType name)
559         ExtName
560         CallConv
561         SrcLoc
562
563 instance (Outputable name)
564               => Outputable (ForeignDecl name) where
565
566     ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
567       = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+> 
568         ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
569         where
570          (ppr_imp_exp, ppr_unsafe) =
571            case imp_exp of
572              FoLabel     -> (ptext SLIT("label"), empty)
573              FoExport    -> (ptext SLIT("export"), empty)
574              FoImport us 
575                 | us        -> (ptext SLIT("import"), ptext SLIT("unsafe"))
576                 | otherwise -> (ptext SLIT("import"), empty)
577
578 data ForKind
579  = FoLabel
580  | FoExport
581  | FoImport Bool -- True  => unsafe call.
582
583 data ExtName
584  = Dynamic 
585  | ExtName CLabelString         -- The external name of the foreign thing,
586            (Maybe CLabelString) -- and optionally its DLL or module name
587                                 -- Both of these are completely unencoded; 
588                                 -- we just print them as they are
589
590 isDynamicExtName :: ExtName -> Bool
591 isDynamicExtName Dynamic = True
592 isDynamicExtName _       = False
593
594 extNameStatic :: ExtName -> CLabelString
595 extNameStatic (ExtName f _) = f
596 extNameStatic Dynamic       = panic "staticExtName: Dynamic - shouldn't ever happen."
597
598 instance Outputable ExtName where
599   ppr Dynamic      = ptext SLIT("dynamic")
600   ppr (ExtName nm mb_mod) = 
601      case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+> 
602      doubleQuotes (pprCLabelString nm)
603 \end{code}
604
605 %************************************************************************
606 %*                                                                      *
607 \subsection{Transformation rules}
608 %*                                                                      *
609 %************************************************************************
610
611 \begin{code}
612 data RuleDecl name pat
613   = HsRule                      -- Source rule
614         FAST_STRING             -- Rule name
615         [name]                  -- Forall'd tyvars, filled in by the renamer with
616                                 -- tyvars mentioned in sigs; then filled out by typechecker
617         [RuleBndr name]         -- Forall'd term vars
618         (HsExpr name pat)       -- LHS
619         (HsExpr name pat)       -- RHS
620         SrcLoc          
621
622   | IfaceRule                   -- One that's come in from an interface file; pre-typecheck
623         FAST_STRING
624         [UfBinder name]         -- Tyvars and term vars
625         name                    -- Head of lhs
626         [UfExpr name]           -- Args of LHS
627         (UfExpr name)           -- Pre typecheck
628         SrcLoc          
629
630   | IfaceRuleOut                -- Post typecheck
631         name                    -- Head of LHS
632         CoreRule
633
634 isIfaceRuleDecl (HsRule _ _ _ _ _ _) = False
635 isIfaceRuleDecl other                = True
636
637 data RuleBndr name
638   = RuleBndr name
639   | RuleBndrSig name (HsType name)
640
641 instance Ord name => Eq (RuleDecl name pat) where
642   -- Works for IfaceRules only; used when comparing interface file versions
643   (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
644      = n1==n2 && f1 == f2 && 
645        eq_ufBinders emptyEqHsEnv bs1 bs2 (\env -> 
646        eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
647
648 instance (Outputable name, Outputable pat)
649               => Outputable (RuleDecl name pat) where
650   ppr (HsRule name tvs ns lhs rhs loc)
651         = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
652                pp_forall, ppr lhs, equals <+> ppr rhs,
653                text "#-}" ]
654         where
655           pp_forall | null tvs && null ns = empty
656                     | otherwise           = text "forall" <+> 
657                                             fsep (map ppr tvs ++ map ppr ns)
658                                             <> dot
659
660   ppr (IfaceRule name tpl_vars fn tpl_args rhs loc) 
661     = hsep [ doubleQuotes (ptext name),
662            ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
663            ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
664            ptext SLIT("=") <+> ppr rhs
665       ] <+> semi
666
667   ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
668
669 instance Outputable name => Outputable (RuleBndr name) where
670    ppr (RuleBndr name) = ppr name
671    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
672
673 toHsRule id (BuiltinRule _)
674   = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
675
676 toHsRule id (Rule name bndrs args rhs)
677   = IfaceRule name (map toUfBndr bndrs) (getName id)
678               (map toUfExpr args) (toUfExpr rhs) noSrcLoc
679
680 bogusIfaceRule id
681   = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
682 \end{code}
683
684
685 %************************************************************************
686 %*                                                                      *
687 \subsection[DeprecDecl]{Deprecations}
688 %*                                                                      *
689 %************************************************************************
690
691 We use exported entities for things to deprecate.
692
693 \begin{code}
694 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
695
696 type DeprecTxt = FAST_STRING    -- reason/explanation for deprecation
697
698 instance Outputable name => Outputable (DeprecDecl name) where
699     ppr (Deprecation thing txt _)
700       = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
701 \end{code}