2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
9 {-# OPTIONS -fno-warn-incomplete-patterns #-}
10 -- The above warning supression flag is a temporary kludge.
11 -- While working on this module you are encouraged to remove it and fix
12 -- any warnings in the module. See
13 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
15 {-# LANGUAGE DeriveDataTypeable #-}
17 -- | Abstract syntax of global declarations.
19 -- Definitions for: @TyDecl@ and @ConDecl@, @ClassDecl@,
20 -- @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
22 -- * Toplevel declarations
24 -- ** Class or type declarations
25 TyClDecl(..), LTyClDecl,
26 isClassDecl, isSynDecl, isDataDecl, isTypeDecl, isFamilyDecl,
27 isFamInstDecl, tcdName, tyClDeclNames, tyClDeclTyVars,
29 -- ** Instance declarations
30 InstDecl(..), LInstDecl, NewOrData(..), FamilyFlavour(..),
32 -- ** Standalone deriving declarations
33 DerivDecl(..), LDerivDecl,
34 -- ** @RULE@ declarations
35 RuleDecl(..), LRuleDecl, RuleBndr(..),
36 collectRuleBndrSigTys,
37 -- ** @default@ declarations
38 DefaultDecl(..), LDefaultDecl,
39 -- ** Top-level template haskell splice
41 -- ** Foreign function interface declarations
42 ForeignDecl(..), LForeignDecl, ForeignImport(..), ForeignExport(..),
44 -- ** Data-constructor declarations
45 ConDecl(..), LConDecl, ResType(..),
46 HsConDeclDetails, hsConDeclArgTys, hsConDeclsNames,
47 -- ** Document comments
48 DocDecl(..), LDocDecl, docDeclDoc,
50 WarnDecl(..), LWarnDecl,
52 AnnDecl(..), LAnnDecl,
53 AnnProvenance(..), annProvenanceName_maybe, modifyAnnProvenanceNameM,
56 HsGroup(..), emptyRdrGroup, emptyRnGroup, appendGroups
60 import {-# SOURCE #-} HsExpr( HsExpr, pprExpr )
61 -- Because Expr imports Decls via HsBracket
68 import {- Kind parts of -} Type
79 import Control.Monad ( liftM )
81 import Data.Maybe ( isJust )
84 %************************************************************************
86 \subsection[HsDecl]{Declarations}
88 %************************************************************************
91 type LHsDecl id = Located (HsDecl id)
93 -- | A Haskell Declaration
95 = TyClD (TyClDecl id) -- ^ A type or class declaration.
96 | InstD (InstDecl id) -- ^ An instance declaration.
97 | DerivD (DerivDecl id)
100 | DefD (DefaultDecl id)
101 | ForD (ForeignDecl id)
102 | WarningD (WarnDecl id)
104 | RuleD (RuleDecl id)
105 | SpliceD (SpliceDecl id)
107 | QuasiQuoteD (HsQuasiQuote id)
108 deriving (Data, Typeable)
111 -- NB: all top-level fixity decls are contained EITHER
113 -- OR in the ClassDecls in TyClDs
116 -- a) data constructors
117 -- b) class methods (but they can be also done in the
118 -- signatures of class decls)
119 -- c) imported functions (that have an IfacSig)
120 -- d) top level decls
122 -- The latter is for class methods only
124 -- | A 'HsDecl' is categorised into a 'HsGroup' before being
125 -- fed to the renamer.
128 hs_valds :: HsValBinds id,
129 hs_tyclds :: [LTyClDecl id],
130 hs_instds :: [LInstDecl id],
131 hs_derivds :: [LDerivDecl id],
133 hs_fixds :: [LFixitySig id],
134 -- Snaffled out of both top-level fixity signatures,
135 -- and those in class declarations
137 hs_defds :: [LDefaultDecl id],
138 hs_fords :: [LForeignDecl id],
139 hs_warnds :: [LWarnDecl id],
140 hs_annds :: [LAnnDecl id],
141 hs_ruleds :: [LRuleDecl id],
143 hs_docs :: [LDocDecl]
144 } deriving (Data, Typeable)
146 emptyGroup, emptyRdrGroup, emptyRnGroup :: HsGroup a
147 emptyRdrGroup = emptyGroup { hs_valds = emptyValBindsIn }
148 emptyRnGroup = emptyGroup { hs_valds = emptyValBindsOut }
150 emptyGroup = HsGroup { hs_tyclds = [], hs_instds = [], hs_derivds = [],
151 hs_fixds = [], hs_defds = [], hs_annds = [],
152 hs_fords = [], hs_warnds = [], hs_ruleds = [],
153 hs_valds = error "emptyGroup hs_valds: Can't happen",
156 appendGroups :: HsGroup a -> HsGroup a -> HsGroup a
159 hs_valds = val_groups1,
162 hs_derivds = derivds1,
171 hs_valds = val_groups2,
174 hs_derivds = derivds2,
184 hs_valds = val_groups1 `plusHsValBinds` val_groups2,
185 hs_tyclds = tyclds1 ++ tyclds2,
186 hs_instds = instds1 ++ instds2,
187 hs_derivds = derivds1 ++ derivds2,
188 hs_fixds = fixds1 ++ fixds2,
189 hs_annds = annds1 ++ annds2,
190 hs_defds = defds1 ++ defds2,
191 hs_fords = fords1 ++ fords2,
192 hs_warnds = warnds1 ++ warnds2,
193 hs_ruleds = rulds1 ++ rulds2,
194 hs_docs = docs1 ++ docs2 }
198 instance OutputableBndr name => Outputable (HsDecl name) where
199 ppr (TyClD dcl) = ppr dcl
200 ppr (ValD binds) = ppr binds
201 ppr (DefD def) = ppr def
202 ppr (InstD inst) = ppr inst
203 ppr (DerivD deriv) = ppr deriv
204 ppr (ForD fd) = ppr fd
205 ppr (SigD sd) = ppr sd
206 ppr (RuleD rd) = ppr rd
207 ppr (WarningD wd) = ppr wd
208 ppr (AnnD ad) = ppr ad
209 ppr (SpliceD dd) = ppr dd
210 ppr (DocD doc) = ppr doc
211 ppr (QuasiQuoteD qq) = ppr qq
213 instance OutputableBndr name => Outputable (HsGroup name) where
214 ppr (HsGroup { hs_valds = val_decls,
215 hs_tyclds = tycl_decls,
216 hs_instds = inst_decls,
217 hs_derivds = deriv_decls,
218 hs_fixds = fix_decls,
219 hs_warnds = deprec_decls,
220 hs_annds = ann_decls,
221 hs_fords = foreign_decls,
222 hs_defds = default_decls,
223 hs_ruleds = rule_decls })
224 = vcat [ppr_ds fix_decls, ppr_ds default_decls,
225 ppr_ds deprec_decls, ppr_ds ann_decls,
228 ppr_ds tycl_decls, ppr_ds inst_decls,
230 ppr_ds foreign_decls]
233 ppr_ds ds = blankLine $$ vcat (map ppr ds)
236 = SpliceDecl -- Top level splice
237 (Located (HsExpr id))
238 HsExplicitFlag -- Explicit <=> $(f x y)
239 -- Implicit <=> f x y, i.e. a naked top level expression
240 deriving (Data, Typeable)
242 instance OutputableBndr name => Outputable (SpliceDecl name) where
243 ppr (SpliceDecl e _) = ptext (sLit "$") <> parens (pprExpr (unLoc e))
247 %************************************************************************
249 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
251 %************************************************************************
253 --------------------------------
255 --------------------------------
257 Here is the story about the implicit names that go with type, class,
258 and instance decls. It's a bit tricky, so pay attention!
260 "Implicit" (or "system") binders
261 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
262 Each data type decl defines
263 a worker name for each constructor
264 to-T and from-T convertors
265 Each class decl defines
266 a tycon for the class
267 a data constructor for that tycon
268 the worker for that constructor
269 a selector for each superclass
271 All have occurrence names that are derived uniquely from their parent
274 None of these get separate definitions in an interface file; they are
275 fully defined by the data or class decl. But they may *occur* in
276 interface files, of course. Any such occurrence must haul in the
277 relevant type or class decl.
280 - Ensure they "point to" the parent data/class decl
281 when loading that decl from an interface file
282 (See RnHiFiles.getSysBinders)
284 - When typechecking the decl, we build the implicit TyCons and Ids.
285 When doing so we look them up in the name cache (RnEnv.lookupSysName),
286 to ensure correct module and provenance is set
288 These are the two places that we have to conjure up the magic derived
289 names. (The actual magic is in OccName.mkWorkerOcc, etc.)
293 - Occurrence name is derived uniquely from the method name
296 - If there is a default method name at all, it's recorded in
297 the ClassOpSig (in HsBinds), in the DefMeth field.
298 (DefMeth is defined in Class.lhs)
300 Source-code class decls and interface-code class decls are treated subtly
301 differently, which has given me a great deal of confusion over the years.
302 Here's the deal. (We distinguish the two cases because source-code decls
303 have (Just binds) in the tcdMeths field, whereas interface decls have Nothing.
305 In *source-code* class declarations:
307 - When parsing, every ClassOpSig gets a DefMeth with a suitable RdrName
308 This is done by RdrHsSyn.mkClassOpSigDM
310 - The renamer renames it to a Name
312 - During typechecking, we generate a binding for each $dm for
313 which there's a programmer-supplied default method:
318 We generate a binding for $dmop1 but not for $dmop2.
319 The Class for Foo has a NoDefMeth for op2 and a DefMeth for op1.
320 The Name for $dmop2 is simply discarded.
322 In *interface-file* class declarations:
323 - When parsing, we see if there's an explicit programmer-supplied default method
324 because there's an '=' sign to indicate it:
326 op1 = :: <type> -- NB the '='
328 We use this info to generate a DefMeth with a suitable RdrName for op1,
329 and a NoDefMeth for op2
330 - The interface file has a separate definition for $dmop1, with unfolding etc.
331 - The renamer renames it to a Name.
332 - The renamer treats $dmop1 as a free variable of the declaration, so that
333 the binding for $dmop1 will be sucked in. (See RnHsSyn.tyClDeclFVs)
334 This doesn't happen for source code class decls, because they *bind* the default method.
338 Each instance declaration gives rise to one dictionary function binding.
340 The type checker makes up new source-code instance declarations
341 (e.g. from 'deriving' or generic default methods --- see
342 TcInstDcls.tcInstDecls1). So we can't generate the names for
343 dictionary functions in advance (we don't know how many we need).
345 On the other hand for interface-file instance declarations, the decl
346 specifies the name of the dictionary function, and it has a binding elsewhere
347 in the interface file:
348 instance {Eq Int} = dEqInt
349 dEqInt :: {Eq Int} <pragma info>
351 So again we treat source code and interface file code slightly differently.
354 - Source code instance decls have a Nothing in the (Maybe name) field
355 (see data InstDecl below)
357 - The typechecker makes up a Local name for the dict fun for any source-code
358 instance decl, whether it comes from a source-code instance decl, or whether
359 the instance decl is derived from some other construct (e.g. 'deriving').
361 - The occurrence name it chooses is derived from the instance decl (just for
362 documentation really) --- e.g. dNumInt. Two dict funs may share a common
363 occurrence name, but will have different uniques. E.g.
364 instance Foo [Int] where ...
365 instance Foo [Bool] where ...
366 These might both be dFooList
368 - The CoreTidy phase externalises the name, and ensures the occurrence name is
369 unique (this isn't special to dict funs). So we'd get dFooList and dFooList1.
371 - We can take this relaxed approach (changing the occurrence name later)
372 because dict fun Ids are not captured in a TyCon or Class (unlike default
373 methods, say). Instead, they are kept separately in the InstEnv. This
374 makes it easy to adjust them after compiling a module. (Once we've finished
375 compiling that module, they don't change any more.)
379 - The instance decl gives the dict fun name, so the InstDecl has a (Just name)
380 in the (Maybe name) field.
382 - RnHsSyn.instDeclFVs treats the dict fun name as free in the decl, so that we
383 suck in the dfun binding
387 -- Representation of indexed types
388 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
389 -- Family kind signatures are represented by the variant `TyFamily'. It
390 -- covers "type family", "newtype family", and "data family" declarations,
391 -- distinguished by the value of the field `tcdFlavour'.
393 -- Indexed types are represented by 'TyData' and 'TySynonym' using the field
394 -- 'tcdTyPats::Maybe [LHsType name]', with the following meaning:
396 -- * If it is 'Nothing', we have a *vanilla* data type declaration or type
397 -- synonym declaration and 'tcdVars' contains the type parameters of the
400 -- * If it is 'Just pats', we have the definition of an indexed type. Then,
401 -- 'pats' are type patterns for the type-indexes of the type constructor
402 -- and 'tcdTyVars' are the variables in those patterns. Hence, the arity of
403 -- the indexed type (ie, the number of indexes) is 'length tcdTyPats' and
404 -- *not* 'length tcdVars'.
406 -- In both cases, 'tcdVars' collects all variables we need to quantify over.
408 type LTyClDecl name = Located (TyClDecl name)
410 -- | A type or class declaration.
413 tcdLName :: Located name,
414 tcdExtName :: Maybe FastString
418 | -- | @type/data family T :: *->*@
419 TyFamily { tcdFlavour:: FamilyFlavour, -- type or data
420 tcdLName :: Located name, -- type constructor
421 tcdTyVars :: [LHsTyVarBndr name], -- type variables
422 tcdKind :: Maybe Kind -- result kind
426 | -- | Declares a data type or newtype, giving its construcors
428 -- data/newtype T a = <constrs>
429 -- data/newtype instance T [a] = <constrs>
431 TyData { tcdND :: NewOrData,
432 tcdCtxt :: LHsContext name, -- ^ Context
433 tcdLName :: Located name, -- ^ Type constructor
435 tcdTyVars :: [LHsTyVarBndr name], -- ^ Type variables
437 tcdTyPats :: Maybe [LHsType name],
440 -- @Just [t1..tn]@ for @data instance T t1..tn = ...@
441 -- in this case @tcdTyVars = fv( tcdTyPats )@.
442 -- @Nothing@ for everything else.
444 tcdKindSig:: Maybe Kind,
445 -- ^ Optional kind signature.
447 -- @(Just k)@ for a GADT-style @data@, or @data
448 -- instance@ decl with explicit kind sig
450 tcdCons :: [LConDecl name],
451 -- ^ Data constructors
453 -- For @data T a = T1 | T2 a@
454 -- the 'LConDecl's all have 'ResTyH98'.
455 -- For @data T a where { T1 :: T a }@
456 -- the 'LConDecls' all have 'ResTyGADT'.
458 tcdDerivs :: Maybe [LHsType name]
459 -- ^ Derivings; @Nothing@ => not specified,
460 -- @Just []@ => derive exactly what is asked
462 -- These "types" must be of form
464 -- forall ab. C ty1 ty2
466 -- Typically the foralls and ty args are empty, but they
467 -- are non-empty for the newtype-deriving case
470 | TySynonym { tcdLName :: Located name, -- ^ type constructor
471 tcdTyVars :: [LHsTyVarBndr name], -- ^ type variables
472 tcdTyPats :: Maybe [LHsType name], -- ^ Type patterns
473 -- See comments for tcdTyPats in TyData
474 -- 'Nothing' => vanilla type synonym
476 tcdSynRhs :: LHsType name -- ^ synonym expansion
479 | ClassDecl { tcdCtxt :: LHsContext name, -- ^ Context...
480 tcdLName :: Located name, -- ^ Name of the class
481 tcdTyVars :: [LHsTyVarBndr name], -- ^ Class type variables
482 tcdFDs :: [Located (FunDep name)], -- ^ Functional deps
483 tcdSigs :: [LSig name], -- ^ Methods' signatures
484 tcdMeths :: LHsBinds name, -- ^ Default methods
485 tcdATs :: [LTyClDecl name], -- ^ Associated types; ie
486 -- only 'TyFamily' and
488 -- latter for defaults
489 tcdDocs :: [LDocDecl] -- ^ Haddock docs
491 deriving (Data, Typeable)
494 = NewType -- ^ @newtype Blah ...@
495 | DataType -- ^ @data Blah ...@
496 deriving( Eq, Data, Typeable ) -- Needed because Demand derives Eq
499 = TypeFamily -- ^ @type family ...@
500 | DataFamily -- ^ @data family ...@
501 deriving (Data, Typeable)
507 -- | @True@ <=> argument is a @data@\/@newtype@ or @data@\/@newtype instance@
509 isDataDecl :: TyClDecl name -> Bool
510 isDataDecl (TyData {}) = True
511 isDataDecl _other = False
513 -- | type or type instance declaration
514 isTypeDecl :: TyClDecl name -> Bool
515 isTypeDecl (TySynonym {}) = True
516 isTypeDecl _other = False
518 -- | vanilla Haskell type synonym (ie, not a type instance)
519 isSynDecl :: TyClDecl name -> Bool
520 isSynDecl (TySynonym {tcdTyPats = Nothing}) = True
521 isSynDecl _other = False
524 isClassDecl :: TyClDecl name -> Bool
525 isClassDecl (ClassDecl {}) = True
526 isClassDecl _ = False
528 -- | type family declaration
529 isFamilyDecl :: TyClDecl name -> Bool
530 isFamilyDecl (TyFamily {}) = True
531 isFamilyDecl _other = False
533 -- | family instance (types, newtypes, and data types)
534 isFamInstDecl :: TyClDecl name -> Bool
537 || isDataDecl tydecl = isJust (tcdTyPats tydecl)
544 tcdName :: TyClDecl name -> name
545 tcdName decl = unLoc (tcdLName decl)
547 tyClDeclNames :: Eq name => TyClDecl name -> [Located name]
548 -- ^ Returns all the /binding/ names of the decl, along with their SrcLocs.
549 -- The first one is guaranteed to be the name of the decl. For record fields
550 -- mentioned in multiple constructors, the SrcLoc will be from the first
551 -- occurence. We use the equality to filter out duplicate field names
553 tyClDeclNames (TyFamily {tcdLName = name}) = [name]
554 tyClDeclNames (TySynonym {tcdLName = name}) = [name]
555 tyClDeclNames (ForeignType {tcdLName = name}) = [name]
557 tyClDeclNames (ClassDecl {tcdLName = cls_name, tcdSigs = sigs, tcdATs = ats})
559 concatMap (tyClDeclNames . unLoc) ats ++ [n | L _ (TypeSig n _) <- sigs]
561 tyClDeclNames (TyData {tcdLName = tc_name, tcdCons = cons})
562 = tc_name : hsConDeclsNames cons
564 tyClDeclTyVars :: TyClDecl name -> [LHsTyVarBndr name]
565 tyClDeclTyVars (TyFamily {tcdTyVars = tvs}) = tvs
566 tyClDeclTyVars (TySynonym {tcdTyVars = tvs}) = tvs
567 tyClDeclTyVars (TyData {tcdTyVars = tvs}) = tvs
568 tyClDeclTyVars (ClassDecl {tcdTyVars = tvs}) = tvs
569 tyClDeclTyVars (ForeignType {}) = []
573 countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int, Int, Int)
574 -- class, synonym decls, data, newtype, family decls, family instances
576 = (count isClassDecl decls,
577 count isSynDecl decls, -- excluding...
578 count isDataTy decls, -- ...family...
579 count isNewTy decls, -- ...instances
580 count isFamilyDecl decls,
581 count isFamInstDecl decls)
583 isDataTy TyData{tcdND = DataType, tcdTyPats = Nothing} = True
586 isNewTy TyData{tcdND = NewType, tcdTyPats = Nothing} = True
591 instance OutputableBndr name
592 => Outputable (TyClDecl name) where
594 ppr (ForeignType {tcdLName = ltycon})
595 = hsep [ptext (sLit "foreign import type dotnet"), ppr ltycon]
597 ppr (TyFamily {tcdFlavour = flavour, tcdLName = ltycon,
598 tcdTyVars = tyvars, tcdKind = mb_kind})
599 = pp_flavour <+> pp_decl_head [] ltycon tyvars Nothing <+> pp_kind
601 pp_flavour = case flavour of
602 TypeFamily -> ptext (sLit "type family")
603 DataFamily -> ptext (sLit "data family")
605 pp_kind = case mb_kind of
607 Just kind -> dcolon <+> pprKind kind
609 ppr (TySynonym {tcdLName = ltycon, tcdTyVars = tyvars, tcdTyPats = typats,
610 tcdSynRhs = mono_ty})
611 = hang (ptext (sLit "type") <+>
612 (if isJust typats then ptext (sLit "instance") else empty) <+>
613 pp_decl_head [] ltycon tyvars typats <+>
617 ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdLName = ltycon,
618 tcdTyVars = tyvars, tcdTyPats = typats, tcdKindSig = mb_sig,
619 tcdCons = condecls, tcdDerivs = derivings})
620 = pp_tydecl (null condecls && isJust mb_sig)
622 (if isJust typats then ptext (sLit "instance") else empty) <+>
623 pp_decl_head (unLoc context) ltycon tyvars typats <+>
625 (pp_condecls condecls)
628 ppr_sig Nothing = empty
629 ppr_sig (Just kind) = dcolon <+> pprKind kind
631 ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
633 tcdSigs = sigs, tcdMeths = methods, tcdATs = ats})
634 | null sigs && null ats -- No "where" part
637 | otherwise -- Laid out
638 = sep [hsep [top_matter, ptext (sLit "where {")],
639 nest 4 (sep [ sep (map ppr_semi ats)
640 , sep (map ppr_semi sigs)
641 , pprLHsBinds methods
644 top_matter = ptext (sLit "class")
645 <+> pp_decl_head (unLoc context) lclas tyvars Nothing
646 <+> pprFundeps (map unLoc fds)
647 ppr_semi decl = ppr decl <> semi
649 pp_decl_head :: OutputableBndr name
652 -> [LHsTyVarBndr name]
653 -> Maybe [LHsType name]
655 pp_decl_head context thing tyvars Nothing -- no explicit type patterns
656 = hsep [pprHsContext context, ppr thing, interppSP tyvars]
657 pp_decl_head context thing _ (Just typats) -- explicit type patterns
658 = hsep [ pprHsContext context, ppr thing
659 , hsep (map (pprParendHsType.unLoc) typats)]
661 pp_condecls :: OutputableBndr name => [LConDecl name] -> SDoc
662 pp_condecls cs@(L _ ConDecl{ con_res = ResTyGADT _ } : _) -- In GADT syntax
663 = hang (ptext (sLit "where")) 2 (vcat (map ppr cs))
664 pp_condecls cs -- In H98 syntax
665 = equals <+> sep (punctuate (ptext (sLit " |")) (map ppr cs))
667 pp_tydecl :: OutputableBndr name => Bool -> SDoc -> SDoc -> Maybe [LHsType name] -> SDoc
668 pp_tydecl True pp_head _ _
670 pp_tydecl False pp_head pp_decl_rhs derivings
671 = hang pp_head 4 (sep [
675 Just ds -> hsep [ptext (sLit "deriving"), parens (interpp'SP ds)]
678 instance Outputable NewOrData where
679 ppr NewType = ptext (sLit "newtype")
680 ppr DataType = ptext (sLit "data")
684 %************************************************************************
686 \subsection[ConDecl]{A data-constructor declaration}
688 %************************************************************************
691 type LConDecl name = Located (ConDecl name)
693 -- data T b = forall a. Eq a => MkT a b
694 -- MkT :: forall b a. Eq a => MkT a b
697 -- MkT1 :: Int -> T Int
699 -- data T = Int `MkT` Int
703 -- Int `MkT` Int :: T Int
707 { con_name :: Located name
708 -- ^ Constructor name. This is used for the DataCon itself, and for
709 -- the user-callable wrapper Id.
711 , con_explicit :: HsExplicitFlag
712 -- ^ Is there an user-written forall? (cf. 'HsTypes.HsForAllTy')
714 , con_qvars :: [LHsTyVarBndr name]
715 -- ^ Type variables. Depending on 'con_res' this describes the
716 -- follewing entities
718 -- - ResTyH98: the constructor's *existential* type variables
719 -- - ResTyGADT: *all* the constructor's quantified type variables
721 , con_cxt :: LHsContext name
722 -- ^ The context. This /does not/ include the \"stupid theta\" which
723 -- lives only in the 'TyData' decl.
725 , con_details :: HsConDeclDetails name
726 -- ^ The main payload
728 , con_res :: ResType name
729 -- ^ Result type of the constructor
731 , con_doc :: Maybe LHsDocString
732 -- ^ A possible Haddock comment.
734 , con_old_rec :: Bool
735 -- ^ TEMPORARY field; True <=> user has employed now-deprecated syntax for
736 -- GADT-style record decl C { blah } :: T a b
737 -- Remove this when we no longer parse this stuff, and hence do not
738 -- need to report decprecated use
739 } deriving (Data, Typeable)
741 type HsConDeclDetails name = HsConDetails (LBangType name) [ConDeclField name]
743 hsConDeclArgTys :: HsConDeclDetails name -> [LBangType name]
744 hsConDeclArgTys (PrefixCon tys) = tys
745 hsConDeclArgTys (InfixCon ty1 ty2) = [ty1,ty2]
746 hsConDeclArgTys (RecCon flds) = map cd_fld_type flds
749 = ResTyH98 -- Constructor was declared using Haskell 98 syntax
750 | ResTyGADT (LHsType name) -- Constructor was declared using GADT-style syntax,
751 -- and here is its result type
752 deriving (Data, Typeable)
754 instance OutputableBndr name => Outputable (ResType name) where
756 ppr ResTyH98 = ptext (sLit "ResTyH98")
757 ppr (ResTyGADT ty) = ptext (sLit "ResTyGADT") <+> pprParendHsType (unLoc ty)
761 hsConDeclsNames :: (Eq name) => [LConDecl name] -> [Located name]
762 -- See tyClDeclNames for what this does
763 -- The function is boringly complicated because of the records
764 -- And since we only have equality, we have to be a little careful
766 = snd (foldl do_one ([], []) cons)
768 do_one (flds_seen, acc) (L _ (ConDecl { con_name = lname, con_details = RecCon flds }))
769 = (map unLoc new_flds ++ flds_seen, lname : new_flds ++ acc)
771 new_flds = filterOut (\f -> unLoc f `elem` flds_seen)
772 (map cd_fld_name flds)
774 do_one (flds_seen, acc) (L _ (ConDecl { con_name = lname }))
775 = (flds_seen, lname:acc)
780 instance (OutputableBndr name) => Outputable (ConDecl name) where
783 pprConDecl :: OutputableBndr name => ConDecl name -> SDoc
784 pprConDecl (ConDecl { con_name =con, con_explicit = expl, con_qvars = tvs
785 , con_cxt = cxt, con_details = details
786 , con_res = ResTyH98, con_doc = doc })
787 = sep [ppr_mbDoc doc, pprHsForAll expl tvs cxt, ppr_details con details]
789 ppr_details con (InfixCon t1 t2) = hsep [ppr t1, pprHsInfix con, ppr t2]
790 ppr_details con (PrefixCon tys) = hsep (pprHsVar con : map ppr tys)
791 ppr_details con (RecCon fields) = ppr con <+> pprConDeclFields fields
793 pprConDecl (ConDecl { con_name = con, con_explicit = expl, con_qvars = tvs
794 , con_cxt = cxt, con_details = PrefixCon arg_tys
795 , con_res = ResTyGADT res_ty })
796 = ppr con <+> dcolon <+>
797 sep [pprHsForAll expl tvs cxt, ppr (foldr mk_fun_ty res_ty arg_tys)]
799 mk_fun_ty a b = noLoc (HsFunTy a b)
801 pprConDecl (ConDecl { con_name = con, con_explicit = expl, con_qvars = tvs
802 , con_cxt = cxt, con_details = RecCon fields, con_res = ResTyGADT res_ty })
803 = sep [ppr con <+> dcolon <+> pprHsForAll expl tvs cxt,
804 pprConDeclFields fields <+> arrow <+> ppr res_ty]
806 pprConDecl (ConDecl {con_name = con, con_details = InfixCon {}, con_res = ResTyGADT {} })
807 = pprPanic "pprConDecl" (ppr con)
808 -- In GADT syntax we don't allow infix constructors
811 %************************************************************************
813 \subsection[InstDecl]{An instance declaration
815 %************************************************************************
818 type LInstDecl name = Located (InstDecl name)
821 = InstDecl (LHsType name) -- Context => Class Instance-type
822 -- Using a polytype means that the renamer conveniently
823 -- figures out the quantified type variables for us.
825 [LSig name] -- User-supplied pragmatic info
826 [LTyClDecl name]-- Associated types (ie, 'TyData' and
828 deriving (Data, Typeable)
830 instance (OutputableBndr name) => Outputable (InstDecl name) where
832 ppr (InstDecl inst_ty binds uprags ats)
833 = vcat [hsep [ptext (sLit "instance"), ppr inst_ty, ptext (sLit "where")]
834 , nest 4 $ vcat (map ppr ats)
835 , nest 4 $ vcat (map ppr uprags)
836 , nest 4 $ pprLHsBinds binds ]
838 -- Extract the declarations of associated types from an instance
840 instDeclATs :: InstDecl name -> [LTyClDecl name]
841 instDeclATs (InstDecl _ _ _ ats) = ats
844 %************************************************************************
846 \subsection[DerivDecl]{A stand-alone instance deriving declaration
848 %************************************************************************
851 type LDerivDecl name = Located (DerivDecl name)
853 data DerivDecl name = DerivDecl (LHsType name)
854 deriving (Data, Typeable)
856 instance (OutputableBndr name) => Outputable (DerivDecl name) where
858 = hsep [ptext (sLit "deriving instance"), ppr ty]
861 %************************************************************************
863 \subsection[DefaultDecl]{A @default@ declaration}
865 %************************************************************************
867 There can only be one default declaration per module, but it is hard
868 for the parser to check that; we pass them all through in the abstract
869 syntax, and that restriction must be checked in the front end.
872 type LDefaultDecl name = Located (DefaultDecl name)
874 data DefaultDecl name
875 = DefaultDecl [LHsType name]
876 deriving (Data, Typeable)
878 instance (OutputableBndr name)
879 => Outputable (DefaultDecl name) where
881 ppr (DefaultDecl tys)
882 = ptext (sLit "default") <+> parens (interpp'SP tys)
885 %************************************************************************
887 \subsection{Foreign function interface declaration}
889 %************************************************************************
893 -- foreign declarations are distinguished as to whether they define or use a
896 -- * the Boolean value indicates whether the pre-standard deprecated syntax
899 type LForeignDecl name = Located (ForeignDecl name)
901 data ForeignDecl name
902 = ForeignImport (Located name) (LHsType name) ForeignImport -- defines name
903 | ForeignExport (Located name) (LHsType name) ForeignExport -- uses name
904 deriving (Data, Typeable)
906 -- Specification Of an imported external entity in dependence on the calling
909 data ForeignImport = -- import of a C entity
911 -- * the two strings specifying a header file or library
912 -- may be empty, which indicates the absence of a
913 -- header or object specification (both are not used
914 -- in the case of `CWrapper' and when `CFunction'
915 -- has a dynamic target)
917 -- * the calling convention is irrelevant for code
918 -- generation in the case of `CLabel', but is needed
919 -- for pretty printing
921 -- * `Safety' is irrelevant for `CLabel' and `CWrapper'
923 CImport CCallConv -- ccall or stdcall
924 Safety -- safe or unsafe
925 FastString -- name of C header
926 CImportSpec -- details of the C entity
927 deriving (Data, Typeable)
929 -- details of an external C entity
931 data CImportSpec = CLabel CLabelString -- import address of a C label
932 | CFunction CCallTarget -- static or dynamic function
933 | CWrapper -- wrapper to expose closures
935 deriving (Data, Typeable)
937 -- specification of an externally exported entity in dependence on the calling
940 data ForeignExport = CExport CExportSpec -- contains the calling convention
941 deriving (Data, Typeable)
943 -- pretty printing of foreign declarations
946 instance OutputableBndr name => Outputable (ForeignDecl name) where
947 ppr (ForeignImport n ty fimport) =
948 hang (ptext (sLit "foreign import") <+> ppr fimport <+> ppr n)
949 2 (dcolon <+> ppr ty)
950 ppr (ForeignExport n ty fexport) =
951 hang (ptext (sLit "foreign export") <+> ppr fexport <+> ppr n)
952 2 (dcolon <+> ppr ty)
954 instance Outputable ForeignImport where
955 ppr (CImport cconv safety header spec) =
956 ppr cconv <+> ppr safety <+>
957 char '"' <> pprCEntity spec <> char '"'
959 pp_hdr = if nullFS header then empty else ftext header
961 pprCEntity (CLabel lbl) =
962 ptext (sLit "static") <+> pp_hdr <+> char '&' <> ppr lbl
963 pprCEntity (CFunction (StaticTarget lbl _)) =
964 ptext (sLit "static") <+> pp_hdr <+> ppr lbl
965 pprCEntity (CFunction (DynamicTarget)) =
966 ptext (sLit "dynamic")
967 pprCEntity (CWrapper) = ptext (sLit "wrapper")
969 instance Outputable ForeignExport where
970 ppr (CExport (CExportStatic lbl cconv)) =
971 ppr cconv <+> char '"' <> ppr lbl <> char '"'
975 %************************************************************************
977 \subsection{Transformation rules}
979 %************************************************************************
982 type LRuleDecl name = Located (RuleDecl name)
985 = HsRule -- Source rule
986 RuleName -- Rule name
988 [RuleBndr name] -- Forall'd vars; after typechecking this includes tyvars
989 (Located (HsExpr name)) -- LHS
990 NameSet -- Free-vars from the LHS
991 (Located (HsExpr name)) -- RHS
992 NameSet -- Free-vars from the RHS
993 deriving (Data, Typeable)
996 = RuleBndr (Located name)
997 | RuleBndrSig (Located name) (LHsType name)
998 deriving (Data, Typeable)
1000 collectRuleBndrSigTys :: [RuleBndr name] -> [LHsType name]
1001 collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs]
1003 instance OutputableBndr name => Outputable (RuleDecl name) where
1004 ppr (HsRule name act ns lhs _fv_lhs rhs _fv_rhs)
1005 = sep [text "{-# RULES" <+> doubleQuotes (ftext name) <+> ppr act,
1006 nest 4 (pp_forall <+> pprExpr (unLoc lhs)),
1007 nest 4 (equals <+> pprExpr (unLoc rhs) <+> text "#-}") ]
1009 pp_forall | null ns = empty
1010 | otherwise = text "forall" <+> fsep (map ppr ns) <> dot
1012 instance OutputableBndr name => Outputable (RuleBndr name) where
1013 ppr (RuleBndr name) = ppr name
1014 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
1017 %************************************************************************
1019 \subsection[DocDecl]{Document comments}
1021 %************************************************************************
1025 type LDocDecl = Located (DocDecl)
1028 = DocCommentNext HsDocString
1029 | DocCommentPrev HsDocString
1030 | DocCommentNamed String HsDocString
1031 | DocGroup Int HsDocString
1032 deriving (Data, Typeable)
1034 -- Okay, I need to reconstruct the document comments, but for now:
1035 instance Outputable DocDecl where
1036 ppr _ = text "<document comment>"
1038 docDeclDoc :: DocDecl -> HsDocString
1039 docDeclDoc (DocCommentNext d) = d
1040 docDeclDoc (DocCommentPrev d) = d
1041 docDeclDoc (DocCommentNamed _ d) = d
1042 docDeclDoc (DocGroup _ d) = d
1046 %************************************************************************
1048 \subsection[DeprecDecl]{Deprecations}
1050 %************************************************************************
1052 We use exported entities for things to deprecate.
1055 type LWarnDecl name = Located (WarnDecl name)
1057 data WarnDecl name = Warning name WarningTxt
1058 deriving (Data, Typeable)
1060 instance OutputableBndr name => Outputable (WarnDecl name) where
1061 ppr (Warning thing txt)
1062 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
1065 %************************************************************************
1067 \subsection[AnnDecl]{Annotations}
1069 %************************************************************************
1072 type LAnnDecl name = Located (AnnDecl name)
1074 data AnnDecl name = HsAnnotation (AnnProvenance name) (Located (HsExpr name))
1075 deriving (Data, Typeable)
1077 instance (OutputableBndr name) => Outputable (AnnDecl name) where
1078 ppr (HsAnnotation provenance expr)
1079 = hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"]
1082 data AnnProvenance name = ValueAnnProvenance name
1083 | TypeAnnProvenance name
1084 | ModuleAnnProvenance
1085 deriving (Data, Typeable)
1087 annProvenanceName_maybe :: AnnProvenance name -> Maybe name
1088 annProvenanceName_maybe (ValueAnnProvenance name) = Just name
1089 annProvenanceName_maybe (TypeAnnProvenance name) = Just name
1090 annProvenanceName_maybe ModuleAnnProvenance = Nothing
1092 -- TODO: Replace with Traversable instance when GHC bootstrap version rises high enough
1093 modifyAnnProvenanceNameM :: Monad m => (before -> m after) -> AnnProvenance before -> m (AnnProvenance after)
1094 modifyAnnProvenanceNameM fm prov =
1096 ValueAnnProvenance name -> liftM ValueAnnProvenance (fm name)
1097 TypeAnnProvenance name -> liftM TypeAnnProvenance (fm name)
1098 ModuleAnnProvenance -> return ModuleAnnProvenance
1100 pprAnnProvenance :: OutputableBndr name => AnnProvenance name -> SDoc
1101 pprAnnProvenance ModuleAnnProvenance = ptext (sLit "ANN module")
1102 pprAnnProvenance (ValueAnnProvenance name) = ptext (sLit "ANN") <+> ppr name
1103 pprAnnProvenance (TypeAnnProvenance name) = ptext (sLit "ANN type") <+> ppr name