2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1995
4 \section[MkIface]{Print an interface for a module}
7 #include "HsVersions.h"
9 module MkIface {-( mkInterface )-} where
13 import Bag ( emptyBag, snocBag, bagToList )
14 import Class ( GenClass{-instance NamedThing-} )
15 import CmdLineOpts ( opt_ProduceHi )
17 import Id ( GenId{-instance NamedThing/Outputable-} )
18 import Name ( nameOrigName, exportFlagOn, nameExportFlag, ExportFlag(..),
19 ltLexical, isExported,
20 RdrName{-instance Outputable-}
22 import PprStyle ( PprStyle(..) )
23 import PprType ( TyCon{-instance Outputable-}, GenClass{-ditto-} )
24 import Pretty -- quite a bit
25 import RnHsSyn ( RenamedHsModule(..), RnName{-instance NamedThing-} )
26 import RnIfaces ( VersionInfo(..) )
27 import TcModule ( TcIfaceInfo(..) )
28 import TcInstUtil ( InstInfo )
29 import TyCon ( TyCon{-instance NamedThing-} )
30 import Util ( sortLt, assertPanic )
32 ppSemid x = ppBeside (ppr PprInterface x) ppSemi -- micro util
35 We have a function @startIface@ to open the output file and put
36 (something like) ``interface Foo N'' in it. It gives back a handle
37 for subsequent additions to the interface file.
39 We then have one-function-per-block-of-interface-stuff, e.g.,
40 @ifaceExportList@ produces the @__exports__@ section; it appends
41 to the handle provided by @startIface@.
45 -> IO (Maybe Handle) -- Nothing <=> don't do an interface
46 endIface :: Maybe Handle -> IO ()
63 ifaceDecls :: Maybe Handle
64 -> TcIfaceInfo -- info produced by typechecker, for interfaces
68 -> TcIfaceInfo -- as above
75 = case opt_ProduceHi of
76 Nothing -> return Nothing -- not producing any .hi file
78 openFile fn WriteMode >>= \ if_hdl ->
79 hPutStr if_hdl ("interface "++ _UNPK_ mod ++" 1\n") >>
82 endIface Nothing = return ()
83 endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl
87 ifaceVersions Nothing{-no iface handle-} _ = return ()
89 ifaceVersions (Just if_hdl) version_info
90 = hPutStr if_hdl "__versions__\nFoo(1)" -- a stub, obviously
94 ifaceInstanceModules Nothing{-no iface handle-} _ = return ()
95 ifaceInstanceModules (Just _) [] = return ()
97 ifaceInstanceModules (Just if_hdl) imods
98 = hPutStr if_hdl "\n__instance_modules__\n" >>
99 hPutStr if_hdl (ppShow 100 (ppCat (map ppPStr imods)))
102 Export list: grab the Names of things that are marked Exported, sort
103 (so the interface file doesn't ``wobble'' from one compilation to the
104 next...), and print. Note that the ``module'' now contains all the
105 imported things that we are dealing with, thus including any entities
106 that we are re-exporting from somewhere else.
108 ifaceExportList Nothing{-no iface handle-} _ = return ()
110 ifaceExportList (Just if_hdl)
111 (HsModule _ _ _ _ _ typedecls _ classdecls _ _ _ binds sigs _)
113 name_flag_pairs :: Bag (Name, ExportFlag)
118 (from_binds binds emptyBag{-init accum-})
123 sorted_pairs = sortLt lexical_lt (bagToList name_flag_pairs)
126 hPutStr if_hdl "\n__exports__\n" >>
127 hPutStr if_hdl (ppShow 100 (ppAboves (map pp_pair sorted_pairs)))
129 from_ty (TyData _ n _ _ _ _ _) acc = maybe_add acc n
130 from_ty (TyNew _ n _ _ _ _ _) acc = maybe_add acc n
131 from_ty (TySynonym n _ _ _) acc = maybe_add acc n
133 from_cls (ClassDecl _ n _ _ _ _ _) acc = maybe_add acc n
135 from_sig (Sig n _ _ _) acc = maybe_add acc n
137 from_binds bs acc = maybe_add_list acc (collectTopLevelBinders bs)
140 maybe_add :: Bag (Name, ExportFlag) -> RnName -> Bag (Name, ExportFlag)
143 | exportFlagOn ef = acc `snocBag` (n, ef)
147 ef = nameExportFlag n
150 maybe_add_list acc [] = acc
151 maybe_add_list acc (n:ns) = maybe_add (maybe_add_list acc ns) n
154 lexical_lt (n1,_) (n2,_) = nameOrigName n1 < nameOrigName n2
158 = ppBeside (ppr PprInterface (nameOrigName n)) (pp_export ef)
160 pp_export ExportAll = ppPStr SLIT("(..)")
161 pp_export ExportAbs = ppNil
165 ifaceFixities Nothing{-no iface handle-} _ = return ()
167 ifaceFixities (Just if_hdl) (HsModule _ _ _ _ fixities _ _ _ _ _ _ _ _ _)
168 = if null fixities then
171 hPutStr if_hdl "\n__fixities__\n" >>
172 hPutStr if_hdl (ppShow 100 (ppAboves (map ppSemid fixities)))
176 ifaceDecls Nothing{-no iface handle-} _ = return ()
178 ifaceDecls (Just if_hdl) (vals, tycons, classes, _)
179 = ASSERT(not (null vals && null tycons && null classes))
181 exported_classes = filter isExported classes
182 exported_tycons = filter isExported tycons
183 exported_vals = filter isExported vals
185 sorted_classes = sortLt ltLexical exported_classes
186 sorted_tycons = sortLt ltLexical exported_tycons
187 sorted_vals = sortLt ltLexical exported_vals
189 hPutStr if_hdl "\n__declarations__\n" >>
190 hPutStr if_hdl (ppShow 100 (ppAboves [
191 ppAboves (map ppSemid sorted_classes),
192 ppAboves (map ppSemid sorted_tycons),
193 ppAboves (map ppSemid sorted_vals)]))
197 ifaceInstances Nothing{-no iface handle-} _ = return ()
199 ifaceInstances (Just if_hdl) (_, _, _, insts)
203 exported_classes = filter isExported classes
204 exported_tycons = filter isExported tycons
205 exported_vals = filter isExported vals
207 sorted_classes = sortLt ltLexical exported_classes
208 sorted_tycons = sortLt ltLexical exported_tycons
209 sorted_vals = sortLt ltLexical exported_vals
211 hPutStr if_hdl "\n__declarations__\n" >>
212 hPutStr if_hdl (ppShow 100 (ppAboves [
213 ppAboves (map ppSemid sorted_classes),
214 ppAboves (map ppSemid sorted_tycons),
215 ppAboves (map ppSemid sorted_vals)]))
219 === ALL OLD BELOW HERE ==============
221 %************************************************************************
223 \subsection[main-MkIface]{Main routine for making interfaces}
225 %************************************************************************
230 We get the general what-to-export information from the ``environments''
231 produced by the typechecker (the \tr{[RenamedFixityDecl]} through
232 \tr{Bag InstInfo} arguments).
235 {\em However:} Whereas (for example) an \tr{InstInfo} will have
236 \tr{Ids} in it that identify the constant methods for that instance,
237 those particular \tr{Ids} {\em do not have} the best @IdInfos@!!!
238 Those @IdInfos@ were figured out long after the \tr{InstInfo} was
241 That's why we actually look at the final \tr{StgBindings} that go
242 into the code-generator: they have the best @IdInfos@ on them.
243 Whenever, we are about to print info about an @Id@, we look in the
244 Ids-from-STG-bindings list to see if we have an ``equivalent'' @Id@
245 with presumably-better @IdInfo@.
248 We play this same game whether for values, classes (for their
249 method-selectors and default-methods), or instances (for their
250 @DictFunIds@ or constant-methods).
252 Of course, for imported things, what we got from the typechecker is
256 We {\em sort} things in the interface into some ``canonical'' order;
257 otherwise, with heavily-recursive modules, you can have (unchanged)
258 information ``move around'' in the interface file---deeply unfriendly
264 mkInterface :: FAST_STRING
265 -> (FAST_STRING -> Bool, -- is something in export list, explicitly?
266 FAST_STRING -> Bool) -- is a module among the "dotdot" exported modules?
267 -> IdEnv UnfoldingDetails
268 -> FiniteMap TyCon [(Bool, [Maybe Type])]
269 -> ([RenamedFixityDecl], -- interface info from the typecheck
277 mkInterface modname export_list_fns inline_env tycon_specs
278 (fixity_decls, global_ids, ce, tce, inst_infos)
281 -- first, gather up the things we want to export:
283 exported_tycons = [ tc | tc <- rngTCE tce,
285 is_exportable_tycon_or_class export_list_fns tc ]
286 exported_classes = [ c | c <- rngCE ce,
288 is_exportable_tycon_or_class export_list_fns c ]
289 exported_inst_infos = [ i | i <- bagToList inst_infos,
290 is_exported_inst_info export_list_fns i ]
292 = [ v | v <- global_ids,
293 isExported v && not (isDataCon v) && not (isClassOpId v) ]
295 -- We also have to worry about TyCons/Classes that are
296 -- *mentioned* in exported things (e.g., values' types or
297 -- instances), so that we can be sure to do an import decl for
298 -- them, for original-naming purposes:
300 (mentioned_tycons, mentioned_classes)
301 = foldr ( \ (tcs1, cls1) (tcs2, cls2)
302 -> (tcs1 `unionBags` tcs2, cls1 `unionBags` cls2) )
304 (map getMentionedTyConsAndClassesFromClass exported_classes ++
305 map getMentionedTyConsAndClassesFromTyCon exported_tycons ++
306 map getMentionedTyConsAndClassesFromId exported_vals ++
307 map getMentionedTyConsAndClassesFromInstInfo exported_inst_infos)
310 = filter is_mentionable (bagToList mentioned_classes)
312 = [ tc | tc <- bagToList mentioned_tycons,
314 not (isPrimTyCon tc) ]
316 nondup_mentioned_tycons = fst (removeDups cmp mentionable_tycons)
317 nondup_mentioned_classes = fst (removeDups cmp mentionable_classes)
319 -- Next: as discussed in the notes, we want the top-level
320 -- Ids straight from the final STG code, so we can use
321 -- their IdInfos to print pragmas; we slurp them out here,
322 -- then pass them to the printing functions, which may
325 better_ids = collectExportedStgBinders stg_binds
327 -- Make a lookup function for convenient access:
330 = if not (isLocallyDefined i)
331 then i -- can't be among our "better_ids"
334 eq_fn = if isTopLevId i -- can't trust uniqs
335 then (\ x y -> origName x == origName y)
338 case [ x | x <- better_ids, x `eq_fn` i ] of
339 [] -> pprPanic "better_id_fn:" (ppr PprShowAll i)
342 _ -> panic "better_id_fn"
344 -- Finally, we sort everything lexically, so that we always
345 -- get the same interface from the same information:
347 sorted_mentioned_tycons = sortLt ltLexical nondup_mentioned_tycons
348 sorted_mentioned_classes = sortLt ltLexical nondup_mentioned_classes
350 sorted_tycons = sortLt ltLexical exported_tycons
351 sorted_classes = sortLt ltLexical exported_classes
352 sorted_vals = sortLt ltLexical exported_vals
353 sorted_inst_infos = sortLt lt_lexical_inst_info exported_inst_infos
355 if (any_purely_local sorted_tycons sorted_classes sorted_vals) then
356 -- this will be less of a HACK when we teach
357 -- mkInterface to do I/O (WDP 94/10)
358 error "Can't produce interface file because of errors!\n"
361 [ppPStr SLIT("{-# GHC_PRAGMA INTERFACE VERSION 7 #-}"),
362 ppCat [ppPStr SLIT("interface"), ppPStr modname, ppPStr SLIT("where")],
364 do_import_decls modname
365 sorted_vals sorted_mentioned_classes sorted_mentioned_tycons,
366 -- Mustn't give the data constructors to do_import_decls,
367 -- because they aren't explicitly imported; their tycon is.
369 ppAboves (map do_fixity fixity_decls),
370 ppAboves (map (pprIfaceClass better_id_fn inline_env) sorted_classes),
371 ppAboves (map (do_tycon tycon_specs) sorted_tycons),
372 ppAboves (map (do_value better_id_fn inline_env) sorted_vals),
373 ppAboves (map (do_instance better_id_fn inline_env) sorted_inst_infos),
378 any_purely_local tycons classes vals
379 = any bad_tc tycons || any bad_cl classes || any bad_id vals
382 = case (maybePurelyLocalClass cl) of
384 Just xs -> naughty_trace cl xs
387 = case (maybePurelyLocalType (idType id)) of
389 Just xs -> naughty_trace id xs
392 = case (maybePurelyLocalTyCon tc) of
394 Just xs -> if exported_abs then False else naughty_trace tc xs
396 exported_abs = case (getExportFlag tc) of { ExportAbs -> True; _ -> False }
398 naughty_trace x things
399 = pprTrace "Can't export -- `"
400 (ppBesides [ppr PprForUser x, ppStr "' mentions purely local things: ",
401 ppInterleave pp'SP things])
405 %************************************************************************
407 \subsection[imports-MkIface]{Generating `import' declarations in an interface}
409 %************************************************************************
411 We gather up lots of (module, name) pairs for which we might print an
412 import declaration. We sort them, for the usual canonicalisation
413 reasons. NB: We {\em assume} the lists passed in don't have duplicates in
416 All rather horribly turgid (WDP).
421 -> [Id] -> [Class] -> [TyCon]
424 do_import_decls mod_name vals classes tycons
426 -- Conjure up (module, name) pairs for all
427 -- the potentially import-decls things:
429 vals_names, classes_names, tycons_names :: [(FAST_STRING, FAST_STRING, [Maybe FAST_STRING])]
430 vals_names = map get_val_pair vals
431 classes_names = map get_class_pair classes
432 tycons_names = map get_tycon_pair tycons
434 -- sort the (module, name) pairs and chop
435 -- them into per-module groups:
437 ie_list = sortLt lt (tycons_names ++ classes_names ++ vals_names)
439 per_module_groups = runs same_module ie_list
441 ppAboves (map print_a_decl per_module_groups)
443 lt, same_module :: (FAST_STRING, FAST_STRING)
444 -> (FAST_STRING, FAST_STRING) -> Bool
447 = case (_CMP_STRING_ m1 m2) of { LT_ -> True; EQ_ -> ie1 < ie2; GT__ -> False }
449 same_module (m1, _, _) (m2, _, _) = m1 == m2
451 compiling_the_prelude = opt_CompilingPrelude
453 print_a_decl :: [(FAST_STRING, FAST_STRING, [Maybe FAST_STRING])] -> Pretty
455 Obviously, if the module in question is this one,
456 don't print an import declaration.
458 If it's a Prelude* module, we don't print the TyCons/
459 Classes, because the compiler supposedly knows about
460 them already (and they are PreludeCore things anyway).
462 But if we are compiling a Prelude module, then we
463 try to do it as "normally" as possible.
465 print_a_decl (ielist@((m,_,_) : _))
467 || (not compiling_the_prelude &&
468 ({-OLD:m == pRELUDE_CORE ||-} m == pRELUDE_BUILTIN))
472 = ppBesides [ppPStr SLIT("import "), ppPStr m, ppLparen,
473 ppIntersperse pp'SP{-'-} (map pp_str [n | (_,n,_) <- ielist]),
477 isnt_tycon_ish :: FAST_STRING -> Bool
478 isnt_tycon_ish str = not (isLexCon str)
480 grab_non_Nothings :: [[Maybe FAST_STRING]] -> [FAST_STRING]
482 grab_non_Nothings rns = catMaybes (concat rns)
484 pp_str :: FAST_STRING -> Pretty
486 = if isLexVarSym pstr then ppStr ("("++str++")") else ppPStr pstr
492 get_val_pair :: Id -> (FAST_STRING, FAST_STRING)
493 get_class_pair :: Class -> (FAST_STRING, FAST_STRING)
494 get_tycon_pair :: TyCon -> (FAST_STRING, FAST_STRING)
500 = case (generic_pair clas) of { (orig_mod, orig_nm) ->
502 nm_to_print = case (getExportFlag clas) of
503 ExportAll -> orig_nm _APPEND_ SLIT("(..)") -- nothing like a good HACK!
505 NotExported -> orig_nm
507 (orig_mod, nm_to_print) }
510 = case (generic_pair tycon) of { (orig_mod, orig_nm) ->
512 nm_to_print = case (getExportFlag tycon) of
513 ExportAll -> orig_nm _APPEND_ SLIT("(..)") -- nothing like a good HACK!
515 NotExported -> orig_nm
517 cons = tyConDataCons tycon
519 (orig_mod, nm_to_print) }
522 = case (moduleNamePair thing) of { (orig_mod, orig_nm) ->
523 case (getOccName thing) of { occur_name ->
524 (orig_mod, orig_nm) }}
527 %************************************************************************
529 \subsection[fixities-MkIface]{Generating fixity declarations in an interface}
531 %************************************************************************
535 do_fixity :: -> RenamedFixityDecl -> Pretty
537 do_fixity fixity_decl
538 = case (isLocallyDefined name, getExportFlag name) of
539 (True, ExportAll) -> ppr PprInterface fixity_decl
542 name = get_name fixity_decl
543 get_name (InfixL n _) = n
544 get_name (InfixR n _) = n
545 get_name (InfixN n _) = n
548 %************************************************************************
550 \subsection[tycons-MkIface]{Generating tycon declarations in an interface}
552 %************************************************************************
555 do_tycon :: FiniteMap TyCon [(Bool, [Maybe Type])] -> TyCon -> Pretty
557 do_tycon tycon_specs_map tycon
558 = pprTyCon PprInterface tycon tycon_specs
560 tycon_specs = map snd (lookupWithDefaultFM tycon_specs_map [] tycon)
563 %************************************************************************
565 \subsection[values-MkIface]{Generating a value's signature in an interface}
567 %************************************************************************
570 do_value :: (Id -> Id)
571 -> IdEnv UnfoldingDetails
575 do_value better_id_fn inline_env val
578 better_val = better_id_fn val
579 name_str = getOccName better_val -- NB: not orig name!
581 id_info = getIdInfo better_val
585 final_ty = idType better_val
587 -- ASSERT (orig_ty == final_ty || mkLiftTy orig_ty == final_ty)
588 ASSERT (if (orig_ty == final_ty || mkLiftTy orig_ty == final_ty) then True else pprTrace "do_value:" (ppCat [ppr PprDebug val, ppr PprDebug better_val]) False)
591 -- Note: We export the type of the original val
592 -- The type of an unboxed val will have been *lifted* by the desugarer
593 -- In this case we export an unlifted type, but id_info which assumes
594 -- a lifted Id i.e. extracted from better_val (above)
595 -- The importing module must lift the Id before using the imported id_info
598 = if opt_OmitInterfacePragmas
599 || boringIdInfo id_info
601 else ppCat [ppPStr SLIT("\t{-# GHC_PRAGMA"),
602 ppIdInfo sty better_val True{-yes specs-}
603 better_id_fn inline_env id_info,
606 ppAbove (ppCat [ppr_non_op name_str,
607 ppPStr SLIT("::"), pprGenType sty val_ty])
610 -- sadly duplicates Name.pprNonSym (ToDo)
613 = if isLexVarSym str -- NOT NEEDED: || isAconop
614 then ppBesides [ppLparen, ppPStr str, ppRparen]
618 %************************************************************************
620 \subsection[instances-MkIface]{Generating instance declarations in an interface}
622 %************************************************************************
624 The types of ``dictionary functions'' (dfuns) have just the required
625 info for instance declarations in interfaces. However, the dfuns that
626 GHC really uses have {\em extra} dictionaries passed to them (for
627 efficiency). When we print interfaces, we want to omit that
628 dictionary information. (It can be reconsituted on the other end,
629 from instance and class decls).
632 do_instance :: (Id -> Id)
633 -> IdEnv UnfoldingDetails
637 do_instance better_id_fn inline_env
638 (InstInfo clas tv_tmpls ty inst_decl_theta dfun_theta dfun_id constm_ids _ from_here modname _ _)
642 better_dfun = better_id_fn dfun_id
643 better_dfun_info = getIdInfo better_dfun
644 better_constms = map better_id_fn constm_ids
646 class_op_strs = map classOpString (classOps clas)
649 = ppCat [ppPStr SLIT("\t{-# GHC_PRAGMA"), pp_modname, ppPStr SLIT("{-dfun-}"),
650 ppIdInfo sty better_dfun False{-NO specs-}
651 better_id_fn inline_env better_dfun_info]
653 pragma_end = ppPStr SLIT("#-}")
655 pp_modname = if _NULL_ modname
657 else ppCat [ppStr "_M_", ppPStr modname]
660 = pp_the_list [ ppCat [ppChar '\t', ppr_non_op op, ppEquals,
662 ppIdInfo sty constm True{-YES, specs-}
663 better_id_fn inline_env
666 | (op, constm) <- class_op_strs `zip` better_constms ]
669 pp_the_list [] = panic "MkIface: no class_ops or better_constms?"
672 pp_the_list (p:ps) = ppAbove (ppBeside p ppComma) (pp_the_list ps)
675 = ppCat [ppPStr SLIT("instance"),
676 ppr sty (mkSigmaTy tv_tmpls inst_decl_theta (mkDictTy clas ty))]
678 if opt_OmitInterfacePragmas
679 || boringIdInfo better_dfun_info
681 else ppAbove real_stuff
682 ({-ppNest 8 -} -- ppNest does nothing
683 if null better_constms
684 then ppCat [pragma_begin, pragma_end]
685 else ppAbove pragma_begin (ppCat [name_pragma_pairs, pragma_end])
689 %************************************************************************
691 \subsection[utils-InstInfos]{Utility functions for @InstInfos@}
693 %************************************************************************
697 Classes/TyCons are ``known,'' more-or-less. Prelude TyCons are
698 ``completely'' known---they don't need to be mentioned in interfaces.
699 Classes usually don't need to be mentioned in interfaces, but if we're
700 compiling the prelude, then we treat them without special favours.
702 is_exportable_tycon_or_class export_list_fns tc
703 = if not (fromPreludeCore tc) then
706 in_export_list_or_among_dotdot_modules
707 opt_CompilingPrelude -- ignore M.. stuff if compiling prelude
710 in_export_list_or_among_dotdot_modules ignore_Mdotdots (in_export_list, among_dotdot_modules) tc
711 = if in_export_list (getOccName tc) then
714 -- pprTrace "in_export:" (ppAbove (ppr PprDebug ignore_Mdotdots) (ppPStr (getOccName tc))) (
715 if ignore_Mdotdots then
718 any among_dotdot_modules (getInformingModules tc)
722 = not (from_PreludeCore_or_Builtin tc) || opt_CompilingPrelude
724 from_PreludeCore_or_Builtin thing
726 mod_name = fst (moduleNamePair thing)
728 mod_name == pRELUDE_CORE || mod_name == pRELUDE_BUILTIN
730 is_exported_inst_info export_list_fns
731 (InstInfo clas _ ty _ _ _ _ _ from_here _ _ _)
733 seems_exported = instanceIsExported clas ty from_here
734 (tycon, _, _) = getAppTyCon ty
736 if (opt_OmitReexportedInstances && not from_here) then
737 False -- Flag says to violate Haskell rules, blatantly
739 else if not opt_CompilingPrelude
740 || not (isFunTyCon tycon || fromPreludeCore tycon)
741 || not (fromPreludeCore clas) then
742 seems_exported -- take what we got
744 else -- compiling Prelude & tycon/class are Prelude things...
746 || in_export_list_or_among_dotdot_modules True{-ignore M..s-} export_list_fns clas
747 || in_export_list_or_among_dotdot_modules True{-ignore M..s-} export_list_fns tycon
751 lt_lexical_inst_info (InstInfo _ _ _ _ _ dfun1 _ _ _ _ _ _) (InstInfo _ _ _ _ _ dfun2 _ _ _ _ _ _)
752 = ltLexical dfun1 dfun2
756 getMentionedTyConsAndClassesFromInstInfo (InstInfo clas _ ty _ dfun_theta _ _ _ _ _ _ _)
757 = case (getMentionedTyConsAndClassesFromType ty) of { (ts, cs) ->
758 case [ c | (c, _) <- dfun_theta ] of { theta_classes ->
759 (ts, (cs `unionBags` listToBag theta_classes) `snocBag` clas)
761 OLD from the beginning -}