[project @ 2001-10-25 02:13:10 by sof]
[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, count )
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  = (count isClassDecl     decls,
449     count isSynDecl       decls,
450     count isIfaceSigDecl  decls,
451     count isDataTy        decls,
452     count isNewTy         decls) 
453  where
454    isDataTy TyData{tcdND=DataType} = True
455    isDataTy _                      = False
456    
457    isNewTy TyData{tcdND=NewType} = True
458    isNewTy _                     = False
459 \end{code}
460
461 \begin{code}
462 instance (NamedThing name, Outputable name, Outputable pat)
463               => Outputable (TyClDecl name pat) where
464
465     ppr (IfaceSig {tcdName = var, tcdType = ty, tcdIdInfo = info})
466         = getPprStyle $ \ sty ->
467            hsep [ if ifaceStyle sty then ppr var else ppr_var var,
468                   dcolon, ppr ty, pprHsIdInfo info
469                 ]
470
471     ppr (ForeignType {tcdName = tycon})
472         = hsep [ptext SLIT("foreign import type dotnet"), ppr tycon]
473
474     ppr (TySynonym {tcdName = tycon, tcdTyVars = tyvars, tcdSynRhs = mono_ty})
475       = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
476              4 (ppr mono_ty)
477
478     ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdName = tycon,
479                  tcdTyVars = tyvars, tcdCons = condecls, tcdNCons = ncons,
480                  tcdDerivs = derivings})
481       = pp_tydecl (ptext keyword <+> pp_decl_head context tycon tyvars)
482                   (pp_condecls condecls ncons)
483                   derivings
484       where
485         keyword = case new_or_data of
486                         NewType  -> SLIT("newtype")
487                         DataType -> SLIT("data")
488
489     ppr (ClassDecl {tcdCtxt = context, tcdName = clas, tcdTyVars = tyvars, tcdFDs = fds,
490                     tcdSigs = sigs, tcdMeths = methods})
491       | null sigs       -- No "where" part
492       = top_matter
493
494       | otherwise       -- Laid out
495       = sep [hsep [top_matter, ptext SLIT("where {")],
496              nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
497       where
498         top_matter  = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
499         ppr_sig sig = ppr sig <> semi
500
501         pp_methods = getPprStyle $ \ sty ->
502                      if ifaceStyle sty || isNothing methods
503                         then empty
504                         else ppr (fromJust methods)
505         
506 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
507 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
508
509 pp_condecls []     ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
510 pp_condecls (c:cs) ncons = equals <+> sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
511
512 pp_tydecl pp_head pp_decl_rhs derivings
513   = hang pp_head 4 (sep [
514         pp_decl_rhs,
515         case derivings of
516           Nothing          -> empty
517           Just ds          -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
518     ])
519 \end{code}
520
521
522 %************************************************************************
523 %*                                                                      *
524 \subsection[ConDecl]{A data-constructor declaration}
525 %*                                                                      *
526 %************************************************************************
527
528 \begin{code}
529 data ConDecl name
530   = ConDecl     name                    -- Constructor name; this is used for the
531                                         -- DataCon itself, and for the user-callable wrapper Id
532
533                 name                    -- Name of the constructor's 'worker Id'
534                                         -- Filled in as the ConDecl is built
535
536                 [HsTyVarBndr name]      -- Existentially quantified type variables
537                 (HsContext name)        -- ...and context
538                                         -- If both are empty then there are no existentials
539
540                 (ConDetails name)
541                 SrcLoc
542
543 data ConDetails name
544   = VanillaCon                  -- prefix-style con decl
545                 [BangType name]
546
547   | InfixCon                    -- infix-style con decl
548                 (BangType name)
549                 (BangType name)
550
551   | RecCon                      -- record-style con decl
552                 [([name], BangType name)]       -- list of "fields"
553 \end{code}
554
555 \begin{code}
556 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
557   -- See tyClDeclNames for what this does
558   -- The function is boringly complicated because of the records
559   -- And since we only have equality, we have to be a little careful
560 conDeclsNames cons
561   = snd (foldl do_one ([], []) cons)
562   where
563     do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
564         = do_details ((name,loc):acc) details
565         where
566           do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
567           do_details acc other         = (flds_seen, acc)
568
569           do_fld acc (flds, _) = foldl do_fld1 acc flds
570
571           do_fld1 (flds_seen, acc) fld
572                 | fld `elem` flds_seen = (flds_seen,acc)
573                 | otherwise            = (fld:flds_seen, (fld,loc):acc)
574 \end{code}
575
576 \begin{code}
577 conDetailsTys :: ConDetails name -> [HsType name]
578 conDetailsTys (VanillaCon btys)    = map getBangType btys
579 conDetailsTys (InfixCon bty1 bty2) = [getBangType bty1, getBangType bty2]
580 conDetailsTys (RecCon fields)      = [getBangType bty | (_, bty) <- fields]
581
582
583 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
584                (ConDecl n2 _ tvs2 cxt2 cds2 _)
585   = n1 == n2 &&
586     (eq_hsTyVars env tvs1 tvs2  $ \ env ->
587      eq_hsContext env cxt1 cxt2 &&
588      eq_ConDetails env cds1 cds2)
589
590 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
591   = eqListBy (eq_btype env) bts1 bts2
592 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
593   = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
594 eq_ConDetails env (RecCon fs1) (RecCon fs2)
595   = eqListBy (eq_fld env) fs1 fs2
596 eq_ConDetails env _ _ = False
597
598 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
599 \end{code}
600   
601 \begin{code}
602 data BangType name = BangType StrictnessMark (HsType name)
603
604 getBangType       (BangType _ ty) = ty
605 getBangStrictness (BangType s _)  = s
606
607 unbangedType ty = BangType NotMarkedStrict ty
608
609 eq_btype env (BangType s1 t1) (BangType s2 t2) = s1==s2 && eq_hsType env t1 t2
610 \end{code}
611
612 \begin{code}
613 instance (Outputable name) => Outputable (ConDecl name) where
614     ppr (ConDecl con _ tvs cxt con_details  loc)
615       = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
616
617 ppr_con_details con (InfixCon ty1 ty2)
618   = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
619
620 -- ConDecls generated by MkIface.ifaceTyThing always have a VanillaCon, even
621 -- if the constructor is an infix one.  This is because in an interface file
622 -- we don't distinguish between the two.  Hence when printing these for the
623 -- user, we need to parenthesise infix constructor names.
624 ppr_con_details con (VanillaCon tys)
625   = getPprStyle $ \ sty ->
626     hsep ((if ifaceStyle sty then ppr con else ppr_var con)
627           : map (ppr_bang) tys)
628
629 ppr_con_details con (RecCon fields)
630   = ppr con <+> braces (sep (punctuate comma (map ppr_field fields)))
631   where
632     ppr_field (ns, ty) = hsep (map (ppr) ns) <+> 
633                          dcolon <+>
634                          ppr_bang ty
635
636 instance Outputable name => Outputable (BangType name) where
637     ppr = ppr_bang
638
639 ppr_bang (BangType s ty) = ppr s <> pprParendHsType ty
640 \end{code}
641
642
643 %************************************************************************
644 %*                                                                      *
645 \subsection[InstDecl]{An instance declaration
646 %*                                                                      *
647 %************************************************************************
648
649 \begin{code}
650 data InstDecl name pat
651   = InstDecl    (HsType name)   -- Context => Class Instance-type
652                                 -- Using a polytype means that the renamer conveniently
653                                 -- figures out the quantified type variables for us.
654
655                 (MonoBinds name pat)
656
657                 [Sig name]              -- User-supplied pragmatic info
658
659                 (Maybe name)            -- Name for the dictionary function
660                                         -- Nothing for source-file instance decls
661
662                 SrcLoc
663 \end{code}
664
665 \begin{code}
666 instance (Outputable name, Outputable pat)
667               => Outputable (InstDecl name pat) where
668
669     ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
670       = getPprStyle $ \ sty ->
671         if ifaceStyle sty then
672            hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
673         else
674            vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
675                  nest 4 (ppr uprags),
676                  nest 4 (ppr binds) ]
677       where
678         pp_dfun = case maybe_dfun_name of
679                     Just df -> ppr df
680                     Nothing -> empty
681 \end{code}
682
683 \begin{code}
684 instance Ord name => Eq (InstDecl name pat) where
685         -- Used for interface comparison only, so don't compare bindings
686   (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
687        = inst_ty1 == inst_ty2 && dfun1 == dfun2
688 \end{code}
689
690
691 %************************************************************************
692 %*                                                                      *
693 \subsection[DefaultDecl]{A @default@ declaration}
694 %*                                                                      *
695 %************************************************************************
696
697 There can only be one default declaration per module, but it is hard
698 for the parser to check that; we pass them all through in the abstract
699 syntax, and that restriction must be checked in the front end.
700
701 \begin{code}
702 data DefaultDecl name
703   = DefaultDecl [HsType name]
704                 SrcLoc
705
706 instance (Outputable name)
707               => Outputable (DefaultDecl name) where
708
709     ppr (DefaultDecl tys src_loc)
710       = ptext SLIT("default") <+> parens (interpp'SP tys)
711 \end{code}
712
713 %************************************************************************
714 %*                                                                      *
715 \subsection{Foreign function interface declaration}
716 %*                                                                      *
717 %************************************************************************
718
719 \begin{code}
720 data ForeignDecl name
721   = ForeignImport name (HsType name) FoImport     SrcLoc
722   | ForeignExport name (HsType name) FoExport     SrcLoc
723
724 forDeclName (ForeignImport n _ _ _) = n
725 forDeclName (ForeignExport n _ _ _) = n
726
727 data FoImport 
728   = LblImport  CLabelString     -- foreign label
729   | CImport    CCallSpec        -- foreign import 
730   | CDynImport CCallConv        -- foreign export dynamic
731   | DNImport   DNCallSpec       -- foreign import dotnet
732
733 data FoExport = CExport CExportSpec
734
735 data FoType = DNType            -- In due course we'll add subtype stuff
736             deriving( Eq )      -- Used for equality instance for TyClDecl
737
738 instance Outputable name => Outputable (ForeignDecl name) where
739   ppr (ForeignImport nm ty (LblImport lbl) src_loc)
740     = ptext SLIT("foreign label") <+> ppr lbl <+> ppr nm <+> dcolon <+> ppr ty
741   ppr (ForeignImport nm ty decl src_loc)
742     = ptext SLIT("foreign import") <+> ppr decl <+> ppr nm <+> dcolon <+> ppr ty
743   ppr (ForeignExport nm ty decl src_loc)
744     = ptext SLIT("foreign export") <+> ppr decl <+> ppr nm <+> dcolon <+> ppr ty
745
746 instance Outputable FoImport where
747    ppr (CImport  d)      = ppr d
748    ppr (CDynImport conv) = text "dynamic" <+> ppr conv
749    ppr (DNImport d)      = ptext SLIT("dotnet") <+> ppr d
750    ppr (LblImport l)     = ptext SLIT("label") <+> ppr l
751
752 instance Outputable FoExport where
753    ppr (CExport d) = ppr d
754
755 instance Outputable FoType where
756    ppr DNType = ptext SLIT("type dotnet")
757 \end{code}
758
759
760 %************************************************************************
761 %*                                                                      *
762 \subsection{Transformation rules}
763 %*                                                                      *
764 %************************************************************************
765
766 \begin{code}
767 data RuleDecl name pat
768   = HsRule                      -- Source rule
769         RuleName                -- Rule name
770         Activation
771         [name]                  -- Forall'd tyvars, filled in by the renamer with
772                                 -- tyvars mentioned in sigs; then filled out by typechecker
773         [RuleBndr name]         -- Forall'd term vars
774         (HsExpr name pat)       -- LHS
775         (HsExpr name pat)       -- RHS
776         SrcLoc          
777
778   | IfaceRule                   -- One that's come in from an interface file; pre-typecheck
779         RuleName
780         Activation
781         [UfBinder name]         -- Tyvars and term vars
782         name                    -- Head of lhs
783         [UfExpr name]           -- Args of LHS
784         (UfExpr name)           -- Pre typecheck
785         SrcLoc          
786
787   | IfaceRuleOut                -- Post typecheck
788         name                    -- Head of LHS
789         CoreRule
790
791 isIfaceRuleDecl :: RuleDecl name pat -> Bool
792 isIfaceRuleDecl (HsRule _ _ _ _ _ _ _) = False
793 isIfaceRuleDecl other                  = True
794
795 ifaceRuleDeclName :: RuleDecl name pat -> name
796 ifaceRuleDeclName (IfaceRule _ _ _ n _ _ _) = n
797 ifaceRuleDeclName (IfaceRuleOut n r)        = n
798 ifaceRuleDeclName (HsRule fs _ _ _ _ _ _)   = pprPanic "ifaceRuleDeclName" (ppr fs)
799
800 data RuleBndr name
801   = RuleBndr name
802   | RuleBndrSig name (HsType name)
803
804 instance (NamedThing name, Ord name) => Eq (RuleDecl name pat) where
805   -- Works for IfaceRules only; used when comparing interface file versions
806   (IfaceRule n1 a1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 a2 bs2 f2 es2 rhs2 _)
807      = n1==n2 && f1 == f2 && a1==a2 &&
808        eq_ufBinders emptyEqHsEnv bs1 bs2 (\env -> 
809        eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
810
811 instance (NamedThing name, Outputable name, Outputable pat)
812               => Outputable (RuleDecl name pat) where
813   ppr (HsRule name act tvs ns lhs rhs loc)
814         = sep [text "{-# RULES" <+> doubleQuotes (ptext name) <+> ppr act,
815                pp_forall, ppr lhs, equals <+> ppr rhs,
816                text "#-}" ]
817         where
818           pp_forall | null tvs && null ns = empty
819                     | otherwise           = text "forall" <+> 
820                                             fsep (map ppr tvs ++ map ppr ns)
821                                             <> dot
822
823   ppr (IfaceRule name act tpl_vars fn tpl_args rhs loc) 
824     = hsep [ doubleQuotes (ptext name), ppr act,
825            ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
826            ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
827            ptext SLIT("=") <+> ppr rhs
828       ] <+> semi
829
830   ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
831
832 instance Outputable name => Outputable (RuleBndr name) where
833    ppr (RuleBndr name) = ppr name
834    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
835 \end{code}
836
837
838 %************************************************************************
839 %*                                                                      *
840 \subsection[DeprecDecl]{Deprecations}
841 %*                                                                      *
842 %************************************************************************
843
844 We use exported entities for things to deprecate.
845
846 \begin{code}
847 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
848
849 type DeprecTxt = FAST_STRING    -- reason/explanation for deprecation
850
851 instance Outputable name => Outputable (DeprecDecl name) where
852     ppr (Deprecation thing txt _)
853       = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
854 \end{code}