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, 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,
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 tyClDeclTyVars :: TyClDecl name -> [LHsTyVarBndr name]
548 tyClDeclTyVars (TyFamily {tcdTyVars = tvs}) = tvs
549 tyClDeclTyVars (TySynonym {tcdTyVars = tvs}) = tvs
550 tyClDeclTyVars (TyData {tcdTyVars = tvs}) = tvs
551 tyClDeclTyVars (ClassDecl {tcdTyVars = tvs}) = tvs
552 tyClDeclTyVars (ForeignType {}) = []
556 countTyClDecls :: [TyClDecl name] -> (Int, Int, Int, Int, Int, Int)
557 -- class, synonym decls, data, newtype, family decls, family instances
559 = (count isClassDecl decls,
560 count isSynDecl decls, -- excluding...
561 count isDataTy decls, -- ...family...
562 count isNewTy decls, -- ...instances
563 count isFamilyDecl decls,
564 count isFamInstDecl decls)
566 isDataTy TyData{tcdND = DataType, tcdTyPats = Nothing} = True
569 isNewTy TyData{tcdND = NewType, tcdTyPats = Nothing} = True
574 instance OutputableBndr name
575 => Outputable (TyClDecl name) where
577 ppr (ForeignType {tcdLName = ltycon})
578 = hsep [ptext (sLit "foreign import type dotnet"), ppr ltycon]
580 ppr (TyFamily {tcdFlavour = flavour, tcdLName = ltycon,
581 tcdTyVars = tyvars, tcdKind = mb_kind})
582 = pp_flavour <+> pp_decl_head [] ltycon tyvars Nothing <+> pp_kind
584 pp_flavour = case flavour of
585 TypeFamily -> ptext (sLit "type family")
586 DataFamily -> ptext (sLit "data family")
588 pp_kind = case mb_kind of
590 Just kind -> dcolon <+> pprKind kind
592 ppr (TySynonym {tcdLName = ltycon, tcdTyVars = tyvars, tcdTyPats = typats,
593 tcdSynRhs = mono_ty})
594 = hang (ptext (sLit "type") <+>
595 (if isJust typats then ptext (sLit "instance") else empty) <+>
596 pp_decl_head [] ltycon tyvars typats <+>
600 ppr (TyData {tcdND = new_or_data, tcdCtxt = context, tcdLName = ltycon,
601 tcdTyVars = tyvars, tcdTyPats = typats, tcdKindSig = mb_sig,
602 tcdCons = condecls, tcdDerivs = derivings})
603 = pp_tydecl (null condecls && isJust mb_sig)
605 (if isJust typats then ptext (sLit "instance") else empty) <+>
606 pp_decl_head (unLoc context) ltycon tyvars typats <+>
608 (pp_condecls condecls)
611 ppr_sig Nothing = empty
612 ppr_sig (Just kind) = dcolon <+> pprKind kind
614 ppr (ClassDecl {tcdCtxt = context, tcdLName = lclas, tcdTyVars = tyvars,
616 tcdSigs = sigs, tcdMeths = methods, tcdATs = ats})
617 | null sigs && null ats -- No "where" part
620 | otherwise -- Laid out
621 = sep [hsep [top_matter, ptext (sLit "where {")],
622 nest 4 (sep [ sep (map ppr_semi ats)
623 , sep (map ppr_semi sigs)
624 , pprLHsBinds methods
627 top_matter = ptext (sLit "class")
628 <+> pp_decl_head (unLoc context) lclas tyvars Nothing
629 <+> pprFundeps (map unLoc fds)
630 ppr_semi decl = ppr decl <> semi
632 pp_decl_head :: OutputableBndr name
635 -> [LHsTyVarBndr name]
636 -> Maybe [LHsType name]
638 pp_decl_head context thing tyvars Nothing -- no explicit type patterns
639 = hsep [pprHsContext context, ppr thing, interppSP tyvars]
640 pp_decl_head context thing _ (Just typats) -- explicit type patterns
641 = hsep [ pprHsContext context, ppr thing
642 , hsep (map (pprParendHsType.unLoc) typats)]
644 pp_condecls :: OutputableBndr name => [LConDecl name] -> SDoc
645 pp_condecls cs@(L _ ConDecl{ con_res = ResTyGADT _ } : _) -- In GADT syntax
646 = hang (ptext (sLit "where")) 2 (vcat (map ppr cs))
647 pp_condecls cs -- In H98 syntax
648 = equals <+> sep (punctuate (ptext (sLit " |")) (map ppr cs))
650 pp_tydecl :: OutputableBndr name => Bool -> SDoc -> SDoc -> Maybe [LHsType name] -> SDoc
651 pp_tydecl True pp_head _ _
653 pp_tydecl False pp_head pp_decl_rhs derivings
654 = hang pp_head 4 (sep [
658 Just ds -> hsep [ptext (sLit "deriving"), parens (interpp'SP ds)]
661 instance Outputable NewOrData where
662 ppr NewType = ptext (sLit "newtype")
663 ppr DataType = ptext (sLit "data")
667 %************************************************************************
669 \subsection[ConDecl]{A data-constructor declaration}
671 %************************************************************************
674 type LConDecl name = Located (ConDecl name)
676 -- data T b = forall a. Eq a => MkT a b
677 -- MkT :: forall b a. Eq a => MkT a b
680 -- MkT1 :: Int -> T Int
682 -- data T = Int `MkT` Int
686 -- Int `MkT` Int :: T Int
690 { con_name :: Located name
691 -- ^ Constructor name. This is used for the DataCon itself, and for
692 -- the user-callable wrapper Id.
694 , con_explicit :: HsExplicitFlag
695 -- ^ Is there an user-written forall? (cf. 'HsTypes.HsForAllTy')
697 , con_qvars :: [LHsTyVarBndr name]
698 -- ^ Type variables. Depending on 'con_res' this describes the
699 -- follewing entities
701 -- - ResTyH98: the constructor's *existential* type variables
702 -- - ResTyGADT: *all* the constructor's quantified type variables
704 , con_cxt :: LHsContext name
705 -- ^ The context. This /does not/ include the \"stupid theta\" which
706 -- lives only in the 'TyData' decl.
708 , con_details :: HsConDeclDetails name
709 -- ^ The main payload
711 , con_res :: ResType name
712 -- ^ Result type of the constructor
714 , con_doc :: Maybe LHsDocString
715 -- ^ A possible Haddock comment.
717 , con_old_rec :: Bool
718 -- ^ TEMPORARY field; True <=> user has employed now-deprecated syntax for
719 -- GADT-style record decl C { blah } :: T a b
720 -- Remove this when we no longer parse this stuff, and hence do not
721 -- need to report decprecated use
722 } deriving (Data, Typeable)
724 type HsConDeclDetails name = HsConDetails (LBangType name) [ConDeclField name]
726 hsConDeclArgTys :: HsConDeclDetails name -> [LBangType name]
727 hsConDeclArgTys (PrefixCon tys) = tys
728 hsConDeclArgTys (InfixCon ty1 ty2) = [ty1,ty2]
729 hsConDeclArgTys (RecCon flds) = map cd_fld_type flds
732 = ResTyH98 -- Constructor was declared using Haskell 98 syntax
733 | ResTyGADT (LHsType name) -- Constructor was declared using GADT-style syntax,
734 -- and here is its result type
735 deriving (Data, Typeable)
737 instance OutputableBndr name => Outputable (ResType name) where
739 ppr ResTyH98 = ptext (sLit "ResTyH98")
740 ppr (ResTyGADT ty) = ptext (sLit "ResTyGADT") <+> pprParendHsType (unLoc ty)
745 instance (OutputableBndr name) => Outputable (ConDecl name) where
748 pprConDecl :: OutputableBndr name => ConDecl name -> SDoc
749 pprConDecl (ConDecl { con_name =con, con_explicit = expl, con_qvars = tvs
750 , con_cxt = cxt, con_details = details
751 , con_res = ResTyH98, con_doc = doc })
752 = sep [ppr_mbDoc doc, pprHsForAll expl tvs cxt, ppr_details con details]
754 ppr_details con (InfixCon t1 t2) = hsep [ppr t1, pprHsInfix con, ppr t2]
755 ppr_details con (PrefixCon tys) = hsep (pprHsVar con : map ppr tys)
756 ppr_details con (RecCon fields) = ppr con <+> pprConDeclFields fields
758 pprConDecl (ConDecl { con_name = con, con_explicit = expl, con_qvars = tvs
759 , con_cxt = cxt, con_details = PrefixCon arg_tys
760 , con_res = ResTyGADT res_ty })
761 = ppr con <+> dcolon <+>
762 sep [pprHsForAll expl tvs cxt, ppr (foldr mk_fun_ty res_ty arg_tys)]
764 mk_fun_ty a b = noLoc (HsFunTy a b)
766 pprConDecl (ConDecl { con_name = con, con_explicit = expl, con_qvars = tvs
767 , con_cxt = cxt, con_details = RecCon fields, con_res = ResTyGADT res_ty })
768 = sep [ppr con <+> dcolon <+> pprHsForAll expl tvs cxt,
769 pprConDeclFields fields <+> arrow <+> ppr res_ty]
771 pprConDecl (ConDecl {con_name = con, con_details = InfixCon {}, con_res = ResTyGADT {} })
772 = pprPanic "pprConDecl" (ppr con)
773 -- In GADT syntax we don't allow infix constructors
776 %************************************************************************
778 \subsection[InstDecl]{An instance declaration
780 %************************************************************************
783 type LInstDecl name = Located (InstDecl name)
786 = InstDecl (LHsType name) -- Context => Class Instance-type
787 -- Using a polytype means that the renamer conveniently
788 -- figures out the quantified type variables for us.
790 [LSig name] -- User-supplied pragmatic info
791 [LTyClDecl name]-- Associated types (ie, 'TyData' and
793 deriving (Data, Typeable)
795 instance (OutputableBndr name) => Outputable (InstDecl name) where
797 ppr (InstDecl inst_ty binds uprags ats)
798 = vcat [hsep [ptext (sLit "instance"), ppr inst_ty, ptext (sLit "where")]
799 , nest 4 $ vcat (map ppr ats)
800 , nest 4 $ vcat (map ppr uprags)
801 , nest 4 $ pprLHsBinds binds ]
803 -- Extract the declarations of associated types from an instance
805 instDeclATs :: [LInstDecl name] -> [LTyClDecl name]
806 instDeclATs inst_decls = [at | L _ (InstDecl _ _ _ ats) <- inst_decls, at <- ats]
809 %************************************************************************
811 \subsection[DerivDecl]{A stand-alone instance deriving declaration
813 %************************************************************************
816 type LDerivDecl name = Located (DerivDecl name)
818 data DerivDecl name = DerivDecl (LHsType name)
819 deriving (Data, Typeable)
821 instance (OutputableBndr name) => Outputable (DerivDecl name) where
823 = hsep [ptext (sLit "deriving instance"), ppr ty]
826 %************************************************************************
828 \subsection[DefaultDecl]{A @default@ declaration}
830 %************************************************************************
832 There can only be one default declaration per module, but it is hard
833 for the parser to check that; we pass them all through in the abstract
834 syntax, and that restriction must be checked in the front end.
837 type LDefaultDecl name = Located (DefaultDecl name)
839 data DefaultDecl name
840 = DefaultDecl [LHsType name]
841 deriving (Data, Typeable)
843 instance (OutputableBndr name)
844 => Outputable (DefaultDecl name) where
846 ppr (DefaultDecl tys)
847 = ptext (sLit "default") <+> parens (interpp'SP tys)
850 %************************************************************************
852 \subsection{Foreign function interface declaration}
854 %************************************************************************
858 -- foreign declarations are distinguished as to whether they define or use a
861 -- * the Boolean value indicates whether the pre-standard deprecated syntax
864 type LForeignDecl name = Located (ForeignDecl name)
866 data ForeignDecl name
867 = ForeignImport (Located name) (LHsType name) ForeignImport -- defines name
868 | ForeignExport (Located name) (LHsType name) ForeignExport -- uses name
869 deriving (Data, Typeable)
871 -- Specification Of an imported external entity in dependence on the calling
874 data ForeignImport = -- import of a C entity
876 -- * the two strings specifying a header file or library
877 -- may be empty, which indicates the absence of a
878 -- header or object specification (both are not used
879 -- in the case of `CWrapper' and when `CFunction'
880 -- has a dynamic target)
882 -- * the calling convention is irrelevant for code
883 -- generation in the case of `CLabel', but is needed
884 -- for pretty printing
886 -- * `Safety' is irrelevant for `CLabel' and `CWrapper'
888 CImport CCallConv -- ccall or stdcall
889 Safety -- safe or unsafe
890 FastString -- name of C header
891 CImportSpec -- details of the C entity
892 deriving (Data, Typeable)
894 -- details of an external C entity
896 data CImportSpec = CLabel CLabelString -- import address of a C label
897 | CFunction CCallTarget -- static or dynamic function
898 | CWrapper -- wrapper to expose closures
900 deriving (Data, Typeable)
902 -- specification of an externally exported entity in dependence on the calling
905 data ForeignExport = CExport CExportSpec -- contains the calling convention
906 deriving (Data, Typeable)
908 -- pretty printing of foreign declarations
911 instance OutputableBndr name => Outputable (ForeignDecl name) where
912 ppr (ForeignImport n ty fimport) =
913 hang (ptext (sLit "foreign import") <+> ppr fimport <+> ppr n)
914 2 (dcolon <+> ppr ty)
915 ppr (ForeignExport n ty fexport) =
916 hang (ptext (sLit "foreign export") <+> ppr fexport <+> ppr n)
917 2 (dcolon <+> ppr ty)
919 instance Outputable ForeignImport where
920 ppr (CImport cconv safety header spec) =
921 ppr cconv <+> ppr safety <+>
922 char '"' <> pprCEntity spec <> char '"'
924 pp_hdr = if nullFS header then empty else ftext header
926 pprCEntity (CLabel lbl) =
927 ptext (sLit "static") <+> pp_hdr <+> char '&' <> ppr lbl
928 pprCEntity (CFunction (StaticTarget lbl _)) =
929 ptext (sLit "static") <+> pp_hdr <+> ppr lbl
930 pprCEntity (CFunction (DynamicTarget)) =
931 ptext (sLit "dynamic")
932 pprCEntity (CWrapper) = ptext (sLit "wrapper")
934 instance Outputable ForeignExport where
935 ppr (CExport (CExportStatic lbl cconv)) =
936 ppr cconv <+> char '"' <> ppr lbl <> char '"'
940 %************************************************************************
942 \subsection{Transformation rules}
944 %************************************************************************
947 type LRuleDecl name = Located (RuleDecl name)
950 = HsRule -- Source rule
951 RuleName -- Rule name
953 [RuleBndr name] -- Forall'd vars; after typechecking this includes tyvars
954 (Located (HsExpr name)) -- LHS
955 NameSet -- Free-vars from the LHS
956 (Located (HsExpr name)) -- RHS
957 NameSet -- Free-vars from the RHS
958 deriving (Data, Typeable)
961 = RuleBndr (Located name)
962 | RuleBndrSig (Located name) (LHsType name)
963 deriving (Data, Typeable)
965 collectRuleBndrSigTys :: [RuleBndr name] -> [LHsType name]
966 collectRuleBndrSigTys bndrs = [ty | RuleBndrSig _ ty <- bndrs]
968 instance OutputableBndr name => Outputable (RuleDecl name) where
969 ppr (HsRule name act ns lhs _fv_lhs rhs _fv_rhs)
970 = sep [text "{-# RULES" <+> doubleQuotes (ftext name) <+> ppr act,
971 nest 4 (pp_forall <+> pprExpr (unLoc lhs)),
972 nest 4 (equals <+> pprExpr (unLoc rhs) <+> text "#-}") ]
974 pp_forall | null ns = empty
975 | otherwise = text "forall" <+> fsep (map ppr ns) <> dot
977 instance OutputableBndr name => Outputable (RuleBndr name) where
978 ppr (RuleBndr name) = ppr name
979 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
982 %************************************************************************
984 \subsection[DocDecl]{Document comments}
986 %************************************************************************
990 type LDocDecl = Located (DocDecl)
993 = DocCommentNext HsDocString
994 | DocCommentPrev HsDocString
995 | DocCommentNamed String HsDocString
996 | DocGroup Int HsDocString
997 deriving (Data, Typeable)
999 -- Okay, I need to reconstruct the document comments, but for now:
1000 instance Outputable DocDecl where
1001 ppr _ = text "<document comment>"
1003 docDeclDoc :: DocDecl -> HsDocString
1004 docDeclDoc (DocCommentNext d) = d
1005 docDeclDoc (DocCommentPrev d) = d
1006 docDeclDoc (DocCommentNamed _ d) = d
1007 docDeclDoc (DocGroup _ d) = d
1011 %************************************************************************
1013 \subsection[DeprecDecl]{Deprecations}
1015 %************************************************************************
1017 We use exported entities for things to deprecate.
1020 type LWarnDecl name = Located (WarnDecl name)
1022 data WarnDecl name = Warning name WarningTxt
1023 deriving (Data, Typeable)
1025 instance OutputableBndr name => Outputable (WarnDecl name) where
1026 ppr (Warning thing txt)
1027 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]
1030 %************************************************************************
1032 \subsection[AnnDecl]{Annotations}
1034 %************************************************************************
1037 type LAnnDecl name = Located (AnnDecl name)
1039 data AnnDecl name = HsAnnotation (AnnProvenance name) (Located (HsExpr name))
1040 deriving (Data, Typeable)
1042 instance (OutputableBndr name) => Outputable (AnnDecl name) where
1043 ppr (HsAnnotation provenance expr)
1044 = hsep [text "{-#", pprAnnProvenance provenance, pprExpr (unLoc expr), text "#-}"]
1047 data AnnProvenance name = ValueAnnProvenance name
1048 | TypeAnnProvenance name
1049 | ModuleAnnProvenance
1050 deriving (Data, Typeable)
1052 annProvenanceName_maybe :: AnnProvenance name -> Maybe name
1053 annProvenanceName_maybe (ValueAnnProvenance name) = Just name
1054 annProvenanceName_maybe (TypeAnnProvenance name) = Just name
1055 annProvenanceName_maybe ModuleAnnProvenance = Nothing
1057 -- TODO: Replace with Traversable instance when GHC bootstrap version rises high enough
1058 modifyAnnProvenanceNameM :: Monad m => (before -> m after) -> AnnProvenance before -> m (AnnProvenance after)
1059 modifyAnnProvenanceNameM fm prov =
1061 ValueAnnProvenance name -> liftM ValueAnnProvenance (fm name)
1062 TypeAnnProvenance name -> liftM TypeAnnProvenance (fm name)
1063 ModuleAnnProvenance -> return ModuleAnnProvenance
1065 pprAnnProvenance :: OutputableBndr name => AnnProvenance name -> SDoc
1066 pprAnnProvenance ModuleAnnProvenance = ptext (sLit "ANN module")
1067 pprAnnProvenance (ValueAnnProvenance name) = ptext (sLit "ANN") <+> ppr name
1068 pprAnnProvenance (TypeAnnProvenance name) = ptext (sLit "ANN type") <+> ppr name