[project @ 2002-04-11 12:03:29 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(..), 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         isTypeOrClassDecl, 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 isTypeOrClassDecl (ClassDecl   {}) = True
333 isTypeOrClassDecl (TyData      {}) = True
334 isTypeOrClassDecl (TySynonym   {}) = True
335 isTypeOrClassDecl (ForeignType {}) = True
336 isTypeOrClassDecl other            = False
337
338 isCoreDecl (CoreDecl {}) = True
339 isCoreDecl other         = False
340
341 \end{code}
342
343 Dealing with names
344
345 \begin{code}
346 --------------------------------
347 tyClDeclName :: TyClDecl name pat -> name
348 tyClDeclName tycl_decl = tcdName tycl_decl
349
350 --------------------------------
351 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
352 -- Returns all the *binding* names of the decl, along with their SrcLocs
353 -- The first one is guaranteed to be the name of the decl
354 -- For record fields, the first one counts as the SrcLoc
355 -- We use the equality to filter out duplicate field names
356
357 tyClDeclNames (TySynonym   {tcdName = name, tcdLoc = loc})  = [(name,loc)]
358 tyClDeclNames (IfaceSig    {tcdName = name, tcdLoc = loc})  = [(name,loc)]
359 tyClDeclNames (CoreDecl    {tcdName = name, tcdLoc = loc})  = [(name,loc)]
360 tyClDeclNames (ForeignType {tcdName = name, tcdLoc = loc})  = [(name,loc)]
361
362 tyClDeclNames (ClassDecl {tcdName = cls_name, tcdSigs = sigs, tcdLoc = loc})
363   = (cls_name,loc) : [(n,loc) | ClassOpSig n _ _ loc <- sigs]
364
365 tyClDeclNames (TyData {tcdName = tc_name, tcdCons = cons, tcdLoc = loc})
366   = (tc_name,loc) : conDeclsNames cons
367
368
369 tyClDeclTyVars (TySynonym {tcdTyVars = tvs}) = tvs
370 tyClDeclTyVars (TyData    {tcdTyVars = tvs}) = tvs
371 tyClDeclTyVars (ClassDecl {tcdTyVars = tvs}) = tvs
372 tyClDeclTyVars (ForeignType {})              = []
373 tyClDeclTyVars (IfaceSig {})                 = []
374 tyClDeclTyVars (CoreDecl {})                 = []
375
376
377 --------------------------------
378 -- The "system names" are extra implicit names *bound* by the decl.
379 -- They are kept in a list rather than a tuple 
380 -- to make the renamer easier.
381
382 type ClassSysNames name = [name]
383 -- For class decls they are:
384 --      [tycon, datacon wrapper, datacon worker, 
385 --       superclass selector 1, ..., superclass selector n]
386
387 type DataSysNames name =  [name]
388 -- For data decls they are
389 --      [from, to]
390 -- where from :: T -> Tring
391 --       to   :: Tring -> T
392
393 tyClDeclSysNames :: TyClDecl name pat -> [(name, SrcLoc)]
394 -- Similar to tyClDeclNames, but returns the "implicit" 
395 -- or "system" names of the declaration
396
397 tyClDeclSysNames (ClassDecl {tcdSysNames = names, tcdLoc = loc})
398   = [(n,loc) | n <- names]
399 tyClDeclSysNames (TyData {tcdCons = DataCons cons, tcdSysNames = names, tcdLoc = loc})
400   = [(n,loc) | n <- names] ++ 
401     [(wkr_name,loc) | ConDecl _ wkr_name _ _ _ loc <- cons]
402 tyClDeclSysNames decl = []
403
404
405 mkClassDeclSysNames  :: (name, name, name, [name]) -> [name]
406 getClassDeclSysNames :: [name] -> (name, name, name, [name])
407 mkClassDeclSysNames  (a,b,c,ds) = a:b:c:ds
408 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
409 \end{code}
410
411 \begin{code}
412 instance (NamedThing name, Ord name) => Eq (TyClDecl name pat) where
413         -- Used only when building interface files
414   (==) d1@(IfaceSig {}) d2@(IfaceSig {})
415       = tcdName d1 == tcdName d2 && 
416         tcdType d1 == tcdType d2 && 
417         tcdIdInfo d1 == tcdIdInfo d2
418
419   (==) d1@(CoreDecl {}) d2@(CoreDecl {})
420       = tcdName d1 == tcdName d2 && 
421         tcdType d1 == tcdType d2 && 
422         tcdRhs d1  == tcdRhs  d2
423
424   (==) d1@(ForeignType {}) d2@(ForeignType {})
425       = tcdName d1 == tcdName d2 && 
426         tcdFoType d1 == tcdFoType d2
427
428   (==) d1@(TyData {}) d2@(TyData {})
429       = tcdName d1 == tcdName d2 && 
430         tcdND d1   == tcdND   d2 && 
431         eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
432           eq_hsContext env (tcdCtxt d1) (tcdCtxt d2)  &&
433           eq_hsCD      env (tcdCons d1) (tcdCons d2)
434         )
435
436   (==) d1@(TySynonym {}) d2@(TySynonym {})
437       = tcdName d1 == tcdName d2 && 
438         eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
439           eq_hsType env (tcdSynRhs d1) (tcdSynRhs d2)
440         )
441
442   (==) d1@(ClassDecl {}) d2@(ClassDecl {})
443     = tcdName d1 == tcdName d2 && 
444       eqWithHsTyVars (tcdTyVars d1) (tcdTyVars d2) (\ env -> 
445           eq_hsContext env (tcdCtxt d1) (tcdCtxt d2)  &&
446           eqListBy (eq_hsFD env) (tcdFDs d1) (tcdFDs d2) &&
447           eqListBy (eq_cls_sig env) (tcdSigs d1) (tcdSigs d2)
448        )
449
450   (==) _ _ = False      -- default case
451
452 eq_hsCD env (DataCons c1) (DataCons c2) = eqListBy (eq_ConDecl env) c1 c2
453 eq_hsCD env Unknown       Unknown       = True
454 eq_hsCD env (HasCons n1)  (HasCons n2)  = n1 == n2
455 eq_hsCD env d1            d2            = False
456
457 eq_hsFD env (ns1,ms1) (ns2,ms2)
458   = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
459
460 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
461   = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
462   where
463         -- Ignore the name of the default method for (DefMeth id)
464         -- This is used for comparing declarations before putting
465         -- them into interface files, and the name of the default 
466         -- method isn't relevant
467     NoDefMeth  `eq_dm` NoDefMeth  = True
468     GenDefMeth `eq_dm` GenDefMeth = True
469     DefMeth _  `eq_dm` DefMeth _  = True
470     dm1        `eq_dm` dm2        = False
471
472     
473 \end{code}
474
475 \begin{code}
476 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int, Int)
477         -- class, data, newtype, synonym decls
478 countTyClDecls decls 
479  = (count isClassDecl     decls,
480     count isSynDecl       decls,
481     count (\ x -> isIfaceSigDecl x || isCoreDecl x) decls,
482     count isDataTy        decls,
483     count isNewTy         decls) 
484  where
485    isDataTy TyData{tcdND=DataType} = True
486    isDataTy _                      = False
487    
488    isNewTy TyData{tcdND=NewType} = True
489    isNewTy _                     = False
490 \end{code}
491
492 \begin{code}
493 instance (NamedThing name, Outputable name, Outputable pat)
494               => Outputable (TyClDecl name pat) where
495
496     ppr (IfaceSig {tcdName = var, tcdType = ty, tcdIdInfo = info})
497         = getPprStyle $ \ sty ->
498            hsep [ ppr_var var, dcolon, ppr ty, pprHsIdInfo info ]
499
500     ppr (ForeignType {tcdName = tycon})
501         = hsep [ptext SLIT("foreign import type dotnet"), ppr tycon]
502
503     ppr (TySynonym {tcdName = tycon, tcdTyVars = tyvars, tcdSynRhs = mono_ty})
504       = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
505              4 (ppr mono_ty)
506
507     ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdName = tycon,
508                  tcdTyVars = tyvars, tcdCons = condecls, 
509                  tcdDerivs = derivings})
510       = pp_tydecl (ptext keyword <+> pp_decl_head context tycon tyvars)
511                   (pp_condecls condecls)
512                   derivings
513       where
514         keyword = case new_or_data of
515                         NewType  -> SLIT("newtype")
516                         DataType -> SLIT("data")
517
518     ppr (ClassDecl {tcdCtxt = context, tcdName = clas, tcdTyVars = tyvars, tcdFDs = fds,
519                     tcdSigs = sigs, tcdMeths = methods})
520       | null sigs       -- No "where" part
521       = top_matter
522
523       | otherwise       -- Laid out
524       = sep [hsep [top_matter, ptext SLIT("where {")],
525              nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
526       where
527         top_matter  = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
528         ppr_sig sig = ppr sig <> semi
529
530         pp_methods = if isNothing methods
531                         then empty
532                         else ppr (fromJust methods)
533         
534     ppr (CoreDecl {tcdName = var, tcdType = ty, tcdRhs = rhs})
535         = getPprStyle $ \ sty ->
536            hsep [ ppr_var var, dcolon, ppr ty, ppr rhs ]
537
538 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
539 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
540
541 pp_condecls Unknown       = ptext SLIT("{- abstract -}")
542 pp_condecls (HasCons n)   = ptext SLIT("{- abstract with") <+> int n <+> ptext SLIT("constructors -}")
543 pp_condecls (DataCons cs) = equals <+> sep (punctuate (ptext SLIT(" |")) (map ppr cs))
544
545 pp_tydecl pp_head pp_decl_rhs derivings
546   = hang pp_head 4 (sep [
547         pp_decl_rhs,
548         case derivings of
549           Nothing          -> empty
550           Just ds          -> hsep [ptext SLIT("deriving"), ppr_hs_context ds]
551     ])
552 \end{code}
553
554
555 %************************************************************************
556 %*                                                                      *
557 \subsection[ConDecl]{A data-constructor declaration}
558 %*                                                                      *
559 %************************************************************************
560
561 \begin{code}
562 data ConDecl name
563   = ConDecl     name                    -- Constructor name; this is used for the
564                                         -- DataCon itself, and for the user-callable wrapper Id
565
566                 name                    -- Name of the constructor's 'worker Id'
567                                         -- Filled in as the ConDecl is built
568
569                 [HsTyVarBndr name]      -- Existentially quantified type variables
570                 (HsContext name)        -- ...and context
571                                         -- If both are empty then there are no existentials
572
573                 (ConDetails name)
574                 SrcLoc
575
576 data ConDetails name
577   = VanillaCon                  -- prefix-style con decl
578                 [BangType name]
579
580   | InfixCon                    -- infix-style con decl
581                 (BangType name)
582                 (BangType name)
583
584   | RecCon                      -- record-style con decl
585                 [([name], BangType name)]       -- list of "fields"
586 \end{code}
587
588 \begin{code}
589 conDeclsNames :: Eq name => DataConDetails (ConDecl name) -> [(name,SrcLoc)]
590   -- See tyClDeclNames for what this does
591   -- The function is boringly complicated because of the records
592   -- And since we only have equality, we have to be a little careful
593 conDeclsNames cons
594   = snd (foldl do_one ([], []) (visibleDataCons cons))
595   where
596     do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
597         = do_details ((name,loc):acc) details
598         where
599           do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
600           do_details acc other         = (flds_seen, acc)
601
602           do_fld acc (flds, _) = foldl do_fld1 acc flds
603
604           do_fld1 (flds_seen, acc) fld
605                 | fld `elem` flds_seen = (flds_seen,acc)
606                 | otherwise            = (fld:flds_seen, (fld,loc):acc)
607 \end{code}
608
609 \begin{code}
610 conDetailsTys :: ConDetails name -> [HsType name]
611 conDetailsTys (VanillaCon btys)    = map getBangType btys
612 conDetailsTys (InfixCon bty1 bty2) = [getBangType bty1, getBangType bty2]
613 conDetailsTys (RecCon fields)      = [getBangType bty | (_, bty) <- fields]
614
615
616 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
617                (ConDecl n2 _ tvs2 cxt2 cds2 _)
618   = n1 == n2 &&
619     (eq_hsTyVars env tvs1 tvs2  $ \ env ->
620      eq_hsContext env cxt1 cxt2 &&
621      eq_ConDetails env cds1 cds2)
622
623 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
624   = eqListBy (eq_btype env) bts1 bts2
625 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
626   = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
627 eq_ConDetails env (RecCon fs1) (RecCon fs2)
628   = eqListBy (eq_fld env) fs1 fs2
629 eq_ConDetails env _ _ = False
630
631 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
632 \end{code}
633   
634 \begin{code}
635 data BangType name = BangType StrictnessMark (HsType name)
636
637 getBangType       (BangType _ ty) = ty
638 getBangStrictness (BangType s _)  = s
639
640 unbangedType ty = BangType NotMarkedStrict ty
641
642 eq_btype env (BangType s1 t1) (BangType s2 t2) = s1==s2 && eq_hsType env t1 t2
643 \end{code}
644
645 \begin{code}
646 instance (Outputable name) => Outputable (ConDecl name) where
647     ppr (ConDecl con _ tvs cxt con_details  loc)
648       = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
649
650 ppr_con_details con (InfixCon ty1 ty2)
651   = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
652
653 -- ConDecls generated by MkIface.ifaceTyThing always have a VanillaCon, even
654 -- if the constructor is an infix one.  This is because in an interface file
655 -- we don't distinguish between the two.  Hence when printing these for the
656 -- user, we need to parenthesise infix constructor names.
657 ppr_con_details con (VanillaCon tys)
658   = hsep (ppr_var con : map (ppr_bang) tys)
659
660 ppr_con_details con (RecCon fields)
661   = ppr con <+> braces (sep (punctuate comma (map ppr_field fields)))
662   where
663     ppr_field (ns, ty) = hsep (map (ppr) ns) <+> 
664                          dcolon <+>
665                          ppr_bang ty
666
667 instance Outputable name => Outputable (BangType name) where
668     ppr = ppr_bang
669
670 ppr_bang (BangType s ty) = ppr s <> pprParendHsType ty
671 \end{code}
672
673
674 %************************************************************************
675 %*                                                                      *
676 \subsection[InstDecl]{An instance declaration
677 %*                                                                      *
678 %************************************************************************
679
680 \begin{code}
681 data InstDecl name pat
682   = InstDecl    (HsType name)   -- Context => Class Instance-type
683                                 -- Using a polytype means that the renamer conveniently
684                                 -- figures out the quantified type variables for us.
685
686                 (MonoBinds name pat)
687
688                 [Sig name]              -- User-supplied pragmatic info
689
690                 (Maybe name)            -- Name for the dictionary function
691                                         -- Nothing for source-file instance decls
692
693                 SrcLoc
694
695 isSourceInstDecl :: InstDecl name pat -> Bool
696 isSourceInstDecl (InstDecl _ _ _ maybe_dfun _) = isNothing maybe_dfun
697 \end{code}
698
699 \begin{code}
700 instance (Outputable name, Outputable pat)
701               => Outputable (InstDecl name pat) where
702
703     ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
704       = vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
705               nest 4 (ppr uprags),
706               nest 4 (ppr binds) ]
707       where
708         pp_dfun = case maybe_dfun_name of
709                     Just df -> ppr df
710                     Nothing -> empty
711 \end{code}
712
713 \begin{code}
714 instance Ord name => Eq (InstDecl name pat) where
715         -- Used for interface comparison only, so don't compare bindings
716   (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
717        = inst_ty1 == inst_ty2 && dfun1 == dfun2
718 \end{code}
719
720
721 %************************************************************************
722 %*                                                                      *
723 \subsection[DefaultDecl]{A @default@ declaration}
724 %*                                                                      *
725 %************************************************************************
726
727 There can only be one default declaration per module, but it is hard
728 for the parser to check that; we pass them all through in the abstract
729 syntax, and that restriction must be checked in the front end.
730
731 \begin{code}
732 data DefaultDecl name
733   = DefaultDecl [HsType name]
734                 SrcLoc
735
736 instance (Outputable name)
737               => Outputable (DefaultDecl name) where
738
739     ppr (DefaultDecl tys src_loc)
740       = ptext SLIT("default") <+> parens (interpp'SP tys)
741 \end{code}
742
743 %************************************************************************
744 %*                                                                      *
745 \subsection{Foreign function interface declaration}
746 %*                                                                      *
747 %************************************************************************
748
749 \begin{code}
750
751 -- foreign declarations are distinguished as to whether they define or use a
752 -- Haskell name
753 --
754 -- * the Boolean value indicates whether the pre-standard deprecated syntax
755 --   has been used
756 --
757 data ForeignDecl name
758   = ForeignImport name (HsType name) ForeignImport Bool SrcLoc  -- defines name
759   | ForeignExport name (HsType name) ForeignExport Bool SrcLoc  -- uses name
760
761 -- yield the Haskell name defined or used in a foreign declaration
762 --
763 foreignDeclName                           :: ForeignDecl name -> name
764 foreignDeclName (ForeignImport n _ _ _ _)  = n
765 foreignDeclName (ForeignExport n _ _ _ _)  = n
766
767 -- specification of an imported external entity in dependence on the calling
768 -- convention 
769 --
770 data ForeignImport = -- import of a C entity
771                      --
772                      -- * the two strings specifying a header file or library
773                      --   may be empty, which indicates the absence of a
774                      --   header or object specification (both are not used
775                      --   in the case of `CWrapper' and when `CFunction'
776                      --   has a dynamic target)
777                      --
778                      -- * the calling convention is irrelevant for code
779                      --   generation in the case of `CLabel', but is needed
780                      --   for pretty printing 
781                      --
782                      -- * `Safety' is irrelevant for `CLabel' and `CWrapper'
783                      --
784                      CImport  CCallConv       -- ccall or stdcall
785                               Safety          -- safe or unsafe
786                               FastString      -- name of C header
787                               FastString      -- name of library object
788                               CImportSpec     -- details of the C entity
789
790                      -- import of a .NET function
791                      --
792                    | DNImport DNCallSpec
793
794 -- details of an external C entity
795 --
796 data CImportSpec = CLabel    CLabelString     -- import address of a C label
797                  | CFunction CCallTarget      -- static or dynamic function
798                  | CWrapper                   -- wrapper to expose closures
799                                               -- (former f.e.d.)
800
801 -- specification of an externally exported entity in dependence on the calling
802 -- convention
803 --
804 data ForeignExport = CExport  CExportSpec    -- contains the calling convention
805                    | DNExport                -- presently unused
806
807 -- abstract type imported from .NET
808 --
809 data FoType = DNType            -- In due course we'll add subtype stuff
810             deriving (Eq)       -- Used for equality instance for TyClDecl
811
812
813 -- pretty printing of foreign declarations
814 --
815
816 instance Outputable name => Outputable (ForeignDecl name) where
817   ppr (ForeignImport n ty fimport _ _) =
818     ptext SLIT("foreign import") <+> ppr fimport <+> 
819     ppr n <+> dcolon <+> ppr ty
820   ppr (ForeignExport n ty fexport _ _) =
821     ptext SLIT("foreign export") <+> ppr fexport <+> 
822     ppr n <+> dcolon <+> ppr ty
823
824 instance Outputable ForeignImport where
825   ppr (DNImport                         spec) = 
826     ptext SLIT("dotnet") <+> ppr spec
827   ppr (CImport  cconv safety header lib spec) =
828     ppr cconv <+> ppr safety <+> 
829     char '"' <> pprCEntity header lib spec <> char '"'
830     where
831       pprCEntity header lib (CLabel lbl) = 
832         ptext SLIT("static") <+> ptext header <+> char '&' <>
833         pprLib lib <> ppr lbl
834       pprCEntity header lib (CFunction (StaticTarget lbl)) = 
835         ptext SLIT("static") <+> ptext header <+> char '&' <>
836         pprLib lib <> ppr lbl
837       pprCEntity header lib (CFunction (DynamicTarget)) = 
838         ptext SLIT("dynamic")
839       pprCEntity header lib (CFunction (CasmTarget _)) = 
840         panic "HsDecls.pprCEntity: malformed C function target"
841       pprCEntity _      _   (CWrapper) = ptext SLIT("wrapper")
842       --
843       pprLib lib | nullFastString lib = empty
844                  | otherwise          = char '[' <> ppr lib <> char ']'
845
846 instance Outputable ForeignExport where
847   ppr (CExport  (CExportStatic lbl cconv)) = 
848     ppr cconv <+> char '"' <> ppr lbl <> char '"'
849   ppr (DNExport                          ) = 
850     ptext SLIT("dotnet") <+> ptext SLIT("\"<unused>\"")
851
852 instance Outputable FoType where
853   ppr DNType = ptext SLIT("type dotnet")
854 \end{code}
855
856
857 %************************************************************************
858 %*                                                                      *
859 \subsection{Transformation rules}
860 %*                                                                      *
861 %************************************************************************
862
863 \begin{code}
864 data RuleDecl name pat
865   = HsRule                      -- Source rule
866         RuleName                -- Rule name
867         Activation
868         [RuleBndr name]         -- Forall'd vars; after typechecking this includes tyvars
869         (HsExpr name pat)       -- LHS
870         (HsExpr name pat)       -- RHS
871         SrcLoc          
872
873   | IfaceRule                   -- One that's come in from an interface file; pre-typecheck
874         RuleName
875         Activation
876         [UfBinder name]         -- Tyvars and term vars
877         name                    -- Head of lhs
878         [UfExpr name]           -- Args of LHS
879         (UfExpr name)           -- Pre typecheck
880         SrcLoc          
881
882   | IfaceRuleOut                -- Post typecheck
883         name                    -- Head of LHS
884         CoreRule
885
886 ifaceRuleDeclName :: RuleDecl name pat -> name
887 ifaceRuleDeclName (IfaceRule _ _ _ n _ _ _) = n
888 ifaceRuleDeclName (IfaceRuleOut n r)        = n
889 ifaceRuleDeclName (HsRule fs _ _ _ _ _)     = pprPanic "ifaceRuleDeclName" (ppr fs)
890
891 data RuleBndr name
892   = RuleBndr name
893   | RuleBndrSig name (HsType name)
894
895 collectRuleBndrSigTys :: [RuleBndr name] -> [HsType name]
896 collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs]
897
898 instance (NamedThing name, Ord name) => Eq (RuleDecl name pat) where
899   -- Works for IfaceRules only; used when comparing interface file versions
900   (IfaceRule n1 a1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 a2 bs2 f2 es2 rhs2 _)
901      = n1==n2 && f1 == f2 && a1==a2 &&
902        eq_ufBinders emptyEqHsEnv bs1 bs2 (\env -> 
903        eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
904
905 instance (NamedThing name, Outputable name, Outputable pat)
906               => Outputable (RuleDecl name pat) where
907   ppr (HsRule name act ns lhs rhs loc)
908         = sep [text "{-# RULES" <+> doubleQuotes (ptext name) <+> ppr act,
909                pp_forall, ppr lhs, equals <+> ppr rhs,
910                text "#-}" ]
911         where
912           pp_forall | null ns   = empty
913                     | otherwise = text "forall" <+> fsep (map ppr ns) <> dot
914
915   ppr (IfaceRule name act tpl_vars fn tpl_args rhs loc) 
916     = hsep [ doubleQuotes (ptext name), ppr act,
917            ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
918            ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
919            ptext SLIT("=") <+> ppr rhs
920       ] <+> semi
921
922   ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
923
924 instance Outputable name => Outputable (RuleBndr name) where
925    ppr (RuleBndr name) = ppr name
926    ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
927 \end{code}
928
929
930 %************************************************************************
931 %*                                                                      *
932 \subsection[DeprecDecl]{Deprecations}
933 %*                                                                      *
934 %************************************************************************
935
936 We use exported entities for things to deprecate.
937
938 \begin{code}
939 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
940
941 type DeprecTxt = FAST_STRING    -- reason/explanation for deprecation
942
943 instance Outputable name => Outputable (DeprecDecl name) where
944     ppr (Deprecation thing txt _)
945       = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
946 \end{code}