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