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 DeprecDecl(..), DeprecTxt,
17 hsDeclName, instDeclName, tyClDeclName, tyClDeclNames,
18 isClassDecl, isSynDecl, isDataDecl, isIfaceSigDecl, countTyClDecls,
19 mkClassDeclSysNames, isIfaceRuleDecl,
23 #include "HsVersions.h"
26 import HsBinds ( HsBinds, MonoBinds, Sig(..), FixitySig(..) )
27 import HsExpr ( HsExpr )
29 import PprCore ( pprCoreRule )
30 import HsCore ( UfExpr, UfBinder, HsIdInfo, pprHsIdInfo,
31 eq_ufBinders, eq_ufExpr, pprUfExpr
33 import CoreSyn ( CoreRule(..) )
34 import BasicTypes ( NewOrData(..) )
35 import CallConv ( CallConv, pprCallConv )
38 import FunDeps ( pprFundeps )
39 import Class ( FunDep )
40 import CStrings ( CLabelString, pprCLabelString )
42 import SrcLoc ( SrcLoc )
46 %************************************************************************
48 \subsection[HsDecl]{Declarations}
50 %************************************************************************
54 = TyClD (TyClDecl name pat)
55 | InstD (InstDecl name pat)
56 | DefD (DefaultDecl name)
57 | ValD (HsBinds name pat)
58 | ForD (ForeignDecl 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 (ForD (ForeignDecl name _ _ _ _ _)) = name
85 hsDeclName (FixD (FixitySig name _ _)) = name
86 -- Others don't make sense
88 hsDeclName x = pprPanic "HsDecls.hsDeclName" (ppr x)
92 instDeclName :: InstDecl name pat -> name
93 instDeclName (InstDecl _ _ _ (Just name) _) = name
98 instance (Outputable name, Outputable pat)
99 => Outputable (HsDecl name pat) where
101 ppr (TyClD dcl) = ppr dcl
102 ppr (ValD binds) = ppr binds
103 ppr (DefD def) = ppr def
104 ppr (InstD inst) = ppr inst
105 ppr (ForD fd) = ppr fd
106 ppr (FixD fd) = ppr fd
107 ppr (RuleD rd) = ppr rd
108 ppr (DeprecD dd) = ppr dd
112 instance Ord name => Eq (HsDecl name pat) where
113 -- Used only when comparing interfaces,
114 -- at which time only signature and type/class decls
115 (TyClD d1) == (TyClD d2) = d1 == d2
120 %************************************************************************
122 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
124 %************************************************************************
126 Type and class declarations carry 'implicit names'. In particular:
130 Each data type decl defines
131 a worker name for each constructor
132 to-T and from-T convertors
133 Each class decl defines
134 a tycon for the class
135 a data constructor for that tycon
136 the worker for that constructor
137 a selector for each superclass
139 All have occurrence names that are derived uniquely from their parent declaration.
141 None of these get separate definitions in an interface file; they are
142 fully defined by the data or class decl. But they may *occur* in
143 interface files, of course. Any such occurrence must haul in the
144 relevant type or class decl.
147 - Make up their occurrence names immediately
149 - Ensure they "point to" the parent data/class decl
150 when loading that decl from an interface file
152 - When renaming the decl look them up in the name cache,
153 ensure correct module and provenance is set
155 Type B: Default methods and dictionary functions
156 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
157 Have their own binding in an interface file.
159 Default methods : occurrence name is derived uniquely from the class decl.
160 Dict functions : occurrence name is derived from the instance decl, plus a unique number.
163 - Do *not* make them point to the parent class decl
164 - Interface-file decls: treat just like Type A
165 - Source-file decls: the names aren't in the decl at all;
166 instead the typechecker makes them up
169 data TyClDecl name pat
170 = IfaceSig name -- It may seem odd to classify an interface-file signature
171 (HsType name) -- as a 'TyClDecl', but it's very convenient. These three
172 [HsIdInfo name] -- are the kind that appear in interface files.
176 (HsContext name) -- context
177 name -- type constructor
178 [HsTyVarBndr name] -- type variables
179 [ConDecl name] -- data constructors (empty if abstract)
180 Int -- Number of data constructors (valid even if type is abstract)
181 (Maybe [name]) -- derivings; Nothing => not specified
182 -- (i.e., derive default); Just [] => derive
183 -- *nothing*; Just <list> => as you would
186 name -- generic converter functions
187 name -- generic converter functions
189 | TySynonym name -- type constructor
190 [HsTyVarBndr name] -- type variables
191 (HsType name) -- synonym expansion
194 | ClassDecl (HsContext name) -- context...
195 name -- name of the class
196 [HsTyVarBndr name] -- the class type variables
197 [FunDep name] -- functional dependencies
198 [Sig name] -- methods' signatures
199 (MonoBinds name pat) -- default methods
200 (ClassDeclSysNames name)
207 isIfaceSigDecl, isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
209 isIfaceSigDecl (IfaceSig _ _ _ _) = True
210 isIfaceSigDecl other = False
212 isSynDecl (TySynonym _ _ _ _) = True
213 isSynDecl other = False
215 isDataDecl (TyData _ _ _ _ _ _ _ _ _ _) = True
216 isDataDecl other = False
218 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ ) = True
219 isClassDecl other = False
225 tyClDeclName :: TyClDecl name pat -> name
226 tyClDeclName (IfaceSig name _ _ _) = name
227 tyClDeclName (TyData _ _ name _ _ _ _ _ _ _) = name
228 tyClDeclName (TySynonym name _ _ _) = name
229 tyClDeclName (ClassDecl _ name _ _ _ _ _ _) = name
232 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
233 -- Returns all the binding names of the decl, along with their SrcLocs
234 -- The first one is guaranteed to be the name of the decl
235 -- For record fields, the first one counts as the SrcLoc
236 -- We use the equality to filter out duplicate field names
238 tyClDeclNames (TySynonym name _ _ loc)
241 tyClDeclNames (ClassDecl _ name _ _ sigs _ _ loc)
242 = (name,loc) : [(name,loc) | ClassOpSig n _ _ loc <- sigs]
244 tyClDeclNames (TyData _ _ name _ cons _ _ loc _ _)
245 = (name,loc) : conDeclsNames cons
247 tyClDeclNames (IfaceSig _ _ _ _) = []
249 type ClassDeclSysNames name = [name]
250 -- [tycon, datacon wrapper, datacon worker,
251 -- superclass selector 1, ..., superclass selector n]
252 -- They are kept in a list rather than a tuple to make the
255 mkClassDeclSysNames :: (name, name, name, [name]) -> [name]
256 getClassDeclSysNames :: [name] -> (name, name, name, [name])
257 mkClassDeclSysNames (a,b,c,ds) = a:b:c:ds
258 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
262 instance Ord name => Eq (TyClDecl name pat) where
263 -- Used only when building interface files
264 (==) (IfaceSig n1 t1 i1 _)
265 (IfaceSig n2 t2 i2 _) = n1==n2 && t1==t2 && i1==i2
267 (==) (TyData nd1 cxt1 n1 tvs1 cons1 _ _ _ _ _)
268 (TyData nd2 cxt2 n2 tvs2 cons2 _ _ _ _ _)
271 eqWithHsTyVars tvs1 tvs2 (\ env ->
272 eq_hsContext env cxt1 cxt2 &&
273 eqListBy (eq_ConDecl env) cons1 cons2
276 (==) (TySynonym n1 tvs1 ty1 _)
277 (TySynonym n2 tvs2 ty2 _)
279 eqWithHsTyVars tvs1 tvs2 (\ env -> eq_hsType env ty1 ty2)
281 (==) (ClassDecl cxt1 n1 tvs1 fds1 sigs1 _ _ _ )
282 (ClassDecl cxt2 n2 tvs2 fds2 sigs2 _ _ _ )
284 eqWithHsTyVars tvs1 tvs2 (\ env ->
285 eq_hsContext env cxt1 cxt2 &&
286 eqListBy (eq_hsFD env) fds1 fds2 &&
287 eqListBy (eq_cls_sig env) sigs1 sigs2
290 (==) _ _ = False -- default case
293 eq_hsFD env (ns1,ms1) (ns2,ms2)
294 = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
296 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
297 = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
299 -- Ignore the name of the default method.
300 -- This is used for comparing declarations before putting
301 -- them into interface files, and the name of the default
302 -- method isn't relevant
303 (Just (explicit_dm1)) `eq_dm` (Just (explicit_dm2)) = explicit_dm1 == explicit_dm2
304 Nothing `eq_dm` Nothing = True
305 dm1 `eq_dm` dm2 = False
309 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int, Int)
310 -- class, data, newtype, synonym decls
312 = (length [() | ClassDecl _ _ _ _ _ _ _ _ <- decls],
313 length [() | TyData DataType _ _ _ _ _ _ _ _ _ <- decls],
314 length [() | TyData NewType _ _ _ _ _ _ _ _ _ <- decls],
315 length [() | TySynonym _ _ _ _ <- decls],
316 length [() | IfaceSig _ _ _ _ <- decls])
320 instance (Outputable name, Outputable pat)
321 => Outputable (TyClDecl name pat) where
323 ppr (IfaceSig var ty info _) = hsep [ppr var, dcolon, ppr ty, pprHsIdInfo info]
325 ppr (TySynonym tycon tyvars mono_ty src_loc)
326 = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
329 ppr (TyData new_or_data context tycon tyvars condecls ncons
330 derivings src_loc gen_conv1 gen_conv2) -- The generic names are not printed out ATM
332 (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
333 (pp_condecls condecls ncons)
336 keyword = case new_or_data of
337 NewType -> SLIT("newtype")
338 DataType -> SLIT("data")
340 ppr (ClassDecl context clas tyvars fds sigs methods _ src_loc)
341 | null sigs -- No "where" part
344 | otherwise -- Laid out
345 = sep [hsep [top_matter, ptext SLIT("where {")],
346 nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
348 top_matter = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
349 ppr_sig sig = ppr sig <> semi
350 pp_methods = getPprStyle $ \ sty ->
351 if ifaceStyle sty then empty else ppr methods
353 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
354 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
356 pp_condecls [] ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
357 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
359 pp_tydecl pp_head pp_decl_rhs derivings
360 = hang pp_head 4 (sep [
364 Just ds -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
369 %************************************************************************
371 \subsection[ConDecl]{A data-constructor declaration}
373 %************************************************************************
377 = ConDecl name -- Constructor name; this is used for the
378 -- DataCon itself, and for the user-callable wrapper Id
380 name -- Name of the constructor's 'worker Id'
381 -- Filled in as the ConDecl is built
383 [HsTyVarBndr name] -- Existentially quantified type variables
384 (HsContext name) -- ...and context
385 -- If both are empty then there are no existentials
391 = VanillaCon -- prefix-style con decl
394 | InfixCon -- infix-style con decl
398 | RecCon -- record-style con decl
399 [([name], BangType name)] -- list of "fields"
403 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
404 -- See tyClDeclNames for what this does
405 -- The function is boringly complicated because of the records
406 -- And since we only have equality, we have to be a little careful
408 = snd (foldl do_one ([], []) cons)
410 do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
411 = do_details ((name,loc):acc) details
413 do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
414 do_details acc other = (flds_seen, acc)
416 do_fld acc (flds, _) = foldl do_fld1 acc flds
418 do_fld1 (flds_seen, acc) fld
419 | fld `elem` flds_seen = (flds_seen,acc)
420 | otherwise = (fld:flds_seen, (fld,loc):acc)
424 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
425 (ConDecl n2 _ tvs2 cxt2 cds2 _)
427 (eqWithHsTyVars tvs1 tvs2 $ \ env ->
428 eq_hsContext env cxt1 cxt2 &&
429 eq_ConDetails env cds1 cds2)
431 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
432 = eqListBy (eq_btype env) bts1 bts2
433 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
434 = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
435 eq_ConDetails env (RecCon fs1) (RecCon fs2)
436 = eqListBy (eq_fld env) fs1 fs2
437 eq_ConDetails env _ _ = False
439 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
444 = Banged (HsType name) -- HsType: to allow Haskell extensions
445 | Unbanged (HsType name) -- (MonoType only needed for straight Haskell)
446 | Unpacked (HsType name) -- Field is strict and to be unpacked if poss.
448 getBangType (Banged ty) = ty
449 getBangType (Unbanged ty) = ty
450 getBangType (Unpacked ty) = ty
452 eq_btype env (Banged t1) (Banged t2) = eq_hsType env t1 t2
453 eq_btype env (Unbanged t1) (Unbanged t2) = eq_hsType env t1 t2
454 eq_btype env (Unpacked t1) (Unpacked t2) = eq_hsType env t1 t2
455 eq_btype env _ _ = False
459 instance (Outputable name) => Outputable (ConDecl name) where
460 ppr (ConDecl con _ tvs cxt con_details loc)
461 = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
463 ppr_con_details con (InfixCon ty1 ty2)
464 = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
466 ppr_con_details con (VanillaCon tys)
467 = ppr con <+> hsep (map (ppr_bang) tys)
469 ppr_con_details con (RecCon fields)
470 = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
472 ppr_field (ns, ty) = hsep (map (ppr) ns) <+>
476 instance Outputable name => Outputable (BangType name) where
479 ppr_bang (Banged ty) = ptext SLIT("!") <> pprParendHsType ty
480 ppr_bang (Unbanged ty) = pprParendHsType ty
481 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
485 %************************************************************************
487 \subsection[InstDecl]{An instance declaration
489 %************************************************************************
492 data InstDecl name pat
493 = InstDecl (HsType name) -- Context => Class Instance-type
494 -- Using a polytype means that the renamer conveniently
495 -- figures out the quantified type variables for us.
499 [Sig name] -- User-supplied pragmatic info
501 (Maybe name) -- Name for the dictionary function
502 -- Nothing for source-file instance decls
508 instance (Outputable name, Outputable pat)
509 => Outputable (InstDecl name pat) where
511 ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
512 = getPprStyle $ \ sty ->
513 if ifaceStyle sty then
514 hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
516 vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
520 pp_dfun = case maybe_dfun_name of
526 instance Ord name => Eq (InstDecl name pat) where
527 -- Used for interface comparison only, so don't compare bindings
528 (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
529 = inst_ty1 == inst_ty2 && dfun1 == dfun2
533 %************************************************************************
535 \subsection[DefaultDecl]{A @default@ declaration}
537 %************************************************************************
539 There can only be one default declaration per module, but it is hard
540 for the parser to check that; we pass them all through in the abstract
541 syntax, and that restriction must be checked in the front end.
544 data DefaultDecl name
545 = DefaultDecl [HsType name]
548 instance (Outputable name)
549 => Outputable (DefaultDecl name) where
551 ppr (DefaultDecl tys src_loc)
552 = ptext SLIT("default") <+> parens (interpp'SP tys)
555 %************************************************************************
557 \subsection{Foreign function interface declaration}
559 %************************************************************************
562 data ForeignDecl name =
571 instance (Outputable name)
572 => Outputable (ForeignDecl name) where
574 ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
575 = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+>
576 ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
578 (ppr_imp_exp, ppr_unsafe) =
580 FoLabel -> (ptext SLIT("label"), empty)
581 FoExport -> (ptext SLIT("export"), empty)
583 | us -> (ptext SLIT("import"), ptext SLIT("unsafe"))
584 | otherwise -> (ptext SLIT("import"), empty)
589 | FoImport Bool -- True => unsafe call.
593 | ExtName CLabelString -- The external name of the foreign thing,
594 (Maybe CLabelString) -- and optionally its DLL or module name
595 -- Both of these are completely unencoded;
596 -- we just print them as they are
598 isDynamicExtName :: ExtName -> Bool
599 isDynamicExtName Dynamic = True
600 isDynamicExtName _ = False
602 extNameStatic :: ExtName -> CLabelString
603 extNameStatic (ExtName f _) = f
604 extNameStatic Dynamic = panic "staticExtName: Dynamic - shouldn't ever happen."
606 instance Outputable ExtName where
607 ppr Dynamic = ptext SLIT("dynamic")
608 ppr (ExtName nm mb_mod) =
609 case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+>
610 doubleQuotes (pprCLabelString nm)
613 %************************************************************************
615 \subsection{Transformation rules}
617 %************************************************************************
620 data RuleDecl name pat
621 = HsRule -- Source rule
622 FAST_STRING -- Rule name
623 [name] -- Forall'd tyvars, filled in by the renamer with
624 -- tyvars mentioned in sigs; then filled out by typechecker
625 [RuleBndr name] -- Forall'd term vars
626 (HsExpr name pat) -- LHS
627 (HsExpr name pat) -- RHS
630 | IfaceRule -- One that's come in from an interface file; pre-typecheck
632 [UfBinder name] -- Tyvars and term vars
634 [UfExpr name] -- Args of LHS
635 (UfExpr name) -- Pre typecheck
638 | IfaceRuleOut -- Post typecheck
642 isIfaceRuleDecl (HsRule _ _ _ _ _ _) = False
643 isIfaceRuleDecl other = True
647 | RuleBndrSig name (HsType name)
649 instance Ord name => Eq (RuleDecl name pat) where
650 -- Works for IfaceRules only; used when comparing interface file versions
651 (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
652 = n1==n2 && f1 == f2 &&
653 eq_ufBinders emptyEqHsEnv bs1 bs2 (\env ->
654 eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
656 instance (Outputable name, Outputable pat)
657 => Outputable (RuleDecl name pat) where
658 ppr (HsRule name tvs ns lhs rhs loc)
659 = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
660 pp_forall, ppr lhs, equals <+> ppr rhs,
663 pp_forall | null tvs && null ns = empty
664 | otherwise = text "forall" <+>
665 fsep (map ppr tvs ++ map ppr ns)
668 ppr (IfaceRule name tpl_vars fn tpl_args rhs loc)
669 = hsep [ doubleQuotes (ptext name),
670 ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
671 ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
672 ptext SLIT("=") <+> ppr rhs
675 ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
677 instance Outputable name => Outputable (RuleBndr name) where
678 ppr (RuleBndr name) = ppr name
679 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
683 %************************************************************************
685 \subsection[DeprecDecl]{Deprecations}
687 %************************************************************************
689 We use exported entities for things to deprecate.
692 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
694 type DeprecTxt = FAST_STRING -- reason/explanation for deprecation
696 instance Outputable name => Outputable (DeprecDecl name) where
697 ppr (Deprecation thing txt _)
698 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]