[project @ 2001-05-24 13:59:09 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 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    decl)                 = forDeclName decl
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 -- TyClDecls are precisely the kind of declarations that can 
253 -- appear in interface files; or (internally) in GHC's interface
254 -- for a module.  That's why (despite the misnomer) IfaceSig and ForeignType
255 -- are both in TyClDecl
256
257 data TyClDecl name pat
258   = IfaceSig {  tcdName :: name,                -- It may seem odd to classify an interface-file signature
259                 tcdType :: HsType name,         -- as a 'TyClDecl', but it's very convenient.  
260                 tcdIdInfo :: [HsIdInfo name],
261                 tcdLoc :: SrcLoc
262     }
263
264   | ForeignType { tcdName   :: name,            -- See remarks about IfaceSig above
265                   tcdFoType :: FoType,
266                   tcdLoc    :: SrcLoc }
267
268   | TyData {    tcdND     :: NewOrData,
269                 tcdCtxt   :: HsContext name,     -- context
270                 tcdName   :: name,               -- type constructor
271                 tcdTyVars :: [HsTyVarBndr name], -- type variables
272                 tcdCons   :: [ConDecl name],     -- data constructors (empty if abstract)
273                 tcdNCons  :: Int,                -- Number of data constructors (valid even if type is abstract)
274                 tcdDerivs :: Maybe [name],       -- derivings; Nothing => not specified
275                                  -- (i.e., derive default); Just [] => derive
276                                  -- *nothing*; Just <list> => as you would
277                                  -- expect...
278                 tcdSysNames :: DataSysNames name,       -- Generic converter functions
279                 tcdLoc      :: SrcLoc
280     }
281
282   | TySynonym { tcdName :: name,                        -- type constructor
283                 tcdTyVars :: [HsTyVarBndr name],        -- type variables
284                 tcdSynRhs :: HsType name,               -- synonym expansion
285                 tcdLoc    :: SrcLoc
286     }
287
288   | ClassDecl { tcdCtxt    :: HsContext name,           -- Context...
289                 tcdName    :: name,                     -- Name of the class
290                 tcdTyVars  :: [HsTyVarBndr name],       -- The class type variables
291                 tcdFDs     :: [FunDep name],            -- Functional dependencies
292                 tcdSigs    :: [Sig name],               -- Methods' signatures
293                 tcdMeths   :: Maybe (MonoBinds name pat),       -- Default methods
294                                                                 -- Nothing for imported class decls
295                                                                 -- Just bs for source   class decls
296                 tcdSysNames :: ClassSysNames name,
297                 tcdLoc      :: SrcLoc
298     }
299 \end{code}
300
301 Simple classifiers
302
303 \begin{code}
304 isIfaceSigDecl, isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
305
306 isIfaceSigDecl (IfaceSig {}) = True
307 isIfaceSigDecl other         = False
308
309 isSynDecl (TySynonym {}) = True
310 isSynDecl other          = False
311
312 isDataDecl (TyData {}) = True
313 isDataDecl other       = False
314
315 isClassDecl (ClassDecl {}) = True
316 isClassDecl other          = False
317 \end{code}
318
319 Dealing with names
320
321 \begin{code}
322 --------------------------------
323 tyClDeclName :: TyClDecl name pat -> name
324 tyClDeclName tycl_decl = tcdName tycl_decl
325
326 --------------------------------
327 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
328 -- Returns all the *binding* names of the decl, along with their SrcLocs
329 -- The first one is guaranteed to be the name of the decl
330 -- For record fields, the first one counts as the SrcLoc
331 -- We use the equality to filter out duplicate field names
332
333 tyClDeclNames (TySynonym   {tcdName = name, tcdLoc = loc})  = [(name,loc)]
334 tyClDeclNames (IfaceSig    {tcdName = name, tcdLoc = loc})  = [(name,loc)]
335 tyClDeclNames (ForeignType {tcdName = name, tcdLoc = loc})  = [(name,loc)]
336
337 tyClDeclNames (ClassDecl {tcdName = cls_name, tcdSigs = sigs, tcdLoc = loc})
338   = (cls_name,loc) : [(n,loc) | ClassOpSig n _ _ loc <- sigs]
339
340 tyClDeclNames (TyData {tcdName = tc_name, tcdCons = cons, tcdLoc = loc})
341   = (tc_name,loc) : conDeclsNames cons
342
343
344 tyClDeclTyVars (TySynonym {tcdTyVars = tvs}) = tvs
345 tyClDeclTyVars (TyData    {tcdTyVars = tvs}) = tvs
346 tyClDeclTyVars (ClassDecl {tcdTyVars = tvs}) = tvs
347 tyClDeclTyVars (ForeignType {})              = []
348 tyClDeclTyVars (IfaceSig {})                 = []
349
350
351 --------------------------------
352 -- The "system names" are extra implicit names *bound* by the decl.
353 -- They are kept in a list rather than a tuple 
354 -- to make the renamer easier.
355
356 type ClassSysNames name = [name]
357 -- For class decls they are:
358 --      [tycon, datacon wrapper, datacon worker, 
359 --       superclass selector 1, ..., superclass selector n]
360
361 type DataSysNames name =  [name]
362 -- For data decls they are
363 --      [from, to]
364 -- where from :: T -> Tring
365 --       to   :: Tring -> T
366
367 tyClDeclSysNames :: TyClDecl name pat -> [(name, SrcLoc)]
368 -- Similar to tyClDeclNames, but returns the "implicit" 
369 -- or "system" names of the declaration
370
371 tyClDeclSysNames (ClassDecl {tcdSysNames = names, tcdLoc = loc})
372   = [(n,loc) | n <- names]
373 tyClDeclSysNames (TyData {tcdCons = cons, tcdSysNames = names, tcdLoc = loc})
374   = [(n,loc) | n <- names] ++ 
375     [(wkr_name,loc) | ConDecl _ wkr_name _ _ _ loc <- cons]
376 tyClDeclSysNames decl = []
377
378
379 mkClassDeclSysNames  :: (name, name, name, [name]) -> [name]
380 getClassDeclSysNames :: [name] -> (name, name, name, [name])
381 mkClassDeclSysNames  (a,b,c,ds) = a:b:c:ds
382 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
383 \end{code}
384
385 \begin{code}
386 instance (NamedThing name, Ord name) => Eq (TyClDecl name pat) where
387         -- Used only when building interface files
388   (==) d1@(IfaceSig {}) d2@(IfaceSig {})
389       = tcdName d1 == tcdName d2 && 
390         tcdType d1 == tcdType d2 && 
391         tcdIdInfo d1 == tcdIdInfo d2
392
393   (==) d1@(ForeignType {}) d2@(ForeignType {})
394       = tcdName d1 == tcdName d2 && 
395         tcdFoType d1 == tcdFoType d2
396
397   (==) d1@(TyData {}) d2@(TyData {})
398       = tcdName d1 == tcdName d2 && 
399         tcdND d1   == tcdND   d2 && 
400         eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
401           eq_hsContext env (tcdCtxt d1) (tcdCtxt d2)  &&
402           eqListBy (eq_ConDecl env) (tcdCons d1) (tcdCons d2)
403         )
404
405   (==) d1@(TySynonym {}) d2@(TySynonym {})
406       = tcdName d1 == tcdName d2 && 
407         eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
408           eq_hsType env (tcdSynRhs d1) (tcdSynRhs d2)
409         )
410
411   (==) d1@(ClassDecl {}) d2@(ClassDecl {})
412     = tcdName d1 == tcdName d2 && 
413       eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
414           eq_hsContext env (tcdCtxt d1) (tcdCtxt d2)  &&
415           eqListBy (eq_hsFD env) (tcdFDs d1) (tcdFDs d2) &&
416           eqListBy (eq_cls_sig env) (tcdSigs d1) (tcdSigs d2)
417        )
418
419   (==) _ _ = False      -- default case
420
421 eq_hsFD env (ns1,ms1) (ns2,ms2)
422   = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
423
424 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
425   = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
426   where
427         -- Ignore the name of the default method for (DefMeth id)
428         -- This is used for comparing declarations before putting
429         -- them into interface files, and the name of the default 
430         -- method isn't relevant
431     NoDefMeth  `eq_dm` NoDefMeth  = True
432     GenDefMeth `eq_dm` GenDefMeth = True
433     DefMeth _  `eq_dm` DefMeth _  = True
434     dm1        `eq_dm` dm2        = False
435
436     
437 \end{code}
438
439 \begin{code}
440 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int, Int)
441         -- class, data, newtype, synonym decls
442 countTyClDecls decls 
443  = (length [() | ClassDecl {} <- decls],
444     length [() | TySynonym {} <- decls],
445     length [() | IfaceSig  {} <- decls],
446     length [() | TyData {tcdND = DataType} <- decls],
447     length [() | TyData {tcdND = NewType} <- decls])
448 \end{code}
449
450 \begin{code}
451 instance (NamedThing name, Outputable name, Outputable pat)
452               => Outputable (TyClDecl name pat) where
453
454     ppr (IfaceSig {tcdName = var, tcdType = ty, tcdIdInfo = info})
455         = hsep [ppr var, dcolon, ppr ty, pprHsIdInfo info]
456
457     ppr (ForeignType {tcdName = tycon})
458         = hsep [ptext SLIT("foreign import type dotnet"), ppr tycon]
459
460     ppr (TySynonym {tcdName = tycon, tcdTyVars = tyvars, tcdSynRhs = mono_ty})
461       = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
462              4 (ppr mono_ty)
463
464     ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdName = tycon,
465                  tcdTyVars = tyvars, tcdCons = condecls, tcdNCons = ncons,
466                  tcdDerivs = derivings})
467       = pp_tydecl (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
468                   (pp_condecls condecls ncons)
469                   derivings
470       where
471         keyword = case new_or_data of
472                         NewType  -> SLIT("newtype")
473                         DataType -> SLIT("data")
474
475     ppr (ClassDecl {tcdCtxt = context, tcdName = clas, tcdTyVars = tyvars, tcdFDs = fds,
476                     tcdSigs = sigs, tcdMeths = methods})
477       | null sigs       -- No "where" part
478       = top_matter
479
480       | otherwise       -- Laid out
481       = sep [hsep [top_matter, ptext SLIT("where {")],
482              nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
483       where
484         top_matter  = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
485         ppr_sig sig = ppr sig <> semi
486         pp_methods = getPprStyle $ \ sty ->
487                      if ifaceStyle sty then empty else ppr methods
488         
489 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
490 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
491
492 pp_condecls []     ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
493 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
494
495 pp_tydecl pp_head pp_decl_rhs derivings
496   = hang pp_head 4 (sep [
497         pp_decl_rhs,
498         case derivings of
499           Nothing          -> empty
500           Just ds          -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
501     ])
502 \end{code}
503
504
505 %************************************************************************
506 %*                                                                      *
507 \subsection[ConDecl]{A data-constructor declaration}
508 %*                                                                      *
509 %************************************************************************
510
511 \begin{code}
512 data ConDecl name
513   = ConDecl     name                    -- Constructor name; this is used for the
514                                         -- DataCon itself, and for the user-callable wrapper Id
515
516                 name                    -- Name of the constructor's 'worker Id'
517                                         -- Filled in as the ConDecl is built
518
519                 [HsTyVarBndr name]      -- Existentially quantified type variables
520                 (HsContext name)        -- ...and context
521                                         -- If both are empty then there are no existentials
522
523                 (ConDetails name)
524                 SrcLoc
525
526 data ConDetails name
527   = VanillaCon                  -- prefix-style con decl
528                 [BangType name]
529
530   | InfixCon                    -- infix-style con decl
531                 (BangType name)
532                 (BangType name)
533
534   | RecCon                      -- record-style con decl
535                 [([name], BangType name)]       -- list of "fields"
536 \end{code}
537
538 \begin{code}
539 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
540   -- See tyClDeclNames for what this does
541   -- The function is boringly complicated because of the records
542   -- And since we only have equality, we have to be a little careful
543 conDeclsNames cons
544   = snd (foldl do_one ([], []) cons)
545   where
546     do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
547         = do_details ((name,loc):acc) details
548         where
549           do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
550           do_details acc other         = (flds_seen, acc)
551
552           do_fld acc (flds, _) = foldl do_fld1 acc flds
553
554           do_fld1 (flds_seen, acc) fld
555                 | fld `elem` flds_seen = (flds_seen,acc)
556                 | otherwise            = (fld:flds_seen, (fld,loc):acc)
557 \end{code}
558
559 \begin{code}
560 conDetailsTys :: ConDetails name -> [HsType name]
561 conDetailsTys (VanillaCon btys)    = map getBangType btys
562 conDetailsTys (InfixCon bty1 bty2) = [getBangType bty1, getBangType bty2]
563 conDetailsTys (RecCon fields)      = [getBangType bty | (_, bty) <- fields]
564
565
566 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
567                (ConDecl n2 _ tvs2 cxt2 cds2 _)
568   = n1 == n2 &&
569     (eq_hsTyVars env tvs1 tvs2  $ \ env ->
570      eq_hsContext env cxt1 cxt2 &&
571      eq_ConDetails env cds1 cds2)
572
573 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
574   = eqListBy (eq_btype env) bts1 bts2
575 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
576   = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
577 eq_ConDetails env (RecCon fs1) (RecCon fs2)
578   = eqListBy (eq_fld env) fs1 fs2
579 eq_ConDetails env _ _ = False
580
581 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
582 \end{code}
583   
584 \begin{code}
585 data BangType name = BangType StrictnessMark (HsType name)
586
587 getBangType       (BangType _ ty) = ty
588 getBangStrictness (BangType s _)  = s
589
590 unbangedType ty = BangType NotMarkedStrict ty
591
592 eq_btype env (BangType s1 t1) (BangType s2 t2) = s1==s2 && eq_hsType env t1 t2
593 \end{code}
594
595 \begin{code}
596 instance (Outputable name) => Outputable (ConDecl name) where
597     ppr (ConDecl con _ tvs cxt con_details  loc)
598       = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
599
600 ppr_con_details con (InfixCon ty1 ty2)
601   = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
602
603 ppr_con_details con (VanillaCon tys)
604   = ppr con <+> hsep (map (ppr_bang) tys)
605
606 ppr_con_details con (RecCon fields)
607   = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
608   where
609     ppr_field (ns, ty) = hsep (map (ppr) ns) <+> 
610                          dcolon <+>
611                          ppr_bang ty
612
613 instance Outputable name => Outputable (BangType name) where
614     ppr = ppr_bang
615
616 ppr_bang (BangType s ty) = ppr s <> pprParendHsType ty
617 \end{code}
618
619
620 %************************************************************************
621 %*                                                                      *
622 \subsection[InstDecl]{An instance declaration
623 %*                                                                      *
624 %************************************************************************
625
626 \begin{code}
627 data InstDecl name pat
628   = InstDecl    (HsType name)   -- Context => Class Instance-type
629                                 -- Using a polytype means that the renamer conveniently
630                                 -- figures out the quantified type variables for us.
631
632                 (MonoBinds name pat)
633
634                 [Sig name]              -- User-supplied pragmatic info
635
636                 (Maybe name)            -- Name for the dictionary function
637                                         -- Nothing for source-file instance decls
638
639                 SrcLoc
640 \end{code}
641
642 \begin{code}
643 instance (Outputable name, Outputable pat)
644               => Outputable (InstDecl name pat) where
645
646     ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
647       = getPprStyle $ \ sty ->
648         if ifaceStyle sty then
649            hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
650         else
651            vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
652                  nest 4 (ppr uprags),
653                  nest 4 (ppr binds) ]
654       where
655         pp_dfun = case maybe_dfun_name of
656                     Just df -> ppr df
657                     Nothing -> empty
658 \end{code}
659
660 \begin{code}
661 instance Ord name => Eq (InstDecl name pat) where
662         -- Used for interface comparison only, so don't compare bindings
663   (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
664        = inst_ty1 == inst_ty2 && dfun1 == dfun2
665 \end{code}
666
667
668 %************************************************************************
669 %*                                                                      *
670 \subsection[DefaultDecl]{A @default@ declaration}
671 %*                                                                      *
672 %************************************************************************
673
674 There can only be one default declaration per module, but it is hard
675 for the parser to check that; we pass them all through in the abstract
676 syntax, and that restriction must be checked in the front end.
677
678 \begin{code}
679 data DefaultDecl name
680   = DefaultDecl [HsType name]
681                 SrcLoc
682
683 instance (Outputable name)
684               => Outputable (DefaultDecl name) where
685
686     ppr (DefaultDecl tys src_loc)
687       = ptext SLIT("default") <+> parens (interpp'SP tys)
688 \end{code}
689
690 %************************************************************************
691 %*                                                                      *
692 \subsection{Foreign function interface declaration}
693 %*                                                                      *
694 %************************************************************************
695
696 \begin{code}
697 data ForeignDecl name
698   = ForeignImport name (HsType name) FoImport     SrcLoc
699   | ForeignExport name (HsType name) FoExport     SrcLoc
700
701 forDeclName (ForeignImport n _ _ _) = n
702 forDeclName (ForeignExport n _ _ _) = n
703
704 data FoImport 
705   = LblImport  CLabelString     -- foreign label
706   | CImport    CCallSpec        -- foreign import 
707   | CDynImport CCallConv        -- foreign export dynamic
708   | DNImport   DNCallSpec       -- foreign import dotnet
709
710 data FoExport = CExport CExportSpec
711
712 data FoType = DNType            -- In due course we'll add subtype stuff
713             deriving( Eq )      -- Used for equality instance for TyClDecl
714
715 instance Outputable name => Outputable (ForeignDecl name) where
716   ppr (ForeignImport nm ty (LblImport lbl) src_loc)
717     = ptext SLIT("foreign label") <+> ppr lbl <+> ppr nm <+> dcolon <+> ppr ty
718   ppr (ForeignImport nm ty decl src_loc)
719     = ptext SLIT("foreign import") <+> ppr decl <+> ppr nm <+> dcolon <+> ppr ty
720   ppr (ForeignExport nm ty decl src_loc)
721     = ptext SLIT("foreign export") <+> ppr decl <+> ppr nm <+> dcolon <+> ppr ty
722
723 instance Outputable FoImport where
724    ppr (CImport  d)      = ppr d
725    ppr (CDynImport conv) = text "dynamic" <+> ppr conv
726    ppr (DNImport d)      = ptext SLIT("dotnet") <+> ppr d
727    ppr (LblImport l)     = ptext SLIT("label") <+> ppr l
728
729 instance Outputable FoExport where
730    ppr (CExport d) = ppr d
731
732 instance Outputable FoType where
733    ppr DNType = ptext SLIT("type dotnet")
734 \end{code}
735
736
737 %************************************************************************
738 %*                                                                      *
739 \subsection{Transformation rules}
740 %*                                                                      *
741 %************************************************************************
742
743 \begin{code}
744 data RuleDecl name pat
745   = HsRule                      -- Source rule
746         FAST_STRING             -- Rule name
747         [name]                  -- Forall'd tyvars, filled in by the renamer with
748                                 -- tyvars mentioned in sigs; then filled out by typechecker
749         [RuleBndr name]         -- Forall'd term vars
750         (HsExpr name pat)       -- LHS
751         (HsExpr name pat)       -- RHS
752         SrcLoc          
753
754   | IfaceRule                   -- One that's come in from an interface file; pre-typecheck
755         FAST_STRING
756         [UfBinder name]         -- Tyvars and term vars
757         name                    -- Head of lhs
758         [UfExpr name]           -- Args of LHS
759         (UfExpr name)           -- Pre typecheck
760         SrcLoc          
761
762   | IfaceRuleOut                -- Post typecheck
763         name                    -- Head of LHS
764         CoreRule
765
766 isIfaceRuleDecl (HsRule _ _ _ _ _ _) = False
767 isIfaceRuleDecl other                = True
768
769 ifaceRuleDeclName :: RuleDecl name pat -> name
770 ifaceRuleDeclName (IfaceRule _ _ n _ _ _) = n
771 ifaceRuleDeclName (IfaceRuleOut n r)      = n
772 ifaceRuleDeclName (HsRule fs _ _ _ _ _)   = pprPanic "ifaceRuleDeclName" (ppr fs)
773
774 data RuleBndr name
775   = RuleBndr name
776   | RuleBndrSig name (HsType name)
777
778 instance (NamedThing name, Ord name) => Eq (RuleDecl name pat) where
779   -- Works for IfaceRules only; used when comparing interface file versions
780   (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
781      = n1==n2 && f1 == f2 && 
782        eq_ufBinders emptyEqHsEnv bs1 bs2 (\env -> 
783        eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
784
785 instance (NamedThing name, Outputable name, Outputable pat)
786               => Outputable (RuleDecl name pat) where
787   ppr (HsRule name tvs ns lhs rhs loc)
788         = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
789                pp_forall, ppr lhs, equals <+> ppr rhs,
790                text "#-}" ]
791         where
792           pp_forall | null tvs && null ns = empty
793                     | otherwise           = text "forall" <+> 
794                                             fsep (map ppr tvs ++ map ppr ns)
795                                             <> dot
796
797   ppr (IfaceRule name tpl_vars fn tpl_args rhs loc) 
798     = hsep [ doubleQuotes (ptext name),
799            ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
800            ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
801            ptext SLIT("=") <+> ppr rhs
802       ] <+> semi
803
804   ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
805
806 instance Outputable name => Outputable (RuleBndr name) where
807    ppr (RuleBndr name) = ppr name
808    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
809 \end{code}
810
811
812 %************************************************************************
813 %*                                                                      *
814 \subsection[DeprecDecl]{Deprecations}
815 %*                                                                      *
816 %************************************************************************
817
818 We use exported entities for things to deprecate.
819
820 \begin{code}
821 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
822
823 type DeprecTxt = FAST_STRING    -- reason/explanation for deprecation
824
825 instance Outputable name => Outputable (DeprecDecl name) where
826     ppr (Deprecation thing txt _)
827       = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
828 \end{code}