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