[project @ 2001-05-18 08:46:18 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 @oCnDecl@, @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, getBangStrictness, unbangedType,
16         DeprecDecl(..), DeprecTxt,
17         hsDeclName, instDeclName, tyClDeclName, tyClDeclNames, tyClDeclSysNames,
18         isClassDecl, isSynDecl, isDataDecl, isIfaceSigDecl, countTyClDecls,
19         mkClassDeclSysNames, isIfaceRuleDecl, ifaceRuleDeclName,
20         getClassDeclSysNames, conDetailsTys
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, UfBinder, HsIdInfo, pprHsIdInfo,
31                           eq_ufBinders, eq_ufExpr, pprUfExpr 
32                         )
33 import CoreSyn          ( CoreRule(..) )
34 import BasicTypes       ( NewOrData(..) )
35 import Demand           ( StrictnessMark(..) )
36 import CallConv         ( CallConv, pprCallConv )
37
38 -- others:
39 import Name             ( NamedThing )
40 import FunDeps          ( pprFundeps )
41 import Class            ( FunDep, DefMeth(..) )
42 import CStrings         ( CLabelString, pprCLabelString )
43 import Outputable       
44 import SrcLoc           ( SrcLoc )
45 \end{code}
46
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection[HsDecl]{Declarations}
51 %*                                                                      *
52 %************************************************************************
53
54 \begin{code}
55 data HsDecl name pat
56   = TyClD       (TyClDecl name pat)
57   | InstD       (InstDecl  name pat)
58   | DefD        (DefaultDecl name)
59   | ValD        (HsBinds name pat)
60   | ForD        (ForeignDecl name)
61   | FixD        (FixitySig name)
62   | DeprecD     (DeprecDecl name)
63   | RuleD       (RuleDecl name pat)
64
65 -- NB: all top-level fixity decls are contained EITHER
66 -- EITHER FixDs
67 -- OR     in the ClassDecls in TyClDs
68 --
69 -- The former covers
70 --      a) data constructors
71 --      b) class methods (but they can be also done in the
72 --              signatures of class decls)
73 --      c) imported functions (that have an IfacSig)
74 --      d) top level decls
75 --
76 -- The latter is for class methods only
77 \end{code}
78
79 \begin{code}
80 #ifdef DEBUG
81 hsDeclName :: (NamedThing name, Outputable name, Outputable pat)
82            => HsDecl name pat -> name
83 #endif
84 hsDeclName (TyClD decl)                             = tyClDeclName decl
85 hsDeclName (InstD   decl)                           = instDeclName decl
86 hsDeclName (ForD    (ForeignDecl name _ _ _ _ _))   = name
87 hsDeclName (FixD    (FixitySig name _ _))           = name
88 -- Others don't make sense
89 #ifdef DEBUG
90 hsDeclName x                                  = pprPanic "HsDecls.hsDeclName" (ppr x)
91 #endif
92
93
94 instDeclName :: InstDecl name pat -> name
95 instDeclName (InstDecl _ _ _ (Just name) _) = name
96
97 \end{code}
98
99 \begin{code}
100 instance (NamedThing name, Outputable name, Outputable pat)
101         => Outputable (HsDecl name pat) where
102
103     ppr (TyClD dcl)  = ppr dcl
104     ppr (ValD binds) = ppr binds
105     ppr (DefD def)   = ppr def
106     ppr (InstD inst) = ppr inst
107     ppr (ForD fd)    = ppr fd
108     ppr (FixD fd)    = ppr fd
109     ppr (RuleD rd)   = ppr rd
110     ppr (DeprecD dd) = ppr dd
111 \end{code}
112
113
114 %************************************************************************
115 %*                                                                      *
116 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
117 %*                                                                      *
118 %************************************************************************
119
120                 --------------------------------
121                         THE NAMING STORY
122                 --------------------------------
123
124 Here is the story about the implicit names that go with type, class, and instance
125 decls.  It's a bit tricky, so pay attention!
126
127 "Implicit" (or "system") binders
128 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
129   Each data type decl defines 
130         a worker name for each constructor
131         to-T and from-T convertors
132   Each class decl defines
133         a tycon for the class
134         a data constructor for that tycon
135         the worker for that constructor
136         a selector for each superclass
137
138 All have occurrence names that are derived uniquely from their parent declaration.
139
140 None of these get separate definitions in an interface file; they are
141 fully defined by the data or class decl.  But they may *occur* in
142 interface files, of course.  Any such occurrence must haul in the
143 relevant type or class decl.
144
145 Plan of attack:
146  - Make up their occurrence names immediately
147    This is done in RdrHsSyn.mkClassDecl, mkTyDecl, mkConDecl
148
149  - Ensure they "point to" the parent data/class decl 
150    when loading that decl from an interface file
151    (See RnHiFiles.getTyClDeclSysNames)
152
153  - When renaming the decl look them up in the name cache,
154    ensure correct module and provenance is set
155
156 Default methods
157 ~~~~~~~~~~~~~~~
158  - Occurrence name is derived uniquely from the method name
159    E.g. $dmmax
160
161  - If there is a default method name at all, it's recorded in
162    the ClassOpSig (in HsBinds), in the DefMeth field.
163    (DefMeth is defined in Class.lhs)
164
165 Source-code class decls and interface-code class decls are treated subtly
166 differently, which has given me a great deal of confusion over the years.
167 Here's the deal.  (We distinguish the two cases because source-code decls
168 have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.
169
170 In *source-code* class declarations:
171  - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
172    This is done by RdrHsSyn.mkClassOpSigDM
173
174  - The renamer renames it to a Name
175
176  - During typechecking, we generate a binding for each $dm for 
177    which there's a programmer-supplied default method:
178         class Foo a where
179           op1 :: <type>
180           op2 :: <type>
181           op1 = ...
182    We generate a binding for $dmop1 but not for $dmop2.
183    The Class for Foo has a NoDefMeth for op2 and a DefMeth for op1.
184    The Name for $dmop2 is simply discarded.
185
186 In *interface-file* class declarations:
187   - When parsing, we see if there's an explicit programmer-supplied default method
188     because there's an '=' sign to indicate it:
189         class Foo a where
190           op1 = :: <type>       -- NB the '='
191           op2   :: <type>
192     We use this info to generate a DefMeth with a suitable RdrName for op1,
193     and a NoDefMeth for op2
194   - The interface file has a separate definition for $dmop1, with unfolding etc.
195   - The renamer renames it to a Name.
196   - The renamer treats $dmop1 as a free variable of the declaration, so that
197     the binding for $dmop1 will be sucked in.  (See RnHsSyn.tyClDeclFVs)  
198     This doesn't happen for source code class decls, because they *bind* the default method.
199
200 Dictionary functions
201 ~~~~~~~~~~~~~~~~~~~~
202 Each instance declaration gives rise to one dictionary function binding.
203
204 The type checker makes up new source-code instance declarations
205 (e.g. from 'deriving' or generic default methods --- see
206 TcInstDcls.tcInstDecls1).  So we can't generate the names for
207 dictionary functions in advance (we don't know how many we need).
208
209 On the other hand for interface-file instance declarations, the decl
210 specifies the name of the dictionary function, and it has a binding elsewhere
211 in the interface file:
212         instance {Eq Int} = dEqInt
213         dEqInt :: {Eq Int} <pragma info>
214
215 So again we treat source code and interface file code slightly differently.
216
217 Source code:
218   - Source code instance decls have a Nothing in the (Maybe name) field
219     (see data InstDecl below)
220
221   - The typechecker makes up a Local name for the dict fun for any source-code
222     instance decl, whether it comes from a source-code instance decl, or whether
223     the instance decl is derived from some other construct (e.g. 'deriving').
224
225   - The occurrence name it chooses is derived from the instance decl (just for 
226     documentation really) --- e.g. dNumInt.  Two dict funs may share a common
227     occurrence name, but will have different uniques.  E.g.
228         instance Foo [Int]  where ...
229         instance Foo [Bool] where ...
230     These might both be dFooList
231
232   - The CoreTidy phase globalises the name, and ensures the occurrence name is
233     unique (this isn't special to dict funs).  So we'd get dFooList and dFooList1.
234
235   - We can take this relaxed approach (changing the occurrence name later) 
236     because dict fun Ids are not captured in a TyCon or Class (unlike default
237     methods, say).  Instead, they are kept separately in the InstEnv.  This
238     makes it easy to adjust them after compiling a module.  (Once we've finished
239     compiling that module, they don't change any more.)
240
241
242 Interface file code:
243   - The instance decl gives the dict fun name, so the InstDecl has a (Just name)
244     in the (Maybe name) field.
245
246   - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
247     suck in the dfun binding
248
249
250 \begin{code}
251 data TyClDecl name pat
252   = IfaceSig {  tcdName :: name,                -- It may seem odd to classify an interface-file signature
253                 tcdType :: HsType name,         -- as a 'TyClDecl', but it's very convenient.  These three
254                 tcdIdInfo :: [HsIdInfo name],   -- are the kind that appear in interface files.
255                 tcdLoc :: SrcLoc
256     }
257
258   | TyData {    tcdND     :: NewOrData,
259                 tcdCtxt   :: HsContext name,     -- context
260                 tcdName   :: name,               -- type constructor
261                 tcdTyVars :: [HsTyVarBndr name], -- type variables
262                 tcdCons   :: [ConDecl name],     -- data constructors (empty if abstract)
263                 tcdNCons  :: Int,                -- Number of data constructors (valid even if type is abstract)
264                 tcdDerivs :: Maybe [name],       -- derivings; Nothing => not specified
265                                  -- (i.e., derive default); Just [] => derive
266                                  -- *nothing*; Just <list> => as you would
267                                  -- expect...
268                 tcdSysNames :: DataSysNames name,       -- Generic converter functions
269                 tcdLoc      :: SrcLoc
270     }
271
272   | TySynonym { tcdName :: name,                        -- type constructor
273                 tcdTyVars :: [HsTyVarBndr name],        -- type variables
274                 tcdSynRhs :: HsType name,               -- synonym expansion
275                 tcdLoc    :: SrcLoc
276     }
277
278   | ClassDecl { tcdCtxt    :: HsContext name,           -- Context...
279                 tcdName    :: name,                     -- Name of the class
280                 tcdTyVars  :: [HsTyVarBndr name],       -- The class type variables
281                 tcdFDs     :: [FunDep name],            -- Functional dependencies
282                 tcdSigs    :: [Sig name],               -- Methods' signatures
283                 tcdMeths   :: Maybe (MonoBinds name pat),       -- Default methods
284                                                                 -- Nothing for imported class decls
285                                                                 -- Just bs for source   class decls
286                 tcdSysNames :: ClassSysNames name,
287                 tcdLoc      :: SrcLoc
288     }
289 \end{code}
290
291 Simple classifiers
292
293 \begin{code}
294 isIfaceSigDecl, isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
295
296 isIfaceSigDecl (IfaceSig {}) = True
297 isIfaceSigDecl other         = False
298
299 isSynDecl (TySynonym {}) = True
300 isSynDecl other          = False
301
302 isDataDecl (TyData {}) = True
303 isDataDecl other       = False
304
305 isClassDecl (ClassDecl {}) = True
306 isClassDecl other          = False
307 \end{code}
308
309 Dealing with names
310
311 \begin{code}
312 --------------------------------
313 tyClDeclName :: TyClDecl name pat -> name
314 tyClDeclName tycl_decl = tcdName tycl_decl
315
316 --------------------------------
317 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
318 -- Returns all the *binding* names of the decl, along with their SrcLocs
319 -- The first one is guaranteed to be the name of the decl
320 -- For record fields, the first one counts as the SrcLoc
321 -- We use the equality to filter out duplicate field names
322
323 tyClDeclNames (TySynonym {tcdName = name, tcdLoc = loc})  = [(name,loc)]
324 tyClDeclNames (IfaceSig  {tcdName = name, tcdLoc = loc})  = [(name,loc)]
325
326 tyClDeclNames (ClassDecl {tcdName = cls_name, tcdSigs = sigs, tcdLoc = loc})
327   = (cls_name,loc) : [(n,loc) | ClassOpSig n _ _ loc <- sigs]
328
329 tyClDeclNames (TyData {tcdName = tc_name, tcdCons = cons, tcdLoc = loc})
330   = (tc_name,loc) : conDeclsNames cons
331
332
333 --------------------------------
334 -- The "system names" are extra implicit names *bound* by the decl.
335 -- They are kept in a list rather than a tuple 
336 -- to make the renamer easier.
337
338 type ClassSysNames name = [name]
339 -- For class decls they are:
340 --      [tycon, datacon wrapper, datacon worker, 
341 --       superclass selector 1, ..., superclass selector n]
342
343 type DataSysNames name =  [name]
344 -- For data decls they are
345 --      [from, to]
346 -- where from :: T -> Tring
347 --       to   :: Tring -> T
348
349 tyClDeclSysNames :: TyClDecl name pat -> [(name, SrcLoc)]
350 -- Similar to tyClDeclNames, but returns the "implicit" 
351 -- or "system" names of the declaration
352
353 tyClDeclSysNames (ClassDecl {tcdSysNames = names, tcdLoc = loc})
354   = [(n,loc) | n <- names]
355 tyClDeclSysNames (TyData {tcdCons = cons, tcdSysNames = names, tcdLoc = loc})
356   = [(n,loc) | n <- names] ++ 
357     [(wkr_name,loc) | ConDecl _ wkr_name _ _ _ loc <- cons]
358 tyClDeclSysNames decl = []
359
360
361 mkClassDeclSysNames  :: (name, name, name, [name]) -> [name]
362 getClassDeclSysNames :: [name] -> (name, name, name, [name])
363 mkClassDeclSysNames  (a,b,c,ds) = a:b:c:ds
364 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
365 \end{code}
366
367 \begin{code}
368 instance (NamedThing name, Ord name) => Eq (TyClDecl name pat) where
369         -- Used only when building interface files
370   (==) d1@(IfaceSig {}) d2@(IfaceSig {})
371       = tcdName d1 == tcdName d2 && 
372         tcdType d1 == tcdType d2 && 
373         tcdIdInfo d1 == tcdIdInfo d2
374
375   (==) d1@(TyData {}) d2@(TyData {})
376       = tcdName d1 == tcdName d2 && 
377         tcdND d1   == tcdND   d2 && 
378         eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
379           eq_hsContext env (tcdCtxt d1) (tcdCtxt d2)  &&
380           eqListBy (eq_ConDecl env) (tcdCons d1) (tcdCons d2)
381         )
382
383   (==) d1@(TySynonym {}) d2@(TySynonym {})
384       = tcdName d1 == tcdName d2 && 
385         eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
386           eq_hsType env (tcdSynRhs d1) (tcdSynRhs d2)
387         )
388
389   (==) d1@(ClassDecl {}) d2@(ClassDecl {})
390     = tcdName d1 == tcdName d2 && 
391       eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
392           eq_hsContext env (tcdCtxt d1) (tcdCtxt d2)  &&
393           eqListBy (eq_hsFD env) (tcdFDs d1) (tcdFDs d2) &&
394           eqListBy (eq_cls_sig env) (tcdSigs d1) (tcdSigs d2)
395        )
396
397   (==) _ _ = False      -- default case
398
399 eq_hsFD env (ns1,ms1) (ns2,ms2)
400   = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
401
402 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
403   = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
404   where
405         -- Ignore the name of the default method for (DefMeth id)
406         -- This is used for comparing declarations before putting
407         -- them into interface files, and the name of the default 
408         -- method isn't relevant
409     NoDefMeth  `eq_dm` NoDefMeth  = True
410     GenDefMeth `eq_dm` GenDefMeth = True
411     DefMeth _  `eq_dm` DefMeth _  = True
412     dm1        `eq_dm` dm2        = False
413
414     
415 \end{code}
416
417 \begin{code}
418 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int, Int)
419         -- class, data, newtype, synonym decls
420 countTyClDecls decls 
421  = (length [() | ClassDecl {} <- decls],
422     length [() | TySynonym {} <- decls],
423     length [() | IfaceSig  {} <- decls],
424     length [() | TyData {tcdND = DataType} <- decls],
425     length [() | TyData {tcdND = NewType} <- decls])
426 \end{code}
427
428 \begin{code}
429 instance (NamedThing name, Outputable name, Outputable pat)
430               => Outputable (TyClDecl name pat) where
431
432     ppr (IfaceSig {tcdName = var, tcdType = ty, tcdIdInfo = info})
433         = hsep [ppr var, dcolon, ppr ty, pprHsIdInfo info]
434
435     ppr (TySynonym {tcdName = tycon, tcdTyVars = tyvars, tcdSynRhs = mono_ty})
436       = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
437              4 (ppr mono_ty)
438
439     ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdName = tycon,
440                  tcdTyVars = tyvars, tcdCons = condecls, tcdNCons = ncons,
441                  tcdDerivs = derivings})
442       = pp_tydecl (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
443                   (pp_condecls condecls ncons)
444                   derivings
445       where
446         keyword = case new_or_data of
447                         NewType  -> SLIT("newtype")
448                         DataType -> SLIT("data")
449
450     ppr (ClassDecl {tcdCtxt = context, tcdName = clas, tcdTyVars = tyvars, tcdFDs = fds,
451                     tcdSigs = sigs, tcdMeths = methods})
452       | null sigs       -- No "where" part
453       = top_matter
454
455       | otherwise       -- Laid out
456       = sep [hsep [top_matter, ptext SLIT("where {")],
457              nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
458       where
459         top_matter  = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
460         ppr_sig sig = ppr sig <> semi
461         pp_methods = getPprStyle $ \ sty ->
462                      if ifaceStyle sty then empty else ppr methods
463         
464 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
465 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
466
467 pp_condecls []     ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
468 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
469
470 pp_tydecl pp_head pp_decl_rhs derivings
471   = hang pp_head 4 (sep [
472         pp_decl_rhs,
473         case derivings of
474           Nothing          -> empty
475           Just ds          -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
476     ])
477 \end{code}
478
479
480 %************************************************************************
481 %*                                                                      *
482 \subsection[ConDecl]{A data-constructor declaration}
483 %*                                                                      *
484 %************************************************************************
485
486 \begin{code}
487 data ConDecl name
488   = ConDecl     name                    -- Constructor name; this is used for the
489                                         -- DataCon itself, and for the user-callable wrapper Id
490
491                 name                    -- Name of the constructor's 'worker Id'
492                                         -- Filled in as the ConDecl is built
493
494                 [HsTyVarBndr name]      -- Existentially quantified type variables
495                 (HsContext name)        -- ...and context
496                                         -- If both are empty then there are no existentials
497
498                 (ConDetails name)
499                 SrcLoc
500
501 data ConDetails name
502   = VanillaCon                  -- prefix-style con decl
503                 [BangType name]
504
505   | InfixCon                    -- infix-style con decl
506                 (BangType name)
507                 (BangType name)
508
509   | RecCon                      -- record-style con decl
510                 [([name], BangType name)]       -- list of "fields"
511 \end{code}
512
513 \begin{code}
514 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
515   -- See tyClDeclNames for what this does
516   -- The function is boringly complicated because of the records
517   -- And since we only have equality, we have to be a little careful
518 conDeclsNames cons
519   = snd (foldl do_one ([], []) cons)
520   where
521     do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
522         = do_details ((name,loc):acc) details
523         where
524           do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
525           do_details acc other         = (flds_seen, acc)
526
527           do_fld acc (flds, _) = foldl do_fld1 acc flds
528
529           do_fld1 (flds_seen, acc) fld
530                 | fld `elem` flds_seen = (flds_seen,acc)
531                 | otherwise            = (fld:flds_seen, (fld,loc):acc)
532 \end{code}
533
534 \begin{code}
535 conDetailsTys :: ConDetails name -> [HsType name]
536 conDetailsTys (VanillaCon btys)    = map getBangType btys
537 conDetailsTys (InfixCon bty1 bty2) = [getBangType bty1, getBangType bty2]
538 conDetailsTys (RecCon fields)      = [getBangType bty | (_, bty) <- fields]
539
540
541 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
542                (ConDecl n2 _ tvs2 cxt2 cds2 _)
543   = n1 == n2 &&
544     (eq_hsTyVars env tvs1 tvs2  $ \ env ->
545      eq_hsContext env cxt1 cxt2 &&
546      eq_ConDetails env cds1 cds2)
547
548 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
549   = eqListBy (eq_btype env) bts1 bts2
550 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
551   = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
552 eq_ConDetails env (RecCon fs1) (RecCon fs2)
553   = eqListBy (eq_fld env) fs1 fs2
554 eq_ConDetails env _ _ = False
555
556 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
557 \end{code}
558   
559 \begin{code}
560 data BangType name = BangType StrictnessMark (HsType name)
561
562 getBangType       (BangType _ ty) = ty
563 getBangStrictness (BangType s _)  = s
564
565 unbangedType ty = BangType NotMarkedStrict ty
566
567 eq_btype env (BangType s1 t1) (BangType s2 t2) = s1==s2 && eq_hsType env t1 t2
568 \end{code}
569
570 \begin{code}
571 instance (Outputable name) => Outputable (ConDecl name) where
572     ppr (ConDecl con _ tvs cxt con_details  loc)
573       = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
574
575 ppr_con_details con (InfixCon ty1 ty2)
576   = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
577
578 ppr_con_details con (VanillaCon tys)
579   = ppr con <+> hsep (map (ppr_bang) tys)
580
581 ppr_con_details con (RecCon fields)
582   = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
583   where
584     ppr_field (ns, ty) = hsep (map (ppr) ns) <+> 
585                          dcolon <+>
586                          ppr_bang ty
587
588 instance Outputable name => Outputable (BangType name) where
589     ppr = ppr_bang
590
591 ppr_bang (BangType s ty) = ppr s <> pprParendHsType ty
592 \end{code}
593
594
595 %************************************************************************
596 %*                                                                      *
597 \subsection[InstDecl]{An instance declaration
598 %*                                                                      *
599 %************************************************************************
600
601 \begin{code}
602 data InstDecl name pat
603   = InstDecl    (HsType name)   -- Context => Class Instance-type
604                                 -- Using a polytype means that the renamer conveniently
605                                 -- figures out the quantified type variables for us.
606
607                 (MonoBinds name pat)
608
609                 [Sig name]              -- User-supplied pragmatic info
610
611                 (Maybe name)            -- Name for the dictionary function
612                                         -- Nothing for source-file instance decls
613
614                 SrcLoc
615 \end{code}
616
617 \begin{code}
618 instance (Outputable name, Outputable pat)
619               => Outputable (InstDecl name pat) where
620
621     ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
622       = getPprStyle $ \ sty ->
623         if ifaceStyle sty then
624            hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
625         else
626            vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
627                  nest 4 (ppr uprags),
628                  nest 4 (ppr binds) ]
629       where
630         pp_dfun = case maybe_dfun_name of
631                     Just df -> ppr df
632                     Nothing -> empty
633 \end{code}
634
635 \begin{code}
636 instance Ord name => Eq (InstDecl name pat) where
637         -- Used for interface comparison only, so don't compare bindings
638   (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
639        = inst_ty1 == inst_ty2 && dfun1 == dfun2
640 \end{code}
641
642
643 %************************************************************************
644 %*                                                                      *
645 \subsection[DefaultDecl]{A @default@ declaration}
646 %*                                                                      *
647 %************************************************************************
648
649 There can only be one default declaration per module, but it is hard
650 for the parser to check that; we pass them all through in the abstract
651 syntax, and that restriction must be checked in the front end.
652
653 \begin{code}
654 data DefaultDecl name
655   = DefaultDecl [HsType name]
656                 SrcLoc
657
658 instance (Outputable name)
659               => Outputable (DefaultDecl name) where
660
661     ppr (DefaultDecl tys src_loc)
662       = ptext SLIT("default") <+> parens (interpp'SP tys)
663 \end{code}
664
665 %************************************************************************
666 %*                                                                      *
667 \subsection{Foreign function interface declaration}
668 %*                                                                      *
669 %************************************************************************
670
671 \begin{code}
672 data ForeignDecl name = 
673    ForeignDecl 
674         name 
675         ForKind   
676         (HsType name)
677         ExtName
678         CallConv
679         SrcLoc
680
681 instance (Outputable name)
682               => Outputable (ForeignDecl name) where
683
684     ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
685       = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+> 
686         ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
687         where
688          (ppr_imp_exp, ppr_unsafe) =
689            case imp_exp of
690              FoLabel     -> (ptext SLIT("label"), empty)
691              FoExport    -> (ptext SLIT("export"), empty)
692              FoImport us 
693                 | us        -> (ptext SLIT("import"), ptext SLIT("unsafe"))
694                 | otherwise -> (ptext SLIT("import"), empty)
695
696 data ForKind
697  = FoLabel
698  | FoExport
699  | FoImport Bool -- True  => unsafe call.
700
701 data ExtName
702  = Dynamic 
703  | ExtName CLabelString         -- The external name of the foreign thing,
704            (Maybe CLabelString) -- and optionally its DLL or module name
705                                 -- Both of these are completely unencoded; 
706                                 -- we just print them as they are
707
708 isDynamicExtName :: ExtName -> Bool
709 isDynamicExtName Dynamic = True
710 isDynamicExtName _       = False
711
712 extNameStatic :: ExtName -> CLabelString
713 extNameStatic (ExtName f _) = f
714 extNameStatic Dynamic       = panic "staticExtName: Dynamic - shouldn't ever happen."
715
716 instance Outputable ExtName where
717   ppr Dynamic      = ptext SLIT("dynamic")
718   ppr (ExtName nm mb_mod) = 
719      case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+> 
720      doubleQuotes (pprCLabelString nm)
721 \end{code}
722
723 %************************************************************************
724 %*                                                                      *
725 \subsection{Transformation rules}
726 %*                                                                      *
727 %************************************************************************
728
729 \begin{code}
730 data RuleDecl name pat
731   = HsRule                      -- Source rule
732         FAST_STRING             -- Rule name
733         [name]                  -- Forall'd tyvars, filled in by the renamer with
734                                 -- tyvars mentioned in sigs; then filled out by typechecker
735         [RuleBndr name]         -- Forall'd term vars
736         (HsExpr name pat)       -- LHS
737         (HsExpr name pat)       -- RHS
738         SrcLoc          
739
740   | IfaceRule                   -- One that's come in from an interface file; pre-typecheck
741         FAST_STRING
742         [UfBinder name]         -- Tyvars and term vars
743         name                    -- Head of lhs
744         [UfExpr name]           -- Args of LHS
745         (UfExpr name)           -- Pre typecheck
746         SrcLoc          
747
748   | IfaceRuleOut                -- Post typecheck
749         name                    -- Head of LHS
750         CoreRule
751
752 isIfaceRuleDecl (HsRule _ _ _ _ _ _) = False
753 isIfaceRuleDecl other                = True
754
755 ifaceRuleDeclName :: RuleDecl name pat -> name
756 ifaceRuleDeclName (IfaceRule _ _ n _ _ _) = n
757 ifaceRuleDeclName (IfaceRuleOut n r)      = n
758 ifaceRuleDeclName (HsRule fs _ _ _ _ _)   = pprPanic "ifaceRuleDeclName" (ppr fs)
759
760 data RuleBndr name
761   = RuleBndr name
762   | RuleBndrSig name (HsType name)
763
764 instance (NamedThing name, Ord name) => Eq (RuleDecl name pat) where
765   -- Works for IfaceRules only; used when comparing interface file versions
766   (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
767      = n1==n2 && f1 == f2 && 
768        eq_ufBinders emptyEqHsEnv bs1 bs2 (\env -> 
769        eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
770
771 instance (NamedThing name, Outputable name, Outputable pat)
772               => Outputable (RuleDecl name pat) where
773   ppr (HsRule name tvs ns lhs rhs loc)
774         = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
775                pp_forall, ppr lhs, equals <+> ppr rhs,
776                text "#-}" ]
777         where
778           pp_forall | null tvs && null ns = empty
779                     | otherwise           = text "forall" <+> 
780                                             fsep (map ppr tvs ++ map ppr ns)
781                                             <> dot
782
783   ppr (IfaceRule name tpl_vars fn tpl_args rhs loc) 
784     = hsep [ doubleQuotes (ptext name),
785            ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
786            ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
787            ptext SLIT("=") <+> ppr rhs
788       ] <+> semi
789
790   ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
791
792 instance Outputable name => Outputable (RuleBndr name) where
793    ppr (RuleBndr name) = ppr name
794    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
795 \end{code}
796
797
798 %************************************************************************
799 %*                                                                      *
800 \subsection[DeprecDecl]{Deprecations}
801 %*                                                                      *
802 %************************************************************************
803
804 We use exported entities for things to deprecate.
805
806 \begin{code}
807 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
808
809 type DeprecTxt = FAST_STRING    -- reason/explanation for deprecation
810
811 instance Outputable name => Outputable (DeprecDecl name) where
812     ppr (Deprecation thing txt _)
813       = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
814 \end{code}