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