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