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,
24 #include "HsVersions.h"
27 import HsBinds ( HsBinds, MonoBinds, Sig(..), FixitySig(..) )
28 import HsExpr ( HsExpr )
29 import HsPragmas ( DataPragmas, ClassPragmas )
30 import HsImpExp ( IE(..) )
32 import PprCore ( pprCoreRule )
33 import HsCore ( UfExpr(UfVar), UfBinder, IfaceSig(..), eq_ufBinders, eq_ufExpr, pprUfExpr, toUfExpr, toUfBndr )
34 import CoreSyn ( CoreRule(..) )
35 import BasicTypes ( NewOrData(..) )
36 import CallConv ( CallConv, pprCallConv )
37 import Name ( toRdrName )
40 import FunDeps ( pprFundeps )
41 import Class ( FunDep )
42 import CStrings ( CLabelString, pprCLabelString )
44 import SrcLoc ( SrcLoc, noSrcLoc )
48 %************************************************************************
50 \subsection[HsDecl]{Declarations}
52 %************************************************************************
56 = TyClD (TyClDecl name pat)
57 | InstD (InstDecl name pat)
58 | DefD (DefaultDecl name)
59 | ValD (HsBinds name pat)
60 | ForD (ForeignDecl name)
61 | SigD (IfaceSig name)
62 | FixD (FixitySig name)
63 | DeprecD (DeprecDecl name)
64 | RuleD (RuleDecl name pat)
66 -- NB: all top-level fixity decls are contained EITHER
68 -- OR in the ClassDecls in TyClDs
71 -- a) data constructors
72 -- b) class methods (but they can be also done in the
73 -- signatures of class decls)
74 -- c) imported functions (that have an IfacSig)
77 -- The latter is for class methods only
82 hsDeclName :: (Outputable name, Outputable pat)
83 => HsDecl name pat -> name
85 hsDeclName (TyClD decl) = tyClDeclName decl
86 hsDeclName (InstD decl) = instDeclName decl
87 hsDeclName (SigD (IfaceSig name _ _ _)) = name
88 hsDeclName (ForD (ForeignDecl name _ _ _ _ _)) = name
89 hsDeclName (FixD (FixitySig name _ _)) = name
90 -- Others don't make sense
92 hsDeclName x = pprPanic "HsDecls.hsDeclName" (ppr x)
96 tyClDeclName :: TyClDecl name pat -> name
97 tyClDeclName (TyData _ _ name _ _ _ _ _ _ _ _) = name
98 tyClDeclName (TySynonym name _ _ _) = name
99 tyClDeclName (ClassDecl _ name _ _ _ _ _ _ _ ) = name
101 instDeclName :: InstDecl name pat -> name
102 instDeclName (InstDecl _ _ _ (Just name) _) = name
107 instance (Outputable name, Outputable pat)
108 => Outputable (HsDecl name pat) where
110 ppr (TyClD dcl) = ppr dcl
111 ppr (SigD sig) = ppr sig
112 ppr (ValD binds) = ppr binds
113 ppr (DefD def) = ppr def
114 ppr (InstD inst) = ppr inst
115 ppr (ForD fd) = ppr fd
116 ppr (FixD fd) = ppr fd
117 ppr (RuleD rd) = ppr rd
118 ppr (DeprecD dd) = ppr dd
122 instance Ord name => Eq (HsDecl name pat) where
123 -- Used only when comparing interfaces,
124 -- at which time only signature and type/class decls
125 (SigD s1) == (SigD s2) = s1 == s2
126 (TyClD d1) == (TyClD d2) = d1 == d2
131 %************************************************************************
133 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
135 %************************************************************************
137 Type and class declarations carry 'implicit names'. In particular:
141 Each data type decl defines
142 a worker name for each constructor
143 to-T and from-T convertors
144 Each class decl defines
145 a tycon for the class
146 a data constructor for that tycon
147 the worker for that constructor
148 a selector for each superclass
150 All have occurrence names that are derived uniquely from their parent declaration.
152 None of these get separate definitions in an interface file; they are
153 fully defined by the data or class decl. But they may *occur* in
154 interface files, of course. Any such occurrence must haul in the
155 relevant type or class decl.
158 - Make up their occurrence names immediately
160 - Ensure they "point to" the parent data/class decl
161 when loading that decl from an interface file
163 - When renaming the decl look them up in the name cache,
164 ensure correct module and provenance is set
166 Type B: Default methods and dictionary functions
167 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
168 Have their own binding in an interface file.
170 Default methods : occurrence name is derived uniquely from the class decl.
171 Dict functions : occurrence name is derived from the instance decl, plus a unique number.
174 - Do *not* make them point to the parent class decl
175 - Interface-file decls: treat just like Type A
176 - Source-file decls: the names aren't in the decl at all;
177 instead the typechecker makes them up
180 data TyClDecl name pat
182 (HsContext name) -- context
183 name -- type constructor
184 [HsTyVarBndr name] -- type variables
185 [ConDecl name] -- data constructors (empty if abstract)
186 Int -- Number of data constructors (valid even if type is abstract)
187 (Maybe [name]) -- derivings; Nothing => not specified
188 -- (i.e., derive default); Just [] => derive
189 -- *nothing*; Just <list> => as you would
193 name -- generic converter functions
194 name -- generic converter functions
196 | TySynonym name -- type constructor
197 [HsTyVarBndr name] -- type variables
198 (HsType name) -- synonym expansion
201 | ClassDecl (HsContext name) -- context...
202 name -- name of the class
203 [HsTyVarBndr name] -- the class type variables
204 [FunDep name] -- functional dependencies
205 [Sig name] -- methods' signatures
206 (MonoBinds name pat) -- default methods
208 [name] -- The names of the tycon, datacon
209 -- wrapper, datacon worker,
210 -- and superclass selectors for this
211 -- class (the first 3 are at the front
212 -- of the list in this order)
213 -- These are filled in as the
214 -- ClassDecl is made.
217 -- Put type signatures in and explain further!!
218 -- The names of the tycon, datacon
219 -- wrapper, datacon worker,
220 -- and superclass selectors for this
221 -- class (the first 3 are at the front
222 -- of the list in this order)
223 -- These are filled in as the
224 toClassDeclNameList (a,b,c,ds) = a:b:c:ds
225 fromClassDeclNameList (a:b:c:ds) = (a,b,c,ds)
227 instance Ord name => Eq (TyClDecl name pat) where
228 -- Used only when building interface files
229 (==) (TyData nd1 cxt1 n1 tvs1 cons1 _ _ _ _ _ _)
230 (TyData nd2 cxt2 n2 tvs2 cons2 _ _ _ _ _ _)
233 eqWithHsTyVars tvs1 tvs2 (\ env ->
234 eq_hsContext env cxt1 cxt2 &&
235 eqListBy (eq_ConDecl env) cons1 cons2
238 (==) (TySynonym n1 tvs1 ty1 _)
239 (TySynonym n2 tvs2 ty2 _)
241 eqWithHsTyVars tvs1 tvs2 (\ env -> eq_hsType env ty1 ty2)
243 (==) (ClassDecl cxt1 n1 tvs1 fds1 sigs1 _ _ _ _ )
244 (ClassDecl cxt2 n2 tvs2 fds2 sigs2 _ _ _ _ )
246 eqWithHsTyVars tvs1 tvs2 (\ env ->
247 eq_hsContext env cxt1 cxt2 &&
248 eqListBy (eq_hsFD env) fds1 fds2 &&
249 eqListBy (eq_cls_sig env) sigs1 sigs2
252 (==) _ _ = False -- default case
255 eq_hsFD env (ns1,ms1) (ns2,ms2)
256 = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
258 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
259 = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
261 -- Ignore the name of the default method.
262 -- This is used for comparing declarations before putting
263 -- them into interface files, and the name of the default
264 -- method isn't relevant
265 (Just (explicit_dm1)) `eq_dm` (Just (explicit_dm2)) = explicit_dm1 == explicit_dm2
266 Nothing `eq_dm` Nothing = True
267 dm1 `eq_dm` dm2 = False
271 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int)
272 -- class, data, newtype, synonym decls
274 = (length [() | ClassDecl _ _ _ _ _ _ _ _ _ <- decls],
275 length [() | TyData DataType _ _ _ _ _ _ _ _ _ _ <- decls],
276 length [() | TyData NewType _ _ _ _ _ _ _ _ _ _ <- decls],
277 length [() | TySynonym _ _ _ _ <- decls])
279 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
281 isSynDecl (TySynonym _ _ _ _) = True
282 isSynDecl other = False
284 isDataDecl (TyData _ _ _ _ _ _ _ _ _ _ _) = True
285 isDataDecl other = False
287 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ _ ) = True
288 isClassDecl other = False
292 instance (Outputable name, Outputable pat)
293 => Outputable (TyClDecl name pat) where
295 ppr (TySynonym tycon tyvars mono_ty src_loc)
296 = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
299 ppr (TyData new_or_data context tycon tyvars condecls ncons derivings pragmas src_loc gen_conv1 gen_conv2) -- The generic names are not printed out ATM
301 (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
302 (pp_condecls condecls ncons)
305 keyword = case new_or_data of
306 NewType -> SLIT("newtype")
307 DataType -> SLIT("data")
309 ppr (ClassDecl context clas tyvars fds sigs methods pragmas _ src_loc)
310 | null sigs -- No "where" part
313 | otherwise -- Laid out
314 = sep [hsep [top_matter, ptext SLIT("where {")],
315 nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
317 top_matter = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
318 ppr_sig sig = ppr sig <> semi
319 pp_methods = getPprStyle $ \ sty ->
320 if ifaceStyle sty then empty else ppr methods
323 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
324 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
326 pp_condecls [] ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
327 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
329 pp_tydecl pp_head pp_decl_rhs derivings
330 = hang pp_head 4 (sep [
334 Just ds -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
338 A type for recording what types a datatype should be specialised to.
339 It's called a ``Sig'' because it's sort of like a ``type signature''
340 for an datatype declaration.
343 data SpecDataSig name
344 = SpecDataSig name -- tycon to specialise
348 instance (Outputable name)
349 => Outputable (SpecDataSig name) where
351 ppr (SpecDataSig tycon ty _)
352 = hsep [text "{-# SPECIALIZE data", ppr ty, text "#-}"]
355 %************************************************************************
357 \subsection[ConDecl]{A data-constructor declaration}
359 %************************************************************************
363 = ConDecl name -- Constructor name; this is used for the
364 -- DataCon itself, and for the user-callable wrapper Id
366 name -- Name of the constructor's 'worker Id'
367 -- Filled in as the ConDecl is built
369 [HsTyVarBndr name] -- Existentially quantified type variables
370 (HsContext name) -- ...and context
371 -- If both are empty then there are no existentials
377 = VanillaCon -- prefix-style con decl
380 | InfixCon -- infix-style con decl
384 | RecCon -- record-style con decl
385 [([name], BangType name)] -- list of "fields"
387 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
388 (ConDecl n2 _ tvs2 cxt2 cds2 _)
390 (eqWithHsTyVars tvs1 tvs2 $ \ env ->
391 eq_hsContext env cxt1 cxt2 &&
392 eq_ConDetails env cds1 cds2)
394 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
395 = eqListBy (eq_btype env) bts1 bts2
396 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
397 = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
398 eq_ConDetails env (RecCon fs1) (RecCon fs2)
399 = eqListBy (eq_fld env) fs1 fs2
400 eq_ConDetails env _ _ = False
402 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
406 = Banged (HsType name) -- HsType: to allow Haskell extensions
407 | Unbanged (HsType name) -- (MonoType only needed for straight Haskell)
408 | Unpacked (HsType name) -- Field is strict and to be unpacked if poss.
410 getBangType (Banged ty) = ty
411 getBangType (Unbanged ty) = ty
412 getBangType (Unpacked ty) = ty
414 eq_btype env (Banged t1) (Banged t2) = eq_hsType env t1 t2
415 eq_btype env (Unbanged t1) (Unbanged t2) = eq_hsType env t1 t2
416 eq_btype env (Unpacked t1) (Unpacked t2) = eq_hsType env t1 t2
417 eq_btype env _ _ = False
421 instance (Outputable name) => Outputable (ConDecl name) where
422 ppr (ConDecl con _ tvs cxt con_details loc)
423 = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
425 ppr_con_details con (InfixCon ty1 ty2)
426 = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
428 ppr_con_details con (VanillaCon tys)
429 = ppr con <+> hsep (map (ppr_bang) tys)
431 ppr_con_details con (RecCon fields)
432 = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
434 ppr_field (ns, ty) = hsep (map (ppr) ns) <+>
438 instance Outputable name => Outputable (BangType name) where
441 ppr_bang (Banged ty) = ptext SLIT("!") <> pprParendHsType ty
442 ppr_bang (Unbanged ty) = pprParendHsType ty
443 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
447 %************************************************************************
449 \subsection[InstDecl]{An instance declaration
451 %************************************************************************
454 data InstDecl name pat
455 = InstDecl (HsType name) -- Context => Class Instance-type
456 -- Using a polytype means that the renamer conveniently
457 -- figures out the quantified type variables for us.
461 [Sig name] -- User-supplied pragmatic info
463 (Maybe name) -- Name for the dictionary function
464 -- Nothing for source-file instance decls
470 instance (Outputable name, Outputable pat)
471 => Outputable (InstDecl name pat) where
473 ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
474 = getPprStyle $ \ sty ->
475 if ifaceStyle sty then
476 hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
478 vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
482 pp_dfun = case maybe_dfun_name of
488 instance Ord name => Eq (InstDecl name pat) where
489 -- Used for interface comparison only, so don't compare bindings
490 (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
491 = inst_ty1 == inst_ty2 && dfun1 == dfun2
495 %************************************************************************
497 \subsection[DefaultDecl]{A @default@ declaration}
499 %************************************************************************
501 There can only be one default declaration per module, but it is hard
502 for the parser to check that; we pass them all through in the abstract
503 syntax, and that restriction must be checked in the front end.
506 data DefaultDecl name
507 = DefaultDecl [HsType name]
510 instance (Outputable name)
511 => Outputable (DefaultDecl name) where
513 ppr (DefaultDecl tys src_loc)
514 = ptext SLIT("default") <+> parens (interpp'SP tys)
517 %************************************************************************
519 \subsection{Foreign function interface declaration}
521 %************************************************************************
524 data ForeignDecl name =
533 instance (Outputable name)
534 => Outputable (ForeignDecl name) where
536 ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
537 = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+>
538 ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
540 (ppr_imp_exp, ppr_unsafe) =
542 FoLabel -> (ptext SLIT("label"), empty)
543 FoExport -> (ptext SLIT("export"), empty)
545 | us -> (ptext SLIT("import"), ptext SLIT("unsafe"))
546 | otherwise -> (ptext SLIT("import"), empty)
551 | FoImport Bool -- True => unsafe call.
555 | ExtName CLabelString -- The external name of the foreign thing,
556 (Maybe CLabelString) -- and optionally its DLL or module name
557 -- Both of these are completely unencoded;
558 -- we just print them as they are
560 isDynamicExtName :: ExtName -> Bool
561 isDynamicExtName Dynamic = True
562 isDynamicExtName _ = False
564 extNameStatic :: ExtName -> CLabelString
565 extNameStatic (ExtName f _) = f
566 extNameStatic Dynamic = panic "staticExtName: Dynamic - shouldn't ever happen."
568 instance Outputable ExtName where
569 ppr Dynamic = ptext SLIT("dynamic")
570 ppr (ExtName nm mb_mod) =
571 case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+>
572 doubleQuotes (pprCLabelString nm)
575 %************************************************************************
577 \subsection{Transformation rules}
579 %************************************************************************
582 data RuleDecl name pat
583 = HsRule -- Source rule
584 FAST_STRING -- Rule name
585 [name] -- Forall'd tyvars, filled in by the renamer with
586 -- tyvars mentioned in sigs; then filled out by typechecker
587 [RuleBndr name] -- Forall'd term vars
588 (HsExpr name pat) -- LHS
589 (HsExpr name pat) -- RHS
592 | IfaceRule -- One that's come in from an interface file; pre-typecheck
594 [UfBinder name] -- Tyvars and term vars
596 [UfExpr name] -- Args of LHS
597 (UfExpr name) -- Pre typecheck
600 | IfaceRuleOut -- Post typecheck
607 | RuleBndrSig name (HsType name)
609 instance Ord name => Eq (RuleDecl name pat) where
610 -- Works for IfaceRules only; used when comparing interface file versions
611 (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
612 = n1==n2 && f1 == f2 &&
613 eq_ufBinders emptyEqHsEnv bs1 bs2 (\env ->
614 eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
616 instance (Outputable name, Outputable pat)
617 => Outputable (RuleDecl name pat) where
618 ppr (HsRule name tvs ns lhs rhs loc)
619 = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
620 pp_forall, ppr lhs, equals <+> ppr rhs,
623 pp_forall | null tvs && null ns = empty
624 | otherwise = text "forall" <+>
625 fsep (map ppr tvs ++ map ppr ns)
628 ppr (IfaceRule name tpl_vars fn tpl_args rhs loc)
629 = hsep [ doubleQuotes (ptext name),
630 ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
631 ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
632 ptext SLIT("=") <+> ppr rhs
635 ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
637 instance Outputable name => Outputable (RuleBndr name) where
638 ppr (RuleBndr name) = ppr name
639 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
641 toHsRule id (BuiltinRule _)
642 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
644 toHsRule id (Rule name bndrs args rhs)
645 = IfaceRule name (map toUfBndr bndrs) (toRdrName id)
646 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
649 = IfaceRule SLIT("bogus") [] (toRdrName id) [] (UfVar (toRdrName id)) noSrcLoc
653 %************************************************************************
655 \subsection[DeprecDecl]{Deprecations}
657 %************************************************************************
659 We use exported entities for things to deprecate. Cunning trick (hack?):
660 `IEModuleContents undefined' is used for module deprecation.
663 data DeprecDecl name = Deprecation (IE name) DeprecTxt SrcLoc
665 type DeprecTxt = FAST_STRING -- reason/explanation for deprecation
667 instance Outputable name => Outputable (DeprecDecl name) where
668 ppr (Deprecation (IEModuleContents _) txt _)
669 = hsep [text "{-# DEPRECATED", doubleQuotes (ppr txt), text "#-}"]
670 ppr (Deprecation thing txt _)
671 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]