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