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,
17 DeprecDecl(..), DeprecTxt,
18 hsDeclName, instDeclName, tyClDeclName, tyClDeclNames,
19 isClassDecl, isSynDecl, isDataDecl, countTyClDecls, toHsRule,
24 #include "HsVersions.h"
27 import HsBinds ( HsBinds, MonoBinds, Sig(..), FixitySig(..) )
28 import HsExpr ( HsExpr )
30 import PprCore ( pprCoreRule )
31 import HsCore ( UfExpr(UfVar), UfBinder, IfaceSig(..), ifaceSigName,
32 eq_ufBinders, eq_ufExpr, pprUfExpr, toUfExpr, toUfBndr
34 import CoreSyn ( CoreRule(..) )
35 import BasicTypes ( NewOrData(..) )
36 import CallConv ( CallConv, pprCallConv )
37 import Name ( getName )
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 decl) = ifaceSigName decl
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 instDeclName :: InstDecl name pat -> name
97 instDeclName (InstDecl _ _ _ (Just name) _) = name
102 instance (Outputable name, Outputable pat)
103 => Outputable (HsDecl name pat) where
105 ppr (TyClD dcl) = ppr dcl
106 ppr (SigD sig) = ppr sig
107 ppr (ValD binds) = ppr binds
108 ppr (DefD def) = ppr def
109 ppr (InstD inst) = ppr inst
110 ppr (ForD fd) = ppr fd
111 ppr (FixD fd) = ppr fd
112 ppr (RuleD rd) = ppr rd
113 ppr (DeprecD dd) = ppr dd
117 instance Ord name => Eq (HsDecl name pat) where
118 -- Used only when comparing interfaces,
119 -- at which time only signature and type/class decls
120 (SigD s1) == (SigD s2) = s1 == s2
121 (TyClD d1) == (TyClD d2) = d1 == d2
126 %************************************************************************
128 \subsection[TyDecl]{@data@, @newtype@ or @type@ (synonym) type declaration}
130 %************************************************************************
132 Type and class declarations carry 'implicit names'. In particular:
136 Each data type decl defines
137 a worker name for each constructor
138 to-T and from-T convertors
139 Each class decl defines
140 a tycon for the class
141 a data constructor for that tycon
142 the worker for that constructor
143 a selector for each superclass
145 All have occurrence names that are derived uniquely from their parent declaration.
147 None of these get separate definitions in an interface file; they are
148 fully defined by the data or class decl. But they may *occur* in
149 interface files, of course. Any such occurrence must haul in the
150 relevant type or class decl.
153 - Make up their occurrence names immediately
155 - Ensure they "point to" the parent data/class decl
156 when loading that decl from an interface file
158 - When renaming the decl look them up in the name cache,
159 ensure correct module and provenance is set
161 Type B: Default methods and dictionary functions
162 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
163 Have their own binding in an interface file.
165 Default methods : occurrence name is derived uniquely from the class decl.
166 Dict functions : occurrence name is derived from the instance decl, plus a unique number.
169 - Do *not* make them point to the parent class decl
170 - Interface-file decls: treat just like Type A
171 - Source-file decls: the names aren't in the decl at all;
172 instead the typechecker makes them up
175 data TyClDecl name pat
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 (TyData _ _ name _ _ _ _ _ _ _) = name
206 tyClDeclName (TySynonym name _ _ _) = name
207 tyClDeclName (ClassDecl _ name _ _ _ _ _ _) = name
210 tyClDeclNames :: Eq name => TyClDecl name pat -> [(name, SrcLoc)]
211 -- Returns all the binding names of the decl, along with their SrcLocs
212 -- The first one is guaranteed to be the name of the decl
213 -- For record fields, the first one counts as the SrcLoc
214 -- We use the equality to filter out duplicate field names
216 tyClDeclNames (TySynonym name _ _ loc)
219 tyClDeclNames (ClassDecl _ name _ _ sigs _ _ loc)
220 = (name,loc) : [(name,loc) | ClassOpSig n _ _ loc <- sigs]
222 tyClDeclNames (TyData _ _ name _ cons _ _ loc _ _)
223 = (name,loc) : conDeclsNames cons
226 type ClassDeclSysNames name = [name]
227 -- [tycon, datacon wrapper, datacon worker,
228 -- superclass selector 1, ..., superclass selector n]
229 -- They are kept in a list rather than a tuple to make the
232 mkClassDeclSysNames :: (name, name, name, [name]) -> [name]
233 getClassDeclSysNames :: [name] -> (name, name, name, [name])
234 mkClassDeclSysNames (a,b,c,ds) = a:b:c:ds
235 getClassDeclSysNames (a:b:c:ds) = (a,b,c,ds)
240 isDataDecl, isSynDecl, isClassDecl :: TyClDecl name pat -> Bool
242 isSynDecl (TySynonym _ _ _ _) = True
243 isSynDecl other = False
245 isDataDecl (TyData _ _ _ _ _ _ _ _ _ _) = True
246 isDataDecl other = False
248 isClassDecl (ClassDecl _ _ _ _ _ _ _ _ ) = True
249 isClassDecl other = False
253 instance Ord name => Eq (TyClDecl name pat) where
254 -- Used only when building interface files
255 (==) (TyData nd1 cxt1 n1 tvs1 cons1 _ _ _ _ _)
256 (TyData nd2 cxt2 n2 tvs2 cons2 _ _ _ _ _)
259 eqWithHsTyVars tvs1 tvs2 (\ env ->
260 eq_hsContext env cxt1 cxt2 &&
261 eqListBy (eq_ConDecl env) cons1 cons2
264 (==) (TySynonym n1 tvs1 ty1 _)
265 (TySynonym n2 tvs2 ty2 _)
267 eqWithHsTyVars tvs1 tvs2 (\ env -> eq_hsType env ty1 ty2)
269 (==) (ClassDecl cxt1 n1 tvs1 fds1 sigs1 _ _ _ )
270 (ClassDecl cxt2 n2 tvs2 fds2 sigs2 _ _ _ )
272 eqWithHsTyVars tvs1 tvs2 (\ env ->
273 eq_hsContext env cxt1 cxt2 &&
274 eqListBy (eq_hsFD env) fds1 fds2 &&
275 eqListBy (eq_cls_sig env) sigs1 sigs2
278 (==) _ _ = False -- default case
281 eq_hsFD env (ns1,ms1) (ns2,ms2)
282 = eqListBy (eq_hsVar env) ns1 ns2 && eqListBy (eq_hsVar env) ms1 ms2
284 eq_cls_sig env (ClassOpSig n1 dm1 ty1 _) (ClassOpSig n2 dm2 ty2 _)
285 = n1==n2 && dm1 `eq_dm` dm2 && eq_hsType env ty1 ty2
287 -- Ignore the name of the default method.
288 -- This is used for comparing declarations before putting
289 -- them into interface files, and the name of the default
290 -- method isn't relevant
291 (Just (explicit_dm1)) `eq_dm` (Just (explicit_dm2)) = explicit_dm1 == explicit_dm2
292 Nothing `eq_dm` Nothing = True
293 dm1 `eq_dm` dm2 = False
297 countTyClDecls :: [TyClDecl name pat] -> (Int, Int, Int, Int)
298 -- class, data, newtype, synonym decls
300 = (length [() | ClassDecl _ _ _ _ _ _ _ _ <- decls],
301 length [() | TyData DataType _ _ _ _ _ _ _ _ _ <- decls],
302 length [() | TyData NewType _ _ _ _ _ _ _ _ _ <- decls],
303 length [() | TySynonym _ _ _ _ <- decls])
307 instance (Outputable name, Outputable pat)
308 => Outputable (TyClDecl name pat) where
310 ppr (TySynonym tycon tyvars mono_ty src_loc)
311 = hang (ptext SLIT("type") <+> pp_decl_head [] tycon tyvars <+> equals)
314 ppr (TyData new_or_data context tycon tyvars condecls ncons
315 derivings src_loc gen_conv1 gen_conv2) -- The generic names are not printed out ATM
317 (ptext keyword <+> pp_decl_head context tycon tyvars <+> equals)
318 (pp_condecls condecls ncons)
321 keyword = case new_or_data of
322 NewType -> SLIT("newtype")
323 DataType -> SLIT("data")
325 ppr (ClassDecl context clas tyvars fds sigs methods _ src_loc)
326 | null sigs -- No "where" part
329 | otherwise -- Laid out
330 = sep [hsep [top_matter, ptext SLIT("where {")],
331 nest 4 (sep [sep (map ppr_sig sigs), pp_methods, char '}'])]
333 top_matter = ptext SLIT("class") <+> pp_decl_head context clas tyvars <+> pprFundeps fds
334 ppr_sig sig = ppr sig <> semi
335 pp_methods = getPprStyle $ \ sty ->
336 if ifaceStyle sty then empty else ppr methods
338 pp_decl_head :: Outputable name => HsContext name -> name -> [HsTyVarBndr name] -> SDoc
339 pp_decl_head context thing tyvars = hsep [pprHsContext context, ppr thing, interppSP tyvars]
341 pp_condecls [] ncons = ptext SLIT("{- abstract with") <+> int ncons <+> ptext SLIT("constructors -}")
342 pp_condecls (c:cs) ncons = sep (ppr c : map (\ c -> ptext SLIT("|") <+> ppr c) cs)
344 pp_tydecl pp_head pp_decl_rhs derivings
345 = hang pp_head 4 (sep [
349 Just ds -> hsep [ptext SLIT("deriving"), parens (interpp'SP ds)]
354 %************************************************************************
356 \subsection[ConDecl]{A data-constructor declaration}
358 %************************************************************************
362 = ConDecl name -- Constructor name; this is used for the
363 -- DataCon itself, and for the user-callable wrapper Id
365 name -- Name of the constructor's 'worker Id'
366 -- Filled in as the ConDecl is built
368 [HsTyVarBndr name] -- Existentially quantified type variables
369 (HsContext name) -- ...and context
370 -- If both are empty then there are no existentials
376 = VanillaCon -- prefix-style con decl
379 | InfixCon -- infix-style con decl
383 | RecCon -- record-style con decl
384 [([name], BangType name)] -- list of "fields"
388 conDeclsNames :: Eq name => [ConDecl name] -> [(name,SrcLoc)]
389 -- See tyClDeclNames for what this does
390 -- The function is boringly complicated because of the records
391 -- And since we only have equality, we have to be a little careful
393 = snd (foldl do_one ([], []) cons)
395 do_one (flds_seen, acc) (ConDecl name _ _ _ details loc)
396 = do_details ((name,loc):acc) details
398 do_details acc (RecCon flds) = foldl do_fld (flds_seen, acc) flds
399 do_details acc other = (flds_seen, acc)
401 do_fld acc (flds, _) = foldl do_fld1 acc flds
403 do_fld1 (flds_seen, acc) fld
404 | fld `elem` flds_seen = (flds_seen,acc)
405 | otherwise = (fld:flds_seen, (fld,loc):acc)
409 eq_ConDecl env (ConDecl n1 _ tvs1 cxt1 cds1 _)
410 (ConDecl n2 _ tvs2 cxt2 cds2 _)
412 (eqWithHsTyVars tvs1 tvs2 $ \ env ->
413 eq_hsContext env cxt1 cxt2 &&
414 eq_ConDetails env cds1 cds2)
416 eq_ConDetails env (VanillaCon bts1) (VanillaCon bts2)
417 = eqListBy (eq_btype env) bts1 bts2
418 eq_ConDetails env (InfixCon bta1 btb1) (InfixCon bta2 btb2)
419 = eq_btype env bta1 bta2 && eq_btype env btb1 btb2
420 eq_ConDetails env (RecCon fs1) (RecCon fs2)
421 = eqListBy (eq_fld env) fs1 fs2
422 eq_ConDetails env _ _ = False
424 eq_fld env (ns1,bt1) (ns2, bt2) = ns1==ns2 && eq_btype env bt1 bt2
429 = Banged (HsType name) -- HsType: to allow Haskell extensions
430 | Unbanged (HsType name) -- (MonoType only needed for straight Haskell)
431 | Unpacked (HsType name) -- Field is strict and to be unpacked if poss.
433 getBangType (Banged ty) = ty
434 getBangType (Unbanged ty) = ty
435 getBangType (Unpacked ty) = ty
437 eq_btype env (Banged t1) (Banged t2) = eq_hsType env t1 t2
438 eq_btype env (Unbanged t1) (Unbanged t2) = eq_hsType env t1 t2
439 eq_btype env (Unpacked t1) (Unpacked t2) = eq_hsType env t1 t2
440 eq_btype env _ _ = False
444 instance (Outputable name) => Outputable (ConDecl name) where
445 ppr (ConDecl con _ tvs cxt con_details loc)
446 = sep [pprHsForAll tvs cxt, ppr_con_details con con_details]
448 ppr_con_details con (InfixCon ty1 ty2)
449 = hsep [ppr_bang ty1, ppr con, ppr_bang ty2]
451 ppr_con_details con (VanillaCon tys)
452 = ppr con <+> hsep (map (ppr_bang) tys)
454 ppr_con_details con (RecCon fields)
455 = ppr con <+> braces (hsep (punctuate comma (map ppr_field fields)))
457 ppr_field (ns, ty) = hsep (map (ppr) ns) <+>
461 instance Outputable name => Outputable (BangType name) where
464 ppr_bang (Banged ty) = ptext SLIT("!") <> pprParendHsType ty
465 ppr_bang (Unbanged ty) = pprParendHsType ty
466 ppr_bang (Unpacked ty) = ptext SLIT("! !") <> pprParendHsType ty
470 %************************************************************************
472 \subsection[InstDecl]{An instance declaration
474 %************************************************************************
477 data InstDecl name pat
478 = InstDecl (HsType name) -- Context => Class Instance-type
479 -- Using a polytype means that the renamer conveniently
480 -- figures out the quantified type variables for us.
484 [Sig name] -- User-supplied pragmatic info
486 (Maybe name) -- Name for the dictionary function
487 -- Nothing for source-file instance decls
493 instance (Outputable name, Outputable pat)
494 => Outputable (InstDecl name pat) where
496 ppr (InstDecl inst_ty binds uprags maybe_dfun_name src_loc)
497 = getPprStyle $ \ sty ->
498 if ifaceStyle sty then
499 hsep [ptext SLIT("instance"), ppr inst_ty, equals, pp_dfun]
501 vcat [hsep [ptext SLIT("instance"), ppr inst_ty, ptext SLIT("where")],
505 pp_dfun = case maybe_dfun_name of
511 instance Ord name => Eq (InstDecl name pat) where
512 -- Used for interface comparison only, so don't compare bindings
513 (==) (InstDecl inst_ty1 _ _ dfun1 _) (InstDecl inst_ty2 _ _ dfun2 _)
514 = inst_ty1 == inst_ty2 && dfun1 == dfun2
518 %************************************************************************
520 \subsection[DefaultDecl]{A @default@ declaration}
522 %************************************************************************
524 There can only be one default declaration per module, but it is hard
525 for the parser to check that; we pass them all through in the abstract
526 syntax, and that restriction must be checked in the front end.
529 data DefaultDecl name
530 = DefaultDecl [HsType name]
533 instance (Outputable name)
534 => Outputable (DefaultDecl name) where
536 ppr (DefaultDecl tys src_loc)
537 = ptext SLIT("default") <+> parens (interpp'SP tys)
540 %************************************************************************
542 \subsection{Foreign function interface declaration}
544 %************************************************************************
547 data ForeignDecl name =
556 instance (Outputable name)
557 => Outputable (ForeignDecl name) where
559 ppr (ForeignDecl nm imp_exp ty ext_name cconv src_loc)
560 = ptext SLIT("foreign") <+> ppr_imp_exp <+> pprCallConv cconv <+>
561 ppr ext_name <+> ppr_unsafe <+> ppr nm <+> dcolon <+> ppr ty
563 (ppr_imp_exp, ppr_unsafe) =
565 FoLabel -> (ptext SLIT("label"), empty)
566 FoExport -> (ptext SLIT("export"), empty)
568 | us -> (ptext SLIT("import"), ptext SLIT("unsafe"))
569 | otherwise -> (ptext SLIT("import"), empty)
574 | FoImport Bool -- True => unsafe call.
578 | ExtName CLabelString -- The external name of the foreign thing,
579 (Maybe CLabelString) -- and optionally its DLL or module name
580 -- Both of these are completely unencoded;
581 -- we just print them as they are
583 isDynamicExtName :: ExtName -> Bool
584 isDynamicExtName Dynamic = True
585 isDynamicExtName _ = False
587 extNameStatic :: ExtName -> CLabelString
588 extNameStatic (ExtName f _) = f
589 extNameStatic Dynamic = panic "staticExtName: Dynamic - shouldn't ever happen."
591 instance Outputable ExtName where
592 ppr Dynamic = ptext SLIT("dynamic")
593 ppr (ExtName nm mb_mod) =
594 case mb_mod of { Nothing -> empty; Just m -> doubleQuotes (ptext m) } <+>
595 doubleQuotes (pprCLabelString nm)
598 %************************************************************************
600 \subsection{Transformation rules}
602 %************************************************************************
605 data RuleDecl name pat
606 = HsRule -- Source rule
607 FAST_STRING -- Rule name
608 [name] -- Forall'd tyvars, filled in by the renamer with
609 -- tyvars mentioned in sigs; then filled out by typechecker
610 [RuleBndr name] -- Forall'd term vars
611 (HsExpr name pat) -- LHS
612 (HsExpr name pat) -- RHS
615 | IfaceRule -- One that's come in from an interface file; pre-typecheck
617 [UfBinder name] -- Tyvars and term vars
619 [UfExpr name] -- Args of LHS
620 (UfExpr name) -- Pre typecheck
623 | IfaceRuleOut -- Post typecheck
630 | RuleBndrSig name (HsType name)
632 instance Ord name => Eq (RuleDecl name pat) where
633 -- Works for IfaceRules only; used when comparing interface file versions
634 (IfaceRule n1 bs1 f1 es1 rhs1 _) == (IfaceRule n2 bs2 f2 es2 rhs2 _)
635 = n1==n2 && f1 == f2 &&
636 eq_ufBinders emptyEqHsEnv bs1 bs2 (\env ->
637 eqListBy (eq_ufExpr env) (rhs1:es1) (rhs2:es2))
639 instance (Outputable name, Outputable pat)
640 => Outputable (RuleDecl name pat) where
641 ppr (HsRule name tvs ns lhs rhs loc)
642 = sep [text "{-# RULES" <+> doubleQuotes (ptext name),
643 pp_forall, ppr lhs, equals <+> ppr rhs,
646 pp_forall | null tvs && null ns = empty
647 | otherwise = text "forall" <+>
648 fsep (map ppr tvs ++ map ppr ns)
651 ppr (IfaceRule name tpl_vars fn tpl_args rhs loc)
652 = hsep [ doubleQuotes (ptext name),
653 ptext SLIT("__forall") <+> braces (interppSP tpl_vars),
654 ppr fn <+> sep (map (pprUfExpr parens) tpl_args),
655 ptext SLIT("=") <+> ppr rhs
658 ppr (IfaceRuleOut fn rule) = pprCoreRule (ppr fn) rule
660 instance Outputable name => Outputable (RuleBndr name) where
661 ppr (RuleBndr name) = ppr name
662 ppr (RuleBndrSig name ty) = ppr name <> dcolon <> ppr ty
664 toHsRule id (BuiltinRule _)
665 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
667 toHsRule id (Rule name bndrs args rhs)
668 = IfaceRule name (map toUfBndr bndrs) (getName id)
669 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
672 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
676 %************************************************************************
678 \subsection[DeprecDecl]{Deprecations}
680 %************************************************************************
682 We use exported entities for things to deprecate.
685 data DeprecDecl name = Deprecation name DeprecTxt SrcLoc
687 type DeprecTxt = FAST_STRING -- reason/explanation for deprecation
689 instance Outputable name => Outputable (DeprecDecl name) where
690 ppr (Deprecation thing txt _)
691 = hsep [text "{-# DEPRECATED", ppr thing, doubleQuotes (ppr txt), text "#-}"]