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