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, countTyClDecls, toHsRule,
23 #include "HsVersions.h"
26 import HsBinds ( HsBinds, MonoBinds, Sig(..), FixitySig(..) )
27 import HsExpr ( HsExpr )
29 import PprCore ( pprCoreRule )
30 import HsCore ( UfExpr(UfVar), UfBinder, HsIdInfo, pprHsIdInfo,
31 eq_ufBinders, eq_ufExpr, pprUfExpr, toUfExpr, toUfBndr
33 import CoreSyn ( CoreRule(..) )
34 import BasicTypes ( NewOrData(..) )
35 import CallConv ( CallConv, pprCallConv )
36 import Name ( getName )
39 import FunDeps ( pprFundeps )
40 import Class ( FunDep )
41 import CStrings ( CLabelString, pprCLabelString )
43 import SrcLoc ( SrcLoc, noSrcLoc )
47 %************************************************************************
49 \subsection[HsDecl]{Declarations}
51 %************************************************************************
55 = TyClD (TyClDecl name pat)
56 | InstD (InstDecl name pat)
57 | DefD (DefaultDecl name)
58 | ValD (HsBinds name pat)
59 | ForD (ForeignDecl name)
60 | FixD (FixitySig name)
61 | DeprecD (DeprecDecl name)
62 | RuleD (RuleDecl name pat)
64 -- NB: all top-level fixity decls are contained EITHER
66 -- OR in the ClassDecls in TyClDs
69 -- a) data constructors
70 -- b) class methods (but they can be also done in the
71 -- signatures of class decls)
72 -- c) imported functions (that have an IfacSig)
75 -- The latter is for class methods only
80 hsDeclName :: (Outputable name, Outputable pat)
81 => HsDecl name pat -> name
83 hsDeclName (TyClD decl) = tyClDeclName decl
84 hsDeclName (InstD decl) = instDeclName decl
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 instDeclName :: InstDecl name pat -> name
94 instDeclName (InstDecl _ _ _ (Just name) _) = name
99 instance (Outputable name, Outputable pat)
100 => Outputable (HsDecl name pat) where
102 ppr (TyClD dcl) = ppr dcl
103 ppr (ValD binds) = ppr binds
104 ppr (DefD def) = ppr def
105 ppr (InstD inst) = ppr inst
106 ppr (ForD fd) = ppr fd
107 ppr (FixD fd) = ppr fd
108 ppr (RuleD rd) = ppr rd
109 ppr (DeprecD dd) = ppr dd
113 instance Ord name => Eq (HsDecl name pat) where
114 -- Used only when comparing interfaces,
115 -- at which time only signature and type/class decls
116 (TyClD d1) == (TyClD d2) = d1 == d2
121 %************************************************************************
123 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
125 %************************************************************************
127 Type and class declarations carry 'implicit names'. In particular:
131 Each data type decl defines
132 a worker name for each constructor
133 to-T and from-T convertors
134 Each class decl defines
135 a tycon for the class
136 a data constructor for that tycon
137 the worker for that constructor
138 a selector for each superclass
140 All have occurrence names that are derived uniquely from their parent declaration.
142 None of these get separate definitions in an interface file; they are
143 fully defined by the data or class decl. But they may *occur* in
144 interface files, of course. Any such occurrence must haul in the
145 relevant type or class decl.
148 - Make up their occurrence names immediately
150 - Ensure they "point to" the parent data/class decl
151 when loading that decl from an interface file
153 - When renaming the decl look them up in the name cache,
154 ensure correct module and provenance is set
156 Type B: Default methods and dictionary functions
157 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
158 Have their own binding in an interface file.
160 Default methods : occurrence name is derived uniquely from the class decl.
161 Dict functions : occurrence name is derived from the instance decl, plus a unique number.
164 - Do *not* make them point to the parent class decl
165 - Interface-file decls: treat just like Type A
166 - Source-file decls: the names aren't in the decl at all;
167 instead the typechecker makes them up
170 data TyClDecl name pat
171 = IfaceSig name -- It may seem odd to classify an interface-file signature
172 (HsType name) -- as a 'TyClDecl', but it's very convenient. These three
173 [HsIdInfo name] -- are the kind that appear in interface files.
177 (HsContext name) -- context
178 name -- type constructor
179 [HsTyVarBndr name] -- type variables
180 [ConDecl name] -- data constructors (empty if abstract)
181 Int -- Number of data constructors (valid even if type is abstract)
182 (Maybe [name]) -- derivings; Nothing => not specified
183 -- (i.e., derive default); Just [] => derive
184 -- *nothing*; Just <list> => as you would
187 name -- generic converter functions
188 name -- generic converter functions
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
201 (ClassDeclSysNames name)
204 tyClDeclName :: TyClDecl name pat -> name
205 tyClDeclName (IfaceSig name _ _ _) = name
206 tyClDeclName (TyData _ _ name _ _ _ _ _ _ _) = name
207 tyClDeclName (TySynonym name _ _ _) = name
208 tyClDeclName (ClassDecl _ name _ _ _ _ _ _) = name
211 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
212 -- Returns all the binding names of the decl, along with their SrcLocs
213 -- The first one is guaranteed to be the name of the decl
214 -- For record fields, the first one counts as the SrcLoc
215 -- We use the equality to filter out duplicate field names
217 tyClDeclNames (TySynonym name _ _ loc)
220 tyClDeclNames (ClassDecl _ name _ _ sigs _ _ loc)
221 = (name,loc) : [(name,loc) | ClassOpSig n _ _ loc <- sigs]
223 tyClDeclNames (TyData _ _ name _ cons _ _ loc _ _)
224 = (name,loc) : conDeclsNames cons
226 tyClDeclNames (IfaceSig _ _ _ _) = []
228 type ClassDeclSysNames name = [name]
229 -- [tycon, datacon wrapper, datacon worker,
230 -- superclass selector 1, ..., superclass selector n]
231 -- They are kept in a list rather than a tuple to make the
234 mkClassDeclSysNames :: (name, name, name, [name]) -> [name]
235 getClassDeclSysNames :: [name] -> (name, name, name, [name])
236 mkClassDeclSysNames (a,b,c,ds) = a:b:c:ds
237 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
242 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
244 isSynDecl (TySynonym _ _ _ _) = True
245 isSynDecl other = False
247 isDataDecl (TyData _ _ _ _ _ _ _ _ _ _) = True
248 isDataDecl other = False
250 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ ) = True
251 isClassDecl other = False
255 instance Ord name => Eq (TyClDecl name pat) where
256 -- Used only when building interface files
257 (==) (IfaceSig n1 t1 i1 _)
258 (IfaceSig n2 t2 i2 _) = n1==n2 && t1==t2 && i1==i2
260 (==) (TyData nd1 cxt1 n1 tvs1 cons1 _ _ _ _ _)
261 (TyData nd2 cxt2 n2 tvs2 cons2 _ _ _ _ _)
264 eqWithHsTyVars tvs1 tvs2 (\ env ->
265 eq_hsContext env cxt1 cxt2 &&
266 eqListBy (eq_ConDecl env) cons1 cons2
269 (==) (TySynonym n1 tvs1 ty1 _)
270 (TySynonym n2 tvs2 ty2 _)
272 eqWithHsTyVars tvs1 tvs2 (\ env -> eq_hsType env ty1 ty2)
274 (==) (ClassDecl cxt1 n1 tvs1 fds1 sigs1 _ _ _ )
275 (ClassDecl cxt2 n2 tvs2 fds2 sigs2 _ _ _ )
277 eqWithHsTyVars tvs1 tvs2 (\ env ->
278 eq_hsContext env cxt1 cxt2 &&
279 eqListBy (eq_hsFD env) fds1 fds2 &&
280 eqListBy (eq_cls_sig env) sigs1 sigs2
283 (==) _ _ = False -- default case
286 eq_hsFD env (ns1,ms1) (ns2,ms2)
287 = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
289 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
290 = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
292 -- Ignore the name of the default method.
293 -- This is used for comparing declarations before putting
294 -- them into interface files, and the name of the default
295 -- method isn't relevant
296 (Just (explicit_dm1)) `eq_dm` (Just (explicit_dm2)) = explicit_dm1 == explicit_dm2
297 Nothing `eq_dm` Nothing = True
298 dm1 `eq_dm` dm2 = False
302 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int, Int)
303 -- class, data, newtype, synonym decls
305 = (length [() | ClassDecl _ _ _ _ _ _ _ _ <- decls],
306 length [() | TyData DataType _ _ _ _ _ _ _ _ _ <- decls],
307 length [() | TyData NewType _ _ _ _ _ _ _ _ _ <- decls],
308 length [() | TySynonym _ _ _ _ <- decls],
309 length [() | IfaceSig _ _ _ _ <- decls])
313 instance (Outputable name, Outputable pat)
314 => Outputable (TyClDecl name pat) where
316 ppr (IfaceSig var ty info _) = hsep [ppr var, dcolon, ppr ty, pprHsIdInfo info]
318 ppr (TySynonym tycon tyvars mono_ty src_loc)
319 = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
322 ppr (TyData new_or_data context tycon tyvars condecls ncons
323 derivings src_loc gen_conv1 gen_conv2) -- The generic names are not printed out ATM
325 (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
326 (pp_condecls condecls ncons)
329 keyword = case new_or_data of
330 NewType -> SLIT("newtype")
331 DataType -> SLIT("data")
333 ppr (ClassDecl context clas tyvars fds sigs methods _ src_loc)
334 | null sigs -- No "where" part
337 | otherwise -- Laid out
338 = sep [hsep [top_matter, ptext SLIT("where {")],
339 nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
341 top_matter = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
342 ppr_sig sig = ppr sig <> semi
343 pp_methods = getPprStyle $ \ sty ->
344 if ifaceStyle sty then empty else ppr methods
346 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
347 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
349 pp_condecls [] ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
350 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
352 pp_tydecl pp_head pp_decl_rhs derivings
353 = hang pp_head 4 (sep [
357 Just ds -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
362 %************************************************************************
364 \subsection[ConDecl]{A data-constructor declaration}
366 %************************************************************************
370 = ConDecl name -- Constructor name; this is used for the
371 -- DataCon itself, and for the user-callable wrapper Id
373 name -- Name of the constructor's 'worker Id'
374 -- Filled in as the ConDecl is built
376 [HsTyVarBndr name] -- Existentially quantified type variables
377 (HsContext name) -- ...and context
378 -- If both are empty then there are no existentials
384 = VanillaCon -- prefix-style con decl
387 | InfixCon -- infix-style con decl
391 | RecCon -- record-style con decl
392 [([name], BangType name)] -- list of "fields"
396 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
397 -- See tyClDeclNames for what this does
398 -- The function is boringly complicated because of the records
399 -- And since we only have equality, we have to be a little careful
401 = snd (foldl do_one ([], []) cons)
403 do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
404 = do_details ((name,loc):acc) details
406 do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
407 do_details acc other = (flds_seen, acc)
409 do_fld acc (flds, _) = foldl do_fld1 acc flds
411 do_fld1 (flds_seen, acc) fld
412 | fld `elem` flds_seen = (flds_seen,acc)
413 | otherwise = (fld:flds_seen, (fld,loc):acc)
417 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
418 (ConDecl n2 _ tvs2 cxt2 cds2 _)
420 (eqWithHsTyVars tvs1 tvs2 $ \ env ->
421 eq_hsContext env cxt1 cxt2 &&
422 eq_ConDetails env cds1 cds2)
424 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
425 = eqListBy (eq_btype env) bts1 bts2
426 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
427 = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
428 eq_ConDetails env (RecCon fs1) (RecCon fs2)
429 = eqListBy (eq_fld env) fs1 fs2
430 eq_ConDetails env _ _ = False
432 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
437 = Banged (HsType name) -- HsType: to allow Haskell extensions
438 | Unbanged (HsType name) -- (MonoType only needed for straight Haskell)
439 | Unpacked (HsType name) -- Field is strict and to be unpacked if poss.
441 getBangType (Banged ty) = ty
442 getBangType (Unbanged ty) = ty
443 getBangType (Unpacked ty) = ty
445 eq_btype env (Banged t1) (Banged t2) = eq_hsType env t1 t2
446 eq_btype env (Unbanged t1) (Unbanged t2) = eq_hsType env t1 t2
447 eq_btype env (Unpacked t1) (Unpacked t2) = eq_hsType env t1 t2
448 eq_btype env _ _ = False
452 instance (Outputable name) => Outputable (ConDecl name) where
453 ppr (ConDecl con _ tvs cxt con_details loc)
454 = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
456 ppr_con_details con (InfixCon ty1 ty2)
457 = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
459 ppr_con_details con (VanillaCon tys)
460 = ppr con <+> hsep (map (ppr_bang) tys)
462 ppr_con_details con (RecCon fields)
463 = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
465 ppr_field (ns, ty) = hsep (map (ppr) ns) <+>
469 instance Outputable name => Outputable (BangType name) where
472 ppr_bang (Banged ty) = ptext SLIT("!") <> pprParendHsType ty
473 ppr_bang (Unbanged ty) = pprParendHsType ty
474 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
478 %************************************************************************
480 \subsection[InstDecl]{An instance declaration
482 %************************************************************************
485 data InstDecl name pat
486 = InstDecl (HsType name) -- Context => Class Instance-type
487 -- Using a polytype means that the renamer conveniently
488 -- figures out the quantified type variables for us.
492 [Sig name] -- User-supplied pragmatic info
494 (Maybe name) -- Name for the dictionary function
495 -- Nothing for source-file instance decls
501 instance (Outputable name, Outputable pat)
502 => Outputable (InstDecl name pat) where
504 ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
505 = getPprStyle $ \ sty ->
506 if ifaceStyle sty then
507 hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
509 vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
513 pp_dfun = case maybe_dfun_name of
519 instance Ord name => Eq (InstDecl name pat) where
520 -- Used for interface comparison only, so don't compare bindings
521 (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
522 = inst_ty1 == inst_ty2 && dfun1 == dfun2
526 %************************************************************************
528 \subsection[DefaultDecl]{A @default@ declaration}
530 %************************************************************************
532 There can only be one default declaration per module, but it is hard
533 for the parser to check that; we pass them all through in the abstract
534 syntax, and that restriction must be checked in the front end.
537 data DefaultDecl name
538 = DefaultDecl [HsType name]
541 instance (Outputable name)
542 => Outputable (DefaultDecl name) where
544 ppr (DefaultDecl tys src_loc)
545 = ptext SLIT("default") <+> parens (interpp'SP tys)
548 %************************************************************************
550 \subsection{Foreign function interface declaration}
552 %************************************************************************
555 data ForeignDecl name =
564 instance (Outputable name)
565 => Outputable (ForeignDecl name) where
567 ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
568 = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+>
569 ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
571 (ppr_imp_exp, ppr_unsafe) =
573 FoLabel -> (ptext SLIT("label"), empty)
574 FoExport -> (ptext SLIT("export"), empty)
576 | us -> (ptext SLIT("import"), ptext SLIT("unsafe"))
577 | otherwise -> (ptext SLIT("import"), empty)
582 | FoImport Bool -- True => unsafe call.
586 | ExtName CLabelString -- The external name of the foreign thing,
587 (Maybe CLabelString) -- and optionally its DLL or module name
588 -- Both of these are completely unencoded;
589 -- we just print them as they are
591 isDynamicExtName :: ExtName -> Bool
592 isDynamicExtName Dynamic = True
593 isDynamicExtName _ = False
595 extNameStatic :: ExtName -> CLabelString
596 extNameStatic (ExtName f _) = f
597 extNameStatic Dynamic = panic "staticExtName: Dynamic - shouldn't ever happen."
599 instance Outputable ExtName where
600 ppr Dynamic = ptext SLIT("dynamic")
601 ppr (ExtName nm mb_mod) =
602 case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+>
603 doubleQuotes (pprCLabelString nm)
606 %************************************************************************
608 \subsection{Transformation rules}
610 %************************************************************************
613 data RuleDecl name pat
614 = HsRule -- Source rule
615 FAST_STRING -- Rule name
616 [name] -- Forall'd tyvars, filled in by the renamer with
617 -- tyvars mentioned in sigs; then filled out by typechecker
618 [RuleBndr name] -- Forall'd term vars
619 (HsExpr name pat) -- LHS
620 (HsExpr name pat) -- RHS
623 | IfaceRule -- One that's come in from an interface file; pre-typecheck
625 [UfBinder name] -- Tyvars and term vars
627 [UfExpr name] -- Args of LHS
628 (UfExpr name) -- Pre typecheck
631 | IfaceRuleOut -- Post typecheck
638 | RuleBndrSig name (HsType name)
640 instance Ord name => Eq (RuleDecl name pat) where
641 -- Works for IfaceRules only; used when comparing interface file versions
642 (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
643 = n1==n2 && f1 == f2 &&
644 eq_ufBinders emptyEqHsEnv bs1 bs2 (\env ->
645 eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
647 instance (Outputable name, Outputable pat)
648 => Outputable (RuleDecl name pat) where
649 ppr (HsRule name tvs ns lhs rhs loc)
650 = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
651 pp_forall, ppr lhs, equals <+> ppr rhs,
654 pp_forall | null tvs && null ns = empty
655 | otherwise = text "forall" <+>
656 fsep (map ppr tvs ++ map ppr ns)
659 ppr (IfaceRule name tpl_vars fn tpl_args rhs loc)
660 = hsep [ doubleQuotes (ptext name),
661 ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
662 ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
663 ptext SLIT("=") <+> ppr rhs
666 ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
668 instance Outputable name => Outputable (RuleBndr name) where
669 ppr (RuleBndr name) = ppr name
670 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
672 toHsRule id (BuiltinRule _)
673 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
675 toHsRule id (Rule name bndrs args rhs)
676 = IfaceRule name (map toUfBndr bndrs) (getName id)
677 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
680 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
684 %************************************************************************
686 \subsection[DeprecDecl]{Deprecations}
688 %************************************************************************
690 We use exported entities for things to deprecate.
693 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
695 type DeprecTxt = FAST_STRING -- reason/explanation for deprecation
697 instance Outputable name => Outputable (DeprecDecl name) where
698 ppr (Deprecation thing txt _)
699 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]