2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[HsDecls]{Abstract syntax: global declarations}
6 Definitions for: @TyDecl@ and @oCnDecl@, @ClassDecl@,
7 @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
11 HsDecl(..), LHsDecl, TyClDecl(..), LTyClDecl,
12 InstDecl(..), LInstDecl, NewOrData(..),
13 RuleDecl(..), LRuleDecl, RuleBndr(..),
14 DefaultDecl(..), LDefaultDecl, HsGroup(..), SpliceDecl(..),
15 ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
16 CImportSpec(..), FoType(..),
17 ConDecl(..), LConDecl,
18 DeprecDecl(..), LDeprecDecl,
19 tcdName, tyClDeclNames, tyClDeclTyVars,
20 isClassDecl, isSynDecl, isDataDecl,
23 collectRuleBndrSigTys,
26 #include "HsVersions.h"
29 import {-# SOURCE #-} HsExpr( HsExpr, pprExpr )
30 -- Because Expr imports Decls via HsBracket
32 import HsBinds ( HsBindGroup, HsBind, LHsBinds,
33 Sig(..), LSig, LFixitySig, pprLHsBinds )
34 import HsPat ( HsConDetails(..), hsConArgs )
35 import HsImpExp ( pprHsVar )
37 import HscTypes ( DeprecTxt )
38 import CoreSyn ( RuleName )
39 import BasicTypes ( Activation(..) )
40 import ForeignCall ( CCallTarget(..), DNCallSpec, CCallConv, Safety,
41 CExportSpec(..), CLabelString )
44 import FunDeps ( pprFundeps )
45 import Class ( FunDep )
48 import SrcLoc ( Located(..), unLoc )
53 %************************************************************************
55 \subsection[HsDecl]{Declarations}
57 %************************************************************************
60 type LHsDecl id = Located (HsDecl id)
67 | DefD (DefaultDecl id)
68 | ForD (ForeignDecl id)
69 | DeprecD (DeprecDecl id)
71 | SpliceD (SpliceDecl id)
73 -- NB: all top-level fixity decls are contained EITHER
75 -- OR in the ClassDecls in TyClDs
78 -- a) data constructors
79 -- b) class methods (but they can be also done in the
80 -- signatures of class decls)
81 -- c) imported functions (that have an IfacSig)
84 -- The latter is for class methods only
86 -- A [HsDecl] is categorised into a HsGroup before being
87 -- fed to the renamer.
90 hs_valds :: [HsBindGroup id],
91 -- Before the renamer, this is a single big HsBindGroup,
92 -- with all the bindings, and all the signatures.
93 -- The renamer does dependency analysis, splitting it up
94 -- into several HsBindGroups.
96 hs_tyclds :: [LTyClDecl id],
97 hs_instds :: [LInstDecl id],
99 hs_fixds :: [LFixitySig id],
100 -- Snaffled out of both top-level fixity signatures,
101 -- and those in class declarations
103 hs_defds :: [LDefaultDecl id],
104 hs_fords :: [LForeignDecl id],
105 hs_depds :: [LDeprecDecl id],
106 hs_ruleds :: [LRuleDecl id]
111 instance OutputableBndr name => Outputable (HsDecl name) where
112 ppr (TyClD dcl) = ppr dcl
113 ppr (ValD binds) = ppr binds
114 ppr (DefD def) = ppr def
115 ppr (InstD inst) = ppr inst
116 ppr (ForD fd) = ppr fd
117 ppr (SigD sd) = ppr sd
118 ppr (RuleD rd) = ppr rd
119 ppr (DeprecD dd) = ppr dd
120 ppr (SpliceD dd) = ppr dd
122 instance OutputableBndr name => Outputable (HsGroup name) where
123 ppr (HsGroup { hs_valds = val_decls,
124 hs_tyclds = tycl_decls,
125 hs_instds = inst_decls,
126 hs_fixds = fix_decls,
127 hs_depds = deprec_decls,
128 hs_fords = foreign_decls,
129 hs_defds = default_decls,
130 hs_ruleds = rule_decls })
131 = vcat [ppr_ds fix_decls, ppr_ds default_decls,
132 ppr_ds deprec_decls, ppr_ds rule_decls,
134 ppr_ds tycl_decls, ppr_ds inst_decls,
135 ppr_ds foreign_decls]
138 ppr_ds ds = text "" $$ vcat (map ppr ds)
140 data SpliceDecl id = SpliceDecl (Located (HsExpr id)) -- Top level splice
142 instance OutputableBndr name => Outputable (SpliceDecl name) where
143 ppr (SpliceDecl e) = ptext SLIT("$") <> parens (pprExpr (unLoc e))
147 %************************************************************************
149 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
151 %************************************************************************
153 --------------------------------
155 --------------------------------
157 Here is the story about the implicit names that go with type, class,
158 and instance decls. It's a bit tricky, so pay attention!
160 "Implicit" (or "system") binders
161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
162 Each data type decl defines
163 a worker name for each constructor
164 to-T and from-T convertors
165 Each class decl defines
166 a tycon for the class
167 a data constructor for that tycon
168 the worker for that constructor
169 a selector for each superclass
171 All have occurrence names that are derived uniquely from their parent
174 None of these get separate definitions in an interface file; they are
175 fully defined by the data or class decl. But they may *occur* in
176 interface files, of course. Any such occurrence must haul in the
177 relevant type or class decl.
180 - Ensure they "point to" the parent data/class decl
181 when loading that decl from an interface file
182 (See RnHiFiles.getSysBinders)
184 - When typechecking the decl, we build the implicit TyCons and Ids.
185 When doing so we look them up in the name cache (RnEnv.lookupSysName),
186 to ensure correct module and provenance is set
188 These are the two places that we have to conjure up the magic derived
189 names. (The actual magic is in OccName.mkWorkerOcc, etc.)
193 - Occurrence name is derived uniquely from the method name
196 - If there is a default method name at all, it's recorded in
197 the ClassOpSig (in HsBinds), in the DefMeth field.
198 (DefMeth is defined in Class.lhs)
200 Source-code class decls and interface-code class decls are treated subtly
201 differently, which has given me a great deal of confusion over the years.
202 Here's the deal. (We distinguish the two cases because source-code decls
203 have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.
205 In *source-code* class declarations:
207 - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
208 This is done by RdrHsSyn.mkClassOpSigDM
210 - The renamer renames it to a Name
212 - During typechecking, we generate a binding for each $dm for
213 which there's a programmer-supplied default method:
218 We generate a binding for $dmop1 but not for $dmop2.
219 The Class for Foo has a NoDefMeth for op2 and a DefMeth for op1.
220 The Name for $dmop2 is simply discarded.
222 In *interface-file* class declarations:
223 - When parsing, we see if there's an explicit programmer-supplied default method
224 because there's an '=' sign to indicate it:
226 op1 = :: <type> -- NB the '='
228 We use this info to generate a DefMeth with a suitable RdrName for op1,
229 and a NoDefMeth for op2
230 - The interface file has a separate definition for $dmop1, with unfolding etc.
231 - The renamer renames it to a Name.
232 - The renamer treats $dmop1 as a free variable of the declaration, so that
233 the binding for $dmop1 will be sucked in. (See RnHsSyn.tyClDeclFVs)
234 This doesn't happen for source code class decls, because they *bind* the default method.
238 Each instance declaration gives rise to one dictionary function binding.
240 The type checker makes up new source-code instance declarations
241 (e.g. from 'deriving' or generic default methods --- see
242 TcInstDcls.tcInstDecls1). So we can't generate the names for
243 dictionary functions in advance (we don't know how many we need).
245 On the other hand for interface-file instance declarations, the decl
246 specifies the name of the dictionary function, and it has a binding elsewhere
247 in the interface file:
248 instance {Eq Int} = dEqInt
249 dEqInt :: {Eq Int} <pragma info>
251 So again we treat source code and interface file code slightly differently.
254 - Source code instance decls have a Nothing in the (Maybe name) field
255 (see data InstDecl below)
257 - The typechecker makes up a Local name for the dict fun for any source-code
258 instance decl, whether it comes from a source-code instance decl, or whether
259 the instance decl is derived from some other construct (e.g. 'deriving').
261 - The occurrence name it chooses is derived from the instance decl (just for
262 documentation really) --- e.g. dNumInt. Two dict funs may share a common
263 occurrence name, but will have different uniques. E.g.
264 instance Foo [Int] where ...
265 instance Foo [Bool] where ...
266 These might both be dFooList
268 - The CoreTidy phase externalises the name, and ensures the occurrence name is
269 unique (this isn't special to dict funs). So we'd get dFooList and dFooList1.
271 - We can take this relaxed approach (changing the occurrence name later)
272 because dict fun Ids are not captured in a TyCon or Class (unlike default
273 methods, say). Instead, they are kept separately in the InstEnv. This
274 makes it easy to adjust them after compiling a module. (Once we've finished
275 compiling that module, they don't change any more.)
279 - The instance decl gives the dict fun name, so the InstDecl has a (Just name)
280 in the (Maybe name) field.
282 - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
283 suck in the dfun binding
287 -- TyClDecls are precisely the kind of declarations that can
288 -- appear in interface files; or (internally) in GHC's interface
289 -- for a module. That's why (despite the misnomer) IfaceSig and ForeignType
290 -- are both in TyClDecl
292 type LTyClDecl name = Located (TyClDecl name)
296 tcdLName :: Located name,
297 tcdExtName :: Maybe FastString,
301 | TyData { tcdND :: NewOrData,
302 tcdCtxt :: LHsContext name, -- Context
303 tcdLName :: Located name, -- Type constructor
304 tcdTyVars :: [LHsTyVarBndr name], -- Type variables
305 tcdCons :: [LConDecl name], -- Data constructors
306 tcdDerivs :: Maybe [LHsType name]
307 -- Derivings; Nothing => not specified
308 -- Just [] => derive exactly what is asked
309 -- These "types" must be of form
310 -- forall ab. C ty1 ty2
311 -- Typically the foralls and ty args are empty, but they
312 -- are non-empty for the newtype-deriving case
315 | TySynonym { tcdLName :: Located name, -- type constructor
316 tcdTyVars :: [LHsTyVarBndr name], -- type variables
317 tcdSynRhs :: LHsType name -- synonym expansion
320 | ClassDecl { tcdCtxt :: LHsContext name, -- Context...
321 tcdLName :: Located name, -- Name of the class
322 tcdTyVars :: [LHsTyVarBndr name], -- Class type variables
323 tcdFDs :: [Located (FunDep name)], -- Functional deps
324 tcdSigs :: [LSig name], -- Methods' signatures
325 tcdMeths :: LHsBinds name -- Default methods
329 = NewType -- "newtype Blah ..."
330 | DataType -- "data Blah ..."
331 deriving( Eq ) -- Needed because Demand derives Eq
337 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name -> Bool
339 isSynDecl (TySynonym {}) = True
340 isSynDecl other = False
342 isDataDecl (TyData {}) = True
343 isDataDecl other = False
345 isClassDecl (ClassDecl {}) = True
346 isClassDecl other = False
352 tcdName :: TyClDecl name -> name
353 tcdName decl = unLoc (tcdLName decl)
355 tyClDeclNames :: Eq name => TyClDecl name -> [Located name]
356 -- Returns all the *binding* names of the decl, along with their SrcLocs
357 -- The first one is guaranteed to be the name of the decl
358 -- For record fields, the first one counts as the SrcLoc
359 -- We use the equality to filter out duplicate field names
361 tyClDeclNames (TySynonym {tcdLName = name}) = [name]
362 tyClDeclNames (ForeignType {tcdLName = name}) = [name]
364 tyClDeclNames (ClassDecl {tcdLName = cls_name, tcdSigs = sigs})
365 = cls_name : [n | L _ (Sig n _) <- sigs]
367 tyClDeclNames (TyData {tcdLName = tc_name, tcdCons = cons})
368 = tc_name : conDeclsNames (map unLoc cons)
370 tyClDeclTyVars (TySynonym {tcdTyVars = tvs}) = tvs
371 tyClDeclTyVars (TyData {tcdTyVars = tvs}) = tvs
372 tyClDeclTyVars (ClassDecl {tcdTyVars = tvs}) = tvs
373 tyClDeclTyVars (ForeignType {}) = []
377 countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int)
378 -- class, data, newtype, synonym decls
380 = (count isClassDecl decls,
381 count isSynDecl decls,
382 count isDataTy decls,
385 isDataTy TyData{tcdND=DataType} = True
388 isNewTy TyData{tcdND=NewType} = True
393 instance OutputableBndr name
394 => Outputable (TyClDecl name) where
396 ppr (ForeignType {tcdLName = ltycon})
397 = hsep [ptext SLIT("foreign import type dotnet"), ppr ltycon]
399 ppr (TySynonym {tcdLName = ltycon, tcdTyVars = tyvars, tcdSynRhs = mono_ty})
400 = hang (ptext SLIT("type") <+> pp_decl_head [] ltycon tyvars <+> equals)
403 ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdLName = ltycon,
404 tcdTyVars = tyvars, tcdCons = condecls,
405 tcdDerivs = derivings})
406 = pp_tydecl (ppr new_or_data <+> pp_decl_head (unLoc context) ltycon tyvars)
407 (pp_condecls condecls)
410 ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars, tcdFDs = fds,
411 tcdSigs = sigs, tcdMeths = methods})
412 | null sigs -- No "where" part
415 | otherwise -- Laid out
416 = sep [hsep [top_matter, ptext SLIT("where {")],
417 nest 4 (sep [sep (map ppr_sig sigs), ppr methods, char '}'])]
419 top_matter = ptext SLIT("class") <+> pp_decl_head (unLoc context) lclas tyvars <+> pprFundeps (map unLoc fds)
420 ppr_sig sig = ppr sig <> semi
422 pp_decl_head :: OutputableBndr name
425 -> [LHsTyVarBndr name]
427 pp_decl_head context thing tyvars
428 = hsep [pprHsContext context, ppr thing, interppSP tyvars]
430 pp_condecls cs@(L _ (GadtDecl _ _) : _) -- In GADT syntax
431 = hang (ptext SLIT("where")) 2 (vcat (map ppr cs))
432 pp_condecls cs -- In H98 syntax
433 = equals <+> sep (punctuate (ptext SLIT(" |")) (map ppr cs))
435 pp_tydecl pp_head pp_decl_rhs derivings
436 = hang pp_head 4 (sep [
440 Just ds -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
443 instance Outputable NewOrData where
444 ppr NewType = ptext SLIT("newtype")
445 ppr DataType = ptext SLIT("data")
449 %************************************************************************
451 \subsection[ConDecl]{A data-constructor declaration}
453 %************************************************************************
456 type LConDecl name = Located (ConDecl name)
459 = ConDecl (Located name) -- Constructor name; this is used for the
460 -- DataCon itself, and for the user-callable wrapper Id
462 [LHsTyVarBndr name] -- Existentially quantified type variables
463 (LHsContext name) -- ...and context
464 -- If both are empty then there are no existentials
465 (HsConDetails name (LBangType name))
467 | GadtDecl (Located name) -- Constructor name; this is used for the
468 -- DataCon itself, and for the user-callable wrapper Id
469 (LHsType name) -- Constructor type; it may have HsBangs on the
474 conDeclsNames :: Eq name => [ConDecl name] -> [Located name]
475 -- See tyClDeclNames for what this does
476 -- The function is boringly complicated because of the records
477 -- And since we only have equality, we have to be a little careful
479 = snd (foldl do_one ([], []) cons)
481 do_one (flds_seen, acc) (ConDecl lname _ _ (RecCon flds))
482 = (map unLoc new_flds ++ flds_seen, lname : [f | f <- new_flds] ++ acc)
484 new_flds = [ f | (f,_) <- flds, not (unLoc f `elem` flds_seen) ]
486 do_one (flds_seen, acc) (ConDecl lname _ _ _)
487 = (flds_seen, lname:acc)
490 do_one (flds_seen, acc) (GadtDecl lname _)
491 = (flds_seen, lname:acc)
493 conDetailsTys details = map getBangType (hsConArgs details)
498 instance (OutputableBndr name) => Outputable (ConDecl name) where
499 ppr (ConDecl con tvs cxt con_details)
500 = sep [pprHsForAll Explicit tvs cxt, ppr_con_details con con_details]
501 ppr (GadtDecl con ty)
502 = ppr con <+> dcolon <+> ppr ty
504 ppr_con_details con (InfixCon ty1 ty2)
505 = hsep [ppr ty1, pprHsVar con, ppr ty2]
507 -- ConDecls generated by MkIface.ifaceTyThing always have a PrefixCon, even
508 -- if the constructor is an infix one. This is because in an interface file
509 -- we don't distinguish between the two. Hence when printing these for the
510 -- user, we need to parenthesise infix constructor names.
511 ppr_con_details con (PrefixCon tys)
512 = hsep (pprHsVar con : map ppr tys)
514 ppr_con_details con (RecCon fields)
515 = ppr con <+> braces (sep (punctuate comma (map ppr_field fields)))
517 ppr_field (n, ty) = ppr n <+> dcolon <+> ppr ty
521 %************************************************************************
523 \subsection[InstDecl]{An instance declaration
525 %************************************************************************
528 type LInstDecl name = Located (InstDecl name)
531 = InstDecl (LHsType name) -- Context => Class Instance-type
532 -- Using a polytype means that the renamer conveniently
533 -- figures out the quantified type variables for us.
535 [LSig name] -- User-supplied pragmatic info
537 instance (OutputableBndr name) => Outputable (InstDecl name) where
539 ppr (InstDecl inst_ty binds uprags)
540 = vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
542 nest 4 (pprLHsBinds binds) ]
545 %************************************************************************
547 \subsection[DefaultDecl]{A @default@ declaration}
549 %************************************************************************
551 There can only be one default declaration per module, but it is hard
552 for the parser to check that; we pass them all through in the abstract
553 syntax, and that restriction must be checked in the front end.
556 type LDefaultDecl name = Located (DefaultDecl name)
558 data DefaultDecl name
559 = DefaultDecl [LHsType name]
561 instance (OutputableBndr name)
562 => Outputable (DefaultDecl name) where
564 ppr (DefaultDecl tys)
565 = ptext SLIT("default") <+> parens (interpp'SP tys)
568 %************************************************************************
570 \subsection{Foreign function interface declaration}
572 %************************************************************************
576 -- foreign declarations are distinguished as to whether they define or use a
579 -- * the Boolean value indicates whether the pre-standard deprecated syntax
582 type LForeignDecl name = Located (ForeignDecl name)
584 data ForeignDecl name
585 = ForeignImport (Located name) (LHsType name) ForeignImport Bool -- defines name
586 | ForeignExport (Located name) (LHsType name) ForeignExport Bool -- uses name
588 -- specification of an imported external entity in dependence on the calling
591 data ForeignImport = -- import of a C entity
593 -- * the two strings specifying a header file or library
594 -- may be empty, which indicates the absence of a
595 -- header or object specification (both are not used
596 -- in the case of `CWrapper' and when `CFunction'
597 -- has a dynamic target)
599 -- * the calling convention is irrelevant for code
600 -- generation in the case of `CLabel', but is needed
601 -- for pretty printing
603 -- * `Safety' is irrelevant for `CLabel' and `CWrapper'
605 CImport CCallConv -- ccall or stdcall
606 Safety -- safe or unsafe
607 FastString -- name of C header
608 FastString -- name of library object
609 CImportSpec -- details of the C entity
611 -- import of a .NET function
613 | DNImport DNCallSpec
615 -- details of an external C entity
617 data CImportSpec = CLabel CLabelString -- import address of a C label
618 | CFunction CCallTarget -- static or dynamic function
619 | CWrapper -- wrapper to expose closures
622 -- specification of an externally exported entity in dependence on the calling
625 data ForeignExport = CExport CExportSpec -- contains the calling convention
626 | DNExport -- presently unused
628 -- abstract type imported from .NET
630 data FoType = DNType -- In due course we'll add subtype stuff
631 deriving (Eq) -- Used for equality instance for TyClDecl
634 -- pretty printing of foreign declarations
637 instance OutputableBndr name => Outputable (ForeignDecl name) where
638 ppr (ForeignImport n ty fimport _) =
639 ptext SLIT("foreign import") <+> ppr fimport <+>
640 ppr n <+> dcolon <+> ppr ty
641 ppr (ForeignExport n ty fexport _) =
642 ptext SLIT("foreign export") <+> ppr fexport <+>
643 ppr n <+> dcolon <+> ppr ty
645 instance Outputable ForeignImport where
646 ppr (DNImport spec) =
647 ptext SLIT("dotnet") <+> ppr spec
648 ppr (CImport cconv safety header lib spec) =
649 ppr cconv <+> ppr safety <+>
650 char '"' <> pprCEntity header lib spec <> char '"'
652 pprCEntity header lib (CLabel lbl) =
653 ptext SLIT("static") <+> ftext header <+> char '&' <>
654 pprLib lib <> ppr lbl
655 pprCEntity header lib (CFunction (StaticTarget lbl)) =
656 ptext SLIT("static") <+> ftext header <+> char '&' <>
657 pprLib lib <> ppr lbl
658 pprCEntity header lib (CFunction (DynamicTarget)) =
659 ptext SLIT("dynamic")
660 pprCEntity _ _ (CWrapper) = ptext SLIT("wrapper")
662 pprLib lib | nullFastString lib = empty
663 | otherwise = char '[' <> ppr lib <> char ']'
665 instance Outputable ForeignExport where
666 ppr (CExport (CExportStatic lbl cconv)) =
667 ppr cconv <+> char '"' <> ppr lbl <> char '"'
669 ptext SLIT("dotnet") <+> ptext SLIT("\"<unused>\"")
671 instance Outputable FoType where
672 ppr DNType = ptext SLIT("type dotnet")
676 %************************************************************************
678 \subsection{Transformation rules}
680 %************************************************************************
683 type LRuleDecl name = Located (RuleDecl name)
686 = HsRule -- Source rule
687 RuleName -- Rule name
689 [RuleBndr name] -- Forall'd vars; after typechecking this includes tyvars
690 (Located (HsExpr name)) -- LHS
691 (Located (HsExpr name)) -- RHS
694 = RuleBndr (Located name)
695 | RuleBndrSig (Located name) (LHsType name)
697 collectRuleBndrSigTys :: [RuleBndr name] -> [LHsType name]
698 collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs]
700 instance OutputableBndr name => Outputable (RuleDecl name) where
701 ppr (HsRule name act ns lhs rhs)
702 = sep [text "{-# RULES" <+> doubleQuotes (ftext name) <+> ppr act,
703 nest 4 (pp_forall <+> pprExpr (unLoc lhs)),
704 nest 4 (equals <+> pprExpr (unLoc rhs) <+> text "#-}") ]
706 pp_forall | null ns = empty
707 | otherwise = text "forall" <+> fsep (map ppr ns) <> dot
709 instance OutputableBndr name => Outputable (RuleBndr name) where
710 ppr (RuleBndr name) = ppr name
711 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
715 %************************************************************************
717 \subsection[DeprecDecl]{Deprecations}
719 %************************************************************************
721 We use exported entities for things to deprecate.
724 type LDeprecDecl name = Located (DeprecDecl name)
726 data DeprecDecl name = Deprecation name DeprecTxt
728 instance OutputableBndr name => Outputable (DeprecDecl name) where
729 ppr (Deprecation thing txt)
730 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]