2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[HsDecls]{Abstract syntax: global declarations}
6 Definitions for: @TyDecl@ and @ConDecl@, @ClassDecl@,
7 @InstDecl@, @DefaultDecl@ and @ForeignDecl@.
11 HsDecl(..), TyClDecl(..), InstDecl(..), RuleDecl(..), RuleBndr(..),
12 DefaultDecl(..), ForeignDecl(..), ForKind(..),
13 ExtName(..), isDynamicExtName, extNameStatic,
14 ConDecl(..), ConDetails(..),
15 BangType(..), getBangType,
16 IfaceSig(..), SpecDataSig(..),
17 DeprecDecl(..), DeprecTxt,
18 hsDeclName, instDeclName, tyClDeclName, isClassDecl, isSynDecl, isDataDecl, countTyClDecls, toHsRule
21 #include "HsVersions.h"
24 import HsBinds ( HsBinds, MonoBinds, Sig(..), FixitySig(..) )
25 import HsExpr ( HsExpr )
26 import HsPragmas ( DataPragmas, ClassPragmas )
27 import HsImpExp ( IE(..) )
29 import PprCore ( pprCoreRule )
30 import HsCore ( UfExpr(UfVar), UfBinder, IfaceSig(..), eq_ufBinders, eq_ufExpr, pprUfExpr, toUfExpr, toUfBndr )
31 import CoreSyn ( CoreRule(..) )
32 import BasicTypes ( NewOrData(..) )
33 import CallConv ( CallConv, pprCallConv )
34 import Name ( toRdrName )
37 import FunDeps ( pprFundeps )
38 import Class ( FunDep )
39 import CStrings ( CLabelString, pprCLabelString )
41 import SrcLoc ( SrcLoc, noSrcLoc )
45 %************************************************************************
47 \subsection[HsDecl]{Declarations}
49 %************************************************************************
53 = TyClD (TyClDecl name pat)
54 | InstD (InstDecl name pat)
55 | DefD (DefaultDecl name)
56 | ValD (HsBinds name pat)
57 | ForD (ForeignDecl name)
58 | SigD (IfaceSig name)
59 | FixD (FixitySig name)
60 | DeprecD (DeprecDecl name)
61 | RuleD (RuleDecl name pat)
63 -- NB: all top-level fixity decls are contained EITHER
65 -- OR in the ClassDecls in TyClDs
68 -- a) data constructors
69 -- b) class methods (but they can be also done in the
70 -- signatures of class decls)
71 -- c) imported functions (that have an IfacSig)
74 -- The latter is for class methods only
79 hsDeclName :: (Outputable name, Outputable pat)
80 => HsDecl name pat -> name
82 hsDeclName (TyClD decl) = tyClDeclName decl
83 hsDeclName (InstD decl) = instDeclName decl
84 hsDeclName (SigD (IfaceSig name _ _ _)) = name
85 hsDeclName (ForD (ForeignDecl name _ _ _ _ _)) = name
86 hsDeclName (FixD (FixitySig name _ _)) = name
87 -- Others don't make sense
89 hsDeclName x = pprPanic "HsDecls.hsDeclName" (ppr x)
93 tyClDeclName :: TyClDecl name pat -> name
94 tyClDeclName (TyData _ _ name _ _ _ _ _ _) = name
95 tyClDeclName (TySynonym name _ _ _) = name
96 tyClDeclName (ClassDecl _ name _ _ _ _ _ _ _ _ _ _) = name
98 instDeclName :: InstDecl name pat -> name
99 instDeclName (InstDecl _ _ _ (Just name) _) = name
103 instance (Outputable name, Outputable pat)
104 => Outputable (HsDecl name pat) where
106 ppr (TyClD dcl) = ppr dcl
107 ppr (SigD sig) = ppr sig
108 ppr (ValD binds) = ppr binds
109 ppr (DefD def) = ppr def
110 ppr (InstD inst) = ppr inst
111 ppr (ForD fd) = ppr fd
112 ppr (FixD fd) = ppr fd
113 ppr (RuleD rd) = ppr rd
114 ppr (DeprecD dd) = ppr dd
118 instance Ord name => Eq (HsDecl name pat) where
119 -- Used only when comparing interfaces,
120 -- at which time only signature and type/class decls
121 (SigD s1) == (SigD s2) = s1 == s2
122 (TyClD d1) == (TyClD d2) = d1 == d2
127 %************************************************************************
129 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
131 %************************************************************************
133 Type and class declarations carry 'implicit names'. In particular:
137 Each data type decl defines
138 a worker name for each constructor
139 to-T and from-T convertors
140 Each class decl defines
141 a tycon for the class
142 a data constructor for that tycon
143 the worker for that constructor
144 a selector for each superclass
146 All have occurrence names that are derived uniquely from their parent declaration.
148 None of these get separate definitions in an interface file; they are
149 fully defined by the data or class decl. But they may *occur* in
150 interface files, of course. Any such occurrence must haul in the
151 relevant type or class decl.
154 - Make up their occurrence names immediately
156 - Ensure they "point to" the parent data/class decl
157 when loading that decl from an interface file
159 - When renaming the decl look them up in the name cache,
160 ensure correct module and provenance is set
162 Type B: Default methods and dictionary functions
163 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
164 Have their own binding in an interface file.
166 Default methods : occurrence name is derived uniquely from the class decl.
167 Dict functions : occurrence name is derived from the instance decl, plus a unique number.
170 - Do *not* make them point to the parent class decl
171 - Interface-file decls: treat just like Type A
172 - Source-file decls: the names aren't in the decl at all;
173 instead the typechecker makes them up
176 data TyClDecl name pat
178 (HsContext name) -- context
179 name -- type constructor
180 [HsTyVarBndr name] -- type variables
181 [ConDecl name] -- data constructors (empty if abstract)
182 Int -- Number of data constructors (valid even if type is abstract)
183 (Maybe [name]) -- derivings; Nothing => not specified
184 -- (i.e., derive default); Just [] => derive
185 -- *nothing*; Just <list> => as you would
190 | TySynonym name -- type constructor
191 [HsTyVarBndr name] -- type variables
192 (HsType name) -- synonym expansion
195 | ClassDecl (HsContext name) -- context...
196 name -- name of the class
197 [HsTyVarBndr name] -- the class type variables
198 [FunDep name] -- functional dependencies
199 [Sig name] -- methods' signatures
200 (MonoBinds name pat) -- default methods
202 name name name [name] -- The names of the tycon, datacon wrapper, datacon worker,
203 -- and superclass selectors for this class.
204 -- These are filled in as the ClassDecl is made.
207 instance Ord name => Eq (TyClDecl name pat) where
208 -- Used only when building interface files
209 (==) (TyData nd1 cxt1 n1 tvs1 cons1 _ _ _ _)
210 (TyData nd2 cxt2 n2 tvs2 cons2 _ _ _ _)
213 eqWithHsTyVars tvs1 tvs2 (\ env ->
214 eq_hsContext env cxt1 cxt2 &&
215 eqListBy (eq_ConDecl env) cons1 cons2
218 (==) (TySynonym n1 tvs1 ty1 _)
219 (TySynonym n2 tvs2 ty2 _)
221 eqWithHsTyVars tvs1 tvs2 (\ env -> eq_hsType env ty1 ty2)
223 (==) (ClassDecl cxt1 n1 tvs1 fds1 sigs1 _ _ _ _ _ _ _)
224 (ClassDecl cxt2 n2 tvs2 fds2 sigs2 _ _ _ _ _ _ _)
226 eqWithHsTyVars tvs1 tvs2 (\ env ->
227 eq_hsContext env cxt1 cxt2 &&
228 eqListBy (eq_hsFD env) fds1 fds2 &&
229 eqListBy (eq_cls_sig env) sigs1 sigs2
232 (==) _ _ = False -- default case
235 eq_hsFD env (ns1,ms1) (ns2,ms2)
236 = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
238 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
239 = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
241 -- Ignore the name of the default method.
242 -- This is used for comparing declarations before putting
243 -- them into interface files, and the name of the default
244 -- method isn't relevant
245 (Just (_,explicit_dm1)) `eq_dm` (Just (_,explicit_dm2)) = explicit_dm1 == explicit_dm2
246 Nothing `eq_dm` Nothing = True
247 dm1 `eq_dm` dm2 = False
251 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int)
252 -- class, data, newtype, synonym decls
254 = (length [() | ClassDecl _ _ _ _ _ _ _ _ _ _ _ _ <- decls],
255 length [() | TyData DataType _ _ _ _ _ _ _ _ <- decls],
256 length [() | TyData NewType _ _ _ _ _ _ _ _ <- decls],
257 length [() | TySynonym _ _ _ _ <- decls])
259 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
261 isSynDecl (TySynonym _ _ _ _) = True
262 isSynDecl other = False
264 isDataDecl (TyData _ _ _ _ _ _ _ _ _) = True
265 isDataDecl other = False
267 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ _ _ _ _) = True
268 isClassDecl other = False
272 instance (Outputable name, Outputable pat)
273 => Outputable (TyClDecl name pat) where
275 ppr (TySynonym tycon tyvars mono_ty src_loc)
276 = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
279 ppr (TyData new_or_data context tycon tyvars condecls ncons derivings pragmas src_loc)
281 (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
282 (pp_condecls condecls ncons)
285 keyword = case new_or_data of
286 NewType -> SLIT("newtype")
287 DataType -> SLIT("data")
289 ppr (ClassDecl context clas tyvars fds sigs methods pragmas _ _ _ _ src_loc)
290 | null sigs -- No "where" part
293 | otherwise -- Laid out
294 = sep [hsep [top_matter, ptext SLIT("where {")],
295 nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
297 top_matter = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
298 ppr_sig sig = ppr sig <> semi
299 pp_methods = getPprStyle $ \ sty ->
300 if ifaceStyle sty then empty else ppr methods
303 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
304 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
306 pp_condecls [] ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
307 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
309 pp_tydecl pp_head pp_decl_rhs derivings
310 = hang pp_head 4 (sep [
314 Just ds -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
318 A type for recording what types a datatype should be specialised to.
319 It's called a ``Sig'' because it's sort of like a ``type signature''
320 for an datatype declaration.
323 data SpecDataSig name
324 = SpecDataSig name -- tycon to specialise
328 instance (Outputable name)
329 => Outputable (SpecDataSig name) where
331 ppr (SpecDataSig tycon ty _)
332 = hsep [text "{-# SPECIALIZE data", ppr ty, text "#-}"]
335 %************************************************************************
337 \subsection[ConDecl]{A data-constructor declaration}
339 %************************************************************************
343 = ConDecl name -- Constructor name; this is used for the
344 -- DataCon itself, and for the user-callable wrapper Id
346 name -- Name of the constructor's 'worker Id'
347 -- Filled in as the ConDecl is built
349 [HsTyVarBndr name] -- Existentially quantified type variables
350 (HsContext name) -- ...and context
351 -- If both are empty then there are no existentials
357 = VanillaCon -- prefix-style con decl
360 | InfixCon -- infix-style con decl
364 | RecCon -- record-style con decl
365 [([name], BangType name)] -- list of "fields"
367 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
368 (ConDecl n2 _ tvs2 cxt2 cds2 _)
370 (eqWithHsTyVars tvs1 tvs2 $ \ env ->
371 eq_hsContext env cxt1 cxt2 &&
372 eq_ConDetails env cds1 cds2)
374 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
375 = eqListBy (eq_btype env) bts1 bts2
376 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
377 = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
378 eq_ConDetails env (RecCon fs1) (RecCon fs2)
379 = eqListBy (eq_fld env) fs1 fs2
380 eq_ConDetails env _ _ = False
382 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
386 = Banged (HsType name) -- HsType: to allow Haskell extensions
387 | Unbanged (HsType name) -- (MonoType only needed for straight Haskell)
388 | Unpacked (HsType name) -- Field is strict and to be unpacked if poss.
390 getBangType (Banged ty) = ty
391 getBangType (Unbanged ty) = ty
392 getBangType (Unpacked ty) = ty
394 eq_btype env (Banged t1) (Banged t2) = eq_hsType env t1 t2
395 eq_btype env (Unbanged t1) (Unbanged t2) = eq_hsType env t1 t2
396 eq_btype env (Unpacked t1) (Unpacked t2) = eq_hsType env t1 t2
397 eq_btype env _ _ = False
401 instance (Outputable name) => Outputable (ConDecl name) where
402 ppr (ConDecl con _ tvs cxt con_details loc)
403 = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
405 ppr_con_details con (InfixCon ty1 ty2)
406 = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
408 ppr_con_details con (VanillaCon tys)
409 = ppr con <+> hsep (map (ppr_bang) tys)
411 ppr_con_details con (RecCon fields)
412 = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
414 ppr_field (ns, ty) = hsep (map (ppr) ns) <+>
418 instance Outputable name => Outputable (BangType name) where
421 ppr_bang (Banged ty) = ptext SLIT("!") <> pprParendHsType ty
422 ppr_bang (Unbanged ty) = pprParendHsType ty
423 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
427 %************************************************************************
429 \subsection[InstDecl]{An instance declaration
431 %************************************************************************
434 data InstDecl name pat
435 = InstDecl (HsType name) -- Context => Class Instance-type
436 -- Using a polytype means that the renamer conveniently
437 -- figures out the quantified type variables for us.
441 [Sig name] -- User-supplied pragmatic info
443 (Maybe name) -- Name for the dictionary function
444 -- Nothing for source-file instance decls
450 instance (Outputable name, Outputable pat)
451 => Outputable (InstDecl name pat) where
453 ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
454 = getPprStyle $ \ sty ->
455 if ifaceStyle sty then
456 hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
458 vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
462 pp_dfun = case maybe_dfun_name of
468 instance Ord name => Eq (InstDecl name pat) where
469 -- Used for interface comparison only, so don't compare bindings
470 (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
471 = inst_ty1 == inst_ty2 && dfun1 == dfun2
475 %************************************************************************
477 \subsection[DefaultDecl]{A @default@ declaration}
479 %************************************************************************
481 There can only be one default declaration per module, but it is hard
482 for the parser to check that; we pass them all through in the abstract
483 syntax, and that restriction must be checked in the front end.
486 data DefaultDecl name
487 = DefaultDecl [HsType name]
490 instance (Outputable name)
491 => Outputable (DefaultDecl name) where
493 ppr (DefaultDecl tys src_loc)
494 = ptext SLIT("default") <+> parens (interpp'SP tys)
497 %************************************************************************
499 \subsection{Foreign function interface declaration}
501 %************************************************************************
504 data ForeignDecl name =
513 instance (Outputable name)
514 => Outputable (ForeignDecl name) where
516 ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
517 = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+>
518 ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
520 (ppr_imp_exp, ppr_unsafe) =
522 FoLabel -> (ptext SLIT("label"), empty)
523 FoExport -> (ptext SLIT("export"), empty)
525 | us -> (ptext SLIT("import"), ptext SLIT("unsafe"))
526 | otherwise -> (ptext SLIT("import"), empty)
531 | FoImport Bool -- True => unsafe call.
535 | ExtName CLabelString -- The external name of the foreign thing,
536 (Maybe CLabelString) -- and optionally its DLL or module name
537 -- Both of these are completely unencoded;
538 -- we just print them as they are
540 isDynamicExtName :: ExtName -> Bool
541 isDynamicExtName Dynamic = True
542 isDynamicExtName _ = False
544 extNameStatic :: ExtName -> CLabelString
545 extNameStatic (ExtName f _) = f
546 extNameStatic Dynamic = panic "staticExtName: Dynamic - shouldn't ever happen."
548 instance Outputable ExtName where
549 ppr Dynamic = ptext SLIT("dynamic")
550 ppr (ExtName nm mb_mod) =
551 case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+>
552 doubleQuotes (pprCLabelString nm)
555 %************************************************************************
557 \subsection{Transformation rules}
559 %************************************************************************
562 data RuleDecl name pat
563 = HsRule -- Source rule
564 FAST_STRING -- Rule name
565 [name] -- Forall'd tyvars, filled in by the renamer with
566 -- tyvars mentioned in sigs; then filled out by typechecker
567 [RuleBndr name] -- Forall'd term vars
568 (HsExpr name pat) -- LHS
569 (HsExpr name pat) -- RHS
572 | IfaceRule -- One that's come in from an interface file; pre-typecheck
574 [UfBinder name] -- Tyvars and term vars
576 [UfExpr name] -- Args of LHS
577 (UfExpr name) -- Pre typecheck
580 | IfaceRuleOut -- Post typecheck
587 | RuleBndrSig name (HsType name)
589 instance Ord name => Eq (RuleDecl name pat) where
590 -- Works for IfaceRules only; used when comparing interface file versions
591 (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
592 = n1==n2 && f1 == f2 &&
593 eq_ufBinders emptyEqHsEnv bs1 bs2 (\env ->
594 eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
596 instance (Outputable name, Outputable pat)
597 => Outputable (RuleDecl name pat) where
598 ppr (HsRule name tvs ns lhs rhs loc)
599 = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
600 pp_forall, ppr lhs, equals <+> ppr rhs,
603 pp_forall | null tvs && null ns = empty
604 | otherwise = text "forall" <+>
605 fsep (map ppr tvs ++ map ppr ns)
608 ppr (IfaceRule name tpl_vars fn tpl_args rhs loc)
609 = hsep [ doubleQuotes (ptext name),
610 ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
611 ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
612 ptext SLIT("=") <+> ppr rhs
615 ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
617 instance Outputable name => Outputable (RuleBndr name) where
618 ppr (RuleBndr name) = ppr name
619 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
621 toHsRule id (BuiltinRule _)
622 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
624 toHsRule id (Rule name bndrs args rhs)
625 = IfaceRule name (map toUfBndr bndrs) (toRdrName id)
626 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
629 = IfaceRule SLIT("bogus") [] (toRdrName id) [] (UfVar (toRdrName id)) noSrcLoc
633 %************************************************************************
635 \subsection[DeprecDecl]{Deprecations}
637 %************************************************************************
639 We use exported entities for things to deprecate. Cunning trick (hack?):
640 `IEModuleContents undefined' is used for module deprecation.
643 data DeprecDecl name = Deprecation (IE name) DeprecTxt SrcLoc
645 type DeprecTxt = FAST_STRING -- reason/explanation for deprecation
647 instance Outputable name => Outputable (DeprecDecl name) where
648 ppr (Deprecation (IEModuleContents _) txt _)
649 = hsep [text "{-# DEPRECATED", doubleQuotes (ppr txt), text "#-}"]
650 ppr (Deprecation thing txt _)
651 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]