2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
4 \section[MkIface]{Print an interface for a module}
13 #include "HsVersions.h"
15 import IO ( Handle, hPutStr, openFile,
16 hClose, hPutStrLn, IOMode(..) )
19 import RdrHsSyn ( RdrName(..) )
20 import RnHsSyn ( RenamedHsModule )
21 import BasicTypes ( Fixity(..), FixityDirection(..), NewOrData(..), IfaceFlavour(..),
25 import RnEnv ( availName, ifaceFlavour )
27 import TcInstUtil ( InstInfo(..) )
28 import WorkWrap ( getWorkerIdAndCons )
31 import Id ( idType, dataConRawArgTys, dataConFieldLabels,
32 getIdInfo, getInlinePragma, omitIfaceSigForId,
33 dataConStrictMarks, StrictnessMark(..),
34 IdSet, idSetToList, unionIdSets, unitIdSet, minusIdSet,
35 isEmptyIdSet, elementOfIdSet, emptyIdSet, mkIdSet,
40 import IdInfo ( IdInfo, StrictnessInfo, ArityInfo,
41 arityInfo, ppArityInfo, strictnessInfo, ppStrictnessInfo,
42 bottomIsGuaranteed, workerExists,
44 import CoreSyn ( CoreExpr, CoreBinding, GenCoreExpr, GenCoreBinding(..) )
45 import CoreUnfold ( calcUnfoldingGuidance, UnfoldingGuidance(..), Unfolding )
46 import FreeVars ( addExprFVs )
47 import Name ( isLocallyDefined, isWiredInName, modAndOcc, nameModule, pprOccName,
48 OccName, occNameString, nameOccName, nameString, isExported,
49 Name {-instance NamedThing-}, Provenance, NamedThing(..)
51 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
52 tyConTheta, tyConTyVars, tyConDataCons
54 import Class ( Class, classBigSig )
55 import FieldLabel ( fieldLabelName, fieldLabelType )
56 import Type ( mkSigmaTy, splitSigmaTy, mkDictTy,
57 mkTyVarTys, Type, ThetaType
60 import PprEnv -- not sure how much...
62 import PprCore ( pprIfaceUnfolding )
64 import Bag ( bagToList, isEmptyBag )
65 import Maybes ( catMaybes, maybeToBool )
66 import FiniteMap ( emptyFM, addToFM, addToFM_C, lookupFM, fmToList, eltsFM, FiniteMap )
67 import UniqFM ( UniqFM, lookupUFM, listToUFM )
68 import Util ( sortLt, zipWithEqual, zipWith3Equal, mapAccumL )
72 We have a function @startIface@ to open the output file and put
73 (something like) ``interface Foo'' in it. It gives back a handle
74 for subsequent additions to the interface file.
76 We then have one-function-per-block-of-interface-stuff, e.g.,
77 @ifaceExportList@ produces the @__exports__@ section; it appends
78 to the handle provided by @startIface@.
82 -> IO (Maybe Handle) -- Nothing <=> don't do an interface
84 ifaceMain :: Maybe Handle
89 ifaceDecls :: Maybe Handle
92 -> [Id] -- Ids used at code-gen time; they have better pragma info!
93 -> [CoreBinding] -- In dependency order, later depend on earlier
96 endIface :: Maybe Handle -> IO ()
101 = case opt_ProduceHi of
102 Nothing -> return Nothing -- not producing any .hi file
104 if_hdl <- openFile fn WriteMode
105 hPutStrLn if_hdl ("_interface_ "++ _UNPK_ mod ++ ' ':show (PROJECTVERSION :: Int))
108 endIface Nothing = return ()
109 endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl
114 ifaceMain Nothing iface_stuff = return ()
115 ifaceMain (Just if_hdl)
116 (import_usages, ExportEnv avails fixities, instance_modules)
118 ifaceInstanceModules if_hdl instance_modules >>
119 ifaceUsages if_hdl import_usages >>
120 ifaceExports if_hdl avails >>
121 ifaceFixities if_hdl fixities >>
124 ifaceDecls Nothing tycons classes inst_info final_ids simplified = return ()
125 ifaceDecls (Just hdl)
129 | null_decls = return ()
130 -- You could have a module with just (re-)exports/instances in it
132 = ifaceInstances hdl inst_infos >>= \ needed_ids ->
133 hPutStr hdl "_declarations_\n" >>
134 ifaceClasses hdl classes >>
135 ifaceTyCons hdl tycons >>
136 ifaceBinds hdl needed_ids final_ids binds >>
139 null_decls = null binds &&
142 isEmptyBag inst_infos
146 ifaceUsages if_hdl import_usages
147 = hPutStr if_hdl "_usages_\n" >>
148 hPutCol if_hdl upp_uses (sortLt lt_imp_vers import_usages)
150 upp_uses (m, hif, mv, whats_imported)
151 = hsep [pprModule m, pp_hif hif, int mv, ptext SLIT("::"),
152 upp_import_versions whats_imported
155 -- Importing the whole module is indicated by an empty list
156 upp_import_versions Everything = empty
158 -- For imported versions we do print the version number
159 upp_import_versions (Specifically nvs)
160 = hsep [ hsep [ppr_unqual_name n, int v] | (n,v) <- sort_versions nvs ]
162 ifaceInstanceModules if_hdl [] = return ()
163 ifaceInstanceModules if_hdl imods
164 = hPutStr if_hdl "_instance_modules_\n" >>
165 printForIface if_hdl (hsep (map ptext (sortLt (<) imods))) >>
168 ifaceExports if_hdl [] = return ()
169 ifaceExports if_hdl avails
170 = hPutStr if_hdl "_exports_\n" >>
171 hPutCol if_hdl do_one_module (fmToList export_fm)
173 -- Sort them into groups by module
174 export_fm :: FiniteMap Module [AvailInfo]
175 export_fm = foldr insert emptyFM avails
177 insert NotAvailable efm = efm
178 insert avail efm = addToFM_C (++) efm mod [avail]
180 mod = nameModule (availName avail)
182 -- Print one module's worth of stuff
183 do_one_module (mod_name, avails@(avail1:_))
184 = hsep [pp_hif (ifaceFlavour (availName avail1)),
186 hsep (map upp_avail (sortLt lt_avail avails))
189 -- The "!" indicates that the exported things came from a hi-boot interface
190 pp_hif HiFile = empty
191 pp_hif HiBootFile = char '!'
193 ifaceFixities if_hdl [] = return ()
194 ifaceFixities if_hdl fixities
195 = hPutStr if_hdl "_fixities_\n" >>
196 hPutCol if_hdl upp_fixity fixities
199 %************************************************************************
201 \subsection{Instance declarations}
203 %************************************************************************
207 ifaceInstances :: Handle -> Bag InstInfo -> IO IdSet -- The IdSet is the needed dfuns
208 ifaceInstances if_hdl inst_infos
209 | null togo_insts = return emptyIdSet
210 | otherwise = hPutStr if_hdl "_instances_\n" >>
211 hPutCol if_hdl pp_inst (sortLt lt_inst togo_insts) >>
214 togo_insts = filter is_togo_inst (bagToList inst_infos)
215 needed_ids = mkIdSet [dfun_id | InstInfo _ _ _ _ _ dfun_id _ _ _ <- togo_insts]
216 is_togo_inst (InstInfo _ _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
219 lt_inst (InstInfo _ _ _ _ _ dfun_id1 _ _ _)
220 (InstInfo _ _ _ _ _ dfun_id2 _ _ _)
221 = getOccName dfun_id1 < getOccName dfun_id2
222 -- The dfuns are assigned names df1, df2, etc, in order of original textual
223 -- occurrence, and this makes as good a sort order as any
226 pp_inst (InstInfo clas tvs tys theta _ dfun_id _ _ _)
228 forall_ty = mkSigmaTy tvs theta (mkDictTy clas tys)
229 renumbered_ty = nmbrGlobalType forall_ty
231 hcat [ptext SLIT("instance "), pprType renumbered_ty,
232 ptext SLIT(" = "), ppr_unqual_name dfun_id, semi]
236 %************************************************************************
238 \subsection{Printing values}
240 %************************************************************************
243 ifaceId :: (Id -> IdInfo) -- This function "knows" the extra info added
244 -- by the STG passes. Sigh
246 -> IdSet -- Set of Ids that are needed by earlier interface
247 -- file emissions. If the Id isn't in this set, and isn't
248 -- exported, there's no need to emit anything
249 -> Bool -- True <=> recursive, so don't print unfolding
251 -> CoreExpr -- The Id's right hand side
252 -> Maybe (SDoc, IdSet) -- The emitted stuff, plus a possibly-augmented set of needed Ids
254 ifaceId get_idinfo needed_ids is_rec id rhs
255 | not (id `elementOfIdSet` needed_ids || -- Needed [no id in needed_ids has omitIfaceSigForId]
256 (isExported id && not (omitIfaceSigForId id))) -- or exported and not to be omitted
257 = Nothing -- Well, that was easy!
259 ifaceId get_idinfo needed_ids is_rec id rhs
260 = Just (hsep [sig_pretty, pp_double_semi, prag_pretty], new_needed_ids)
262 pp_double_semi = ptext SLIT(";;")
263 idinfo = get_idinfo id
264 inline_pragma = getInlinePragma id
266 ty_pretty = pprType (nmbrGlobalType (idType id))
267 sig_pretty = hcat [ppr (getOccName id), ptext SLIT(" _:_ "), ty_pretty]
270 | opt_OmitInterfacePragmas = empty
271 | otherwise = hsep [arity_pretty, strict_pretty, unfold_pretty, pp_double_semi]
273 ------------ Arity --------------
274 arity_pretty = ppArityInfo (arityInfo idinfo)
276 ------------ Strictness --------------
277 strict_info = strictnessInfo idinfo
278 has_worker = workerExists strict_info
279 strict_pretty = ppStrictnessInfo strict_info <+> wrkr_pretty
281 wrkr_pretty | not has_worker = empty
282 | null con_list = pprId work_id
283 | otherwise = pprId work_id <+>
284 braces (hsep (map (pprId) con_list))
286 (work_id, wrapper_cons) = getWorkerIdAndCons id rhs
287 con_list = idSetToList wrapper_cons
289 ------------ Unfolding --------------
290 unfold_pretty | show_unfold = hsep [ptext SLIT("_U_"), pprIfaceUnfolding rhs]
293 show_unfold = not implicit_unfolding && -- Not unnecessary
294 not dodgy_unfolding -- Not dangerous
296 implicit_unfolding = has_worker ||
297 bottomIsGuaranteed strict_info
299 dodgy_unfolding = case guidance of -- True <=> too big to show, or the Inline pragma
300 UnfoldNever -> True -- says it shouldn't be inlined
303 guidance = calcUnfoldingGuidance inline_pragma
304 opt_InterfaceUnfoldThreshold
308 ------------ Extra free Ids --------------
309 new_needed_ids = (needed_ids `minusIdSet` unitIdSet id) `unionIdSets`
312 extra_ids | opt_OmitInterfacePragmas = emptyIdSet
313 | otherwise = worker_ids `unionIdSets`
316 worker_ids | has_worker = unitIdSet work_id
317 | otherwise = emptyIdSet
319 unfold_ids | show_unfold = free_vars
320 | otherwise = emptyIdSet
322 (_,free_vars) = addExprFVs interesting emptyIdSet rhs
323 interesting bound id = isLocallyDefined id &&
324 not (id `elementOfIdSet` bound) &&
325 not (omitIfaceSigForId id)
330 -> IdSet -- These Ids are needed already
331 -> [Id] -- Ids used at code-gen time; they have better pragma info!
332 -> [CoreBinding] -- In dependency order, later depend on earlier
335 ifaceBinds hdl needed_ids final_ids binds
336 = mapIO (printForIface hdl) pretties >>
339 final_id_map = listToUFM [(id,id) | id <- final_ids]
340 get_idinfo id = case lookupUFM final_id_map id of
341 Just id' -> getIdInfo id'
342 Nothing -> pprTrace "ifaceBinds not found:" (ppr id) $
345 pretties = go needed_ids (reverse binds) -- Reverse so that later things will
346 -- provoke earlier ones to be emitted
347 go needed [] = if not (isEmptyIdSet needed) then
348 pprTrace "ifaceBinds: free vars:"
349 (sep (map ppr (idSetToList needed))) $
354 go needed (NonRec id rhs : binds)
355 = case ifaceId get_idinfo needed False id rhs of
356 Nothing -> go needed binds
357 Just (pretty, needed') -> pretty : go needed' binds
359 -- Recursive groups are a bit more of a pain. We may only need one to
360 -- start with, but it may call out the next one, and so on. So we
361 -- have to look for a fixed point.
362 go needed (Rec pairs : binds)
363 = pretties ++ go needed'' binds
365 (needed', pretties) = go_rec needed pairs
366 needed'' = needed' `minusIdSet` mkIdSet (map fst pairs)
367 -- Later ones may spuriously cause earlier ones to be "needed" again
369 go_rec :: IdSet -> [(Id,CoreExpr)] -> (IdSet, [SDoc])
371 | null pretties = (needed, [])
372 | otherwise = (final_needed, more_pretties ++ pretties)
374 reduced_pairs = [pair | (pair,Nothing) <- pairs `zip` maybes]
375 pretties = catMaybes maybes
376 (needed', maybes) = mapAccumL do_one needed pairs
377 (final_needed, more_pretties) = go_rec needed' reduced_pairs
379 do_one needed (id,rhs) = case ifaceId get_idinfo needed True id rhs of
380 Nothing -> (needed, Nothing)
381 Just (pretty, needed') -> (needed', Just pretty)
385 %************************************************************************
387 \subsection{Random small things}
389 %************************************************************************
392 ifaceTyCons hdl tycons = hPutCol hdl upp_tycon (sortLt (<) (filter (for_iface_name . getName) tycons ))
393 ifaceClasses hdl classes = hPutCol hdl upp_class (sortLt (<) (filter (for_iface_name . getName) classes))
395 for_iface_name name = isLocallyDefined name &&
396 not (isWiredInName name)
398 upp_tycon tycon = ifaceTyCon tycon
399 upp_class clas = ifaceClass clas
404 ifaceTyCon :: TyCon -> SDoc
407 = hsep [ ptext SLIT("type"),
409 pprTyVarBndrs tyvars,
415 (tyvars, ty) = getSynTyConDefn tycon
419 = hsep [ ptext keyword,
420 ppr_decl_context (tyConTheta tycon),
422 pprTyVarBndrs (tyConTyVars tycon),
424 hsep (punctuate (ptext SLIT(" | ")) (map ppr_con (tyConDataCons tycon))),
428 keyword | isNewTyCon tycon = SLIT("newtype")
429 | otherwise = SLIT("data")
434 hsep (map ppr_arg_ty (strict_marks `zip` arg_tys))
439 braces $ hsep $ punctuate comma (map ppr_field (strict_marks `zip` field_labels))
442 field_labels = dataConFieldLabels data_con
443 arg_tys = dataConRawArgTys data_con
444 strict_marks = dataConStrictMarks data_con
445 name = getName data_con
447 ppr_arg_ty (strict_mark, ty) = ppr_strict_mark strict_mark <> pprParendType ty
449 ppr_strict_mark NotMarkedStrict = empty
450 ppr_strict_mark MarkedStrict = ptext SLIT("! ")
451 -- The extra space helps the lexical analyser that lexes
452 -- interface files; it doesn't make the rigid operator/identifier
453 -- distinction, so "!a" is a valid identifier so far as it is concerned
455 ppr_field (strict_mark, field_label)
456 = hsep [ ppr (fieldLabelName field_label),
458 ppr_strict_mark strict_mark <> pprParendType (fieldLabelType field_label)
462 = pprPanic "pprIfaceTyDecl" (ppr tycon)
465 = hsep [ptext SLIT("class"),
466 ppr_decl_context sc_theta,
467 ppr clas, -- Print the name
468 pprTyVarBndrs clas_tyvars,
473 (clas_tyvars, sc_theta, _, sel_ids, defms) = classBigSig clas
475 pp_ops | null sel_ids = empty
476 | otherwise = hsep [ptext SLIT("where"),
477 braces (hsep (punctuate semi (zipWith ppr_classop sel_ids defms)))
480 ppr_classop sel_id maybe_defm
481 = ASSERT( sel_tyvars == clas_tyvars)
482 hsep [ppr (getOccName sel_id),
483 if maybeToBool maybe_defm then equals else empty,
488 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
490 ppr_decl_context :: ThetaType -> SDoc
491 ppr_decl_context [] = empty
492 ppr_decl_context theta
493 = braces (hsep (punctuate comma (map (ppr_dict) theta)))
497 ppr_dict (clas,tys) = ppr clas <+> hsep (map pprParendType tys)
500 %************************************************************************
502 \subsection{Random small things}
504 %************************************************************************
506 When printing export lists, we print like this:
508 AvailTC C [C, x, y] C(x,y)
509 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
512 upp_avail NotAvailable = empty
513 upp_avail (Avail name) = upp_occname (getOccName name)
514 upp_avail (AvailTC name []) = empty
515 upp_avail (AvailTC name ns) = hcat [upp_occname (getOccName name), bang, upp_export ns']
517 bang | name `elem` ns = empty
518 | otherwise = char '|'
519 ns' = filter (/= name) ns
521 upp_export [] = empty
522 upp_export names = parens (hsep (map (upp_occname . getOccName) names))
524 upp_fixity (occ, fixity) = hcat [ppr fixity, space, upp_occname occ, semi]
526 ppr_unqual_name :: NamedThing a => a -> SDoc -- Just its occurrence name
527 ppr_unqual_name name = upp_occname (getOccName name)
529 upp_occname :: OccName -> SDoc
530 upp_occname occ = ptext (occNameString occ)
534 %************************************************************************
536 \subsection{Comparisons
538 %************************************************************************
541 The various sorts above simply prevent unnecessary "wobbling" when
542 things change that don't have to. We therefore compare lexically, not
546 lt_avail :: AvailInfo -> AvailInfo -> Bool
548 a1 `lt_avail` a2 = availName a1 `lt_name` availName a2
550 lt_name :: Name -> Name -> Bool
551 n1 `lt_name` n2 = modAndOcc n1 < modAndOcc n2
553 lt_lexical :: NamedThing a => a -> a -> Bool
554 lt_lexical a1 a2 = getName a1 `lt_name` getName a2
556 lt_imp_vers :: ImportVersion a -> ImportVersion a -> Bool
557 lt_imp_vers (m1,_,_,_) (m2,_,_,_) = m1 < m2
559 sort_versions vs = sortLt lt_vers vs
561 lt_vers :: LocalVersion Name -> LocalVersion Name -> Bool
562 lt_vers (n1,v1) (n2,v2) = n1 `lt_name` n2
571 hPutCol hdl fmt xs = mapIO (printForIface hdl . fmt) xs
573 mapIO :: (a -> IO b) -> [a] -> IO ()
574 mapIO f [] = return ()
575 mapIO f (x:xs) = f x >> mapIO f xs