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