2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1996
4 \section[MkIface]{Print an interface for a module}
7 #include "HsVersions.h"
16 IMPORT_1_3(IO(Handle,hPutStr,openFile,hClose,IOMode(..)))
19 import RdrHsSyn ( RdrName(..) )
20 import RnHsSyn ( SYN_IE(RenamedHsModule) )
23 import TcInstUtil ( InstInfo(..) )
26 import Id ( idType, dataConRawArgTys, dataConFieldLabels, isDataCon,
27 getIdInfo, idWantsToBeINLINEd, omitIfaceSigForId,
28 dataConStrictMarks, StrictnessMark(..),
29 SYN_IE(IdSet), idSetToList, unionIdSets, unitIdSet, minusIdSet,
30 isEmptyIdSet, elementOfIdSet, emptyIdSet, mkIdSet,
31 GenId{-instance NamedThing/Outputable-}
33 import IdInfo ( StrictnessInfo, ArityInfo, Unfolding,
34 arityInfo, ppArityInfo, strictnessInfo, ppStrictnessInfo,
35 getWorkerId_maybe, bottomIsGuaranteed
37 import CoreSyn ( SYN_IE(CoreExpr), SYN_IE(CoreBinding), GenCoreExpr, GenCoreBinding(..) )
38 import CoreUnfold ( calcUnfoldingGuidance, UnfoldingGuidance(..) )
39 import FreeVars ( addExprFVs )
40 import Name ( isLocallyDefined, isWiredInName, modAndOcc, getName, pprOccName,
41 OccName, occNameString, nameOccName, nameString, isExported, pprNonSym,
42 Name {-instance NamedThing-}, Provenance
44 import TyCon ( TyCon(..){-instance NamedThing-}, NewOrData(..) )
45 import Class ( GenClass(..){-instance NamedThing-}, GenClassOp, classOpLocalType )
46 import FieldLabel ( FieldLabel{-instance NamedThing-} )
47 import Type ( mkSigmaTy, mkDictTy, getAppTyCon, splitForAllTy )
48 import TyVar ( GenTyVar {- instance Eq -} )
49 import Unique ( Unique {- instance Eq -} )
51 import PprEnv -- not sure how much...
52 import PprStyle ( PprStyle(..) )
54 import PprCore ( pprIfaceUnfolding )
56 import Unpretty -- ditto
59 import Bag ( bagToList )
60 import Maybes ( catMaybes, maybeToBool )
61 import FiniteMap ( emptyFM, addToFM, addToFM_C, lookupFM, fmToList, eltsFM, FiniteMap )
62 import UniqFM ( UniqFM, lookupUFM, listToUFM )
63 import Util ( sortLt, zipWithEqual, zipWith3Equal, mapAccumL,
64 assertPanic, panic{-ToDo:rm-}, pprTrace )
68 We have a function @startIface@ to open the output file and put
69 (something like) ``interface Foo'' in it. It gives back a handle
70 for subsequent additions to the interface file.
72 We then have one-function-per-block-of-interface-stuff, e.g.,
73 @ifaceExportList@ produces the @__exports__@ section; it appends
74 to the handle provided by @startIface@.
78 -> IO (Maybe Handle) -- Nothing <=> don't do an interface
80 ifaceMain :: Maybe Handle
85 ifaceDecls :: Maybe Handle
88 -> [Id] -- Ids used at code-gen time; they have better pragma info!
89 -> [CoreBinding] -- In dependency order, later depend on earlier
92 endIface :: Maybe Handle -> IO ()
97 = case opt_ProduceHi of
98 Nothing -> return Nothing -- not producing any .hi file
100 openFile fn WriteMode >>= \ if_hdl ->
101 hPutStr if_hdl ("{-# GHC_PRAGMA INTERFACE VERSION 20 #-}\n_interface_ "++ _UNPK_ mod ++ "\n") >>
104 endIface Nothing = return ()
105 endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl
110 ifaceMain Nothing iface_stuff = return ()
111 ifaceMain (Just if_hdl)
112 (import_usages, ExportEnv avails fixities, instance_modules)
114 ifaceInstanceModules if_hdl instance_modules >>
115 ifaceUsages if_hdl import_usages >>
116 ifaceExports if_hdl avails >>
117 ifaceFixities if_hdl fixities >>
120 ifaceDecls Nothing rn_mod inst_info final_ids simplified = return ()
121 ifaceDecls (Just hdl)
122 (HsModule _ _ _ _ _ decls _)
125 | null decls = return ()
126 -- You could have a module with just (re-)exports/instances in it
128 = ifaceInstances hdl inst_infos >>= \ needed_ids ->
129 hPutStr hdl "_declarations_\n" >>
130 ifaceTCDecls hdl decls >>
131 ifaceBinds hdl needed_ids final_ids binds >>
136 ifaceUsages if_hdl import_usages
137 = hPutStr if_hdl "_usages_\n" >>
138 hPutCol if_hdl upp_uses (sortLt lt_imp_vers import_usages)
140 upp_uses (m, mv, versions)
141 = uppBesides [upp_module m, uppSP, uppInt mv, uppPStr SLIT(" :: "),
142 upp_import_versions (sort_versions versions), uppSemi]
144 -- For imported versions we do print the version number
145 upp_import_versions nvs
146 = uppIntersperse uppSP [ uppCat [ppr_unqual_name n, uppInt v] | (n,v) <- nvs ]
149 ifaceInstanceModules if_hdl [] = return ()
150 ifaceInstanceModules if_hdl imods
151 = hPutStr if_hdl "_instance_modules_\n" >>
152 hPutStr if_hdl (uppShow 0 (uppCat (map uppPStr imods))) >>
155 ifaceExports if_hdl [] = return ()
156 ifaceExports if_hdl avails
157 = hPutStr if_hdl "_exports_\n" >>
158 hPutCol if_hdl do_one_module (fmToList export_fm)
160 -- Sort them into groups by module
161 export_fm :: FiniteMap Module [AvailInfo]
162 export_fm = foldr insert emptyFM avails
163 insert avail@(Avail name _) efm = addToFM_C (++) efm mod [avail]
165 (mod,_) = modAndOcc name
166 insert NotAvailable efm = efm
168 -- Print one module's worth of stuff
169 do_one_module (mod_name, avails)
170 = uppBesides [upp_module mod_name, uppSP,
171 uppCat (map upp_avail (sortLt lt_avail avails)),
174 ifaceFixities if_hdl [] = return ()
175 ifaceFixities if_hdl fixities
176 = hPutStr if_hdl "_fixities_\n" >>
177 hPutCol if_hdl upp_fixity fixities
179 ifaceTCDecls if_hdl decls
180 = hPutCol if_hdl ppr_decl tc_decls_for_iface
182 tc_decls_for_iface = sortLt lt_decl (filter for_iface decls)
183 for_iface decl@(ClD _) = for_iface_name (hsDeclName decl)
184 for_iface decl@(TyD _) = for_iface_name (hsDeclName decl)
185 for_iface other_decl = False
187 for_iface_name name = isLocallyDefined name &&
188 not (isWiredInName name)
190 lt_decl d1 d2 = hsDeclName d1 < hsDeclName d2
193 %************************************************************************
195 \subsection{Instance declarations}
197 %************************************************************************
201 ifaceInstances :: Handle -> Bag InstInfo -> IO IdSet -- The IdSet is the needed dfuns
202 ifaceInstances if_hdl inst_infos
203 | null togo_insts = return emptyIdSet
204 | otherwise = hPutStr if_hdl "_instances_\n" >>
205 hPutCol if_hdl pp_inst (sortLt lt_inst togo_insts) >>
208 togo_insts = filter is_togo_inst (bagToList inst_infos)
209 needed_ids = mkIdSet [dfun_id | InstInfo _ _ _ _ _ dfun_id _ _ _ <- togo_insts]
210 is_togo_inst (InstInfo _ _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
213 lt_inst (InstInfo _ _ _ _ _ dfun_id1 _ _ _)
214 (InstInfo _ _ _ _ _ dfun_id2 _ _ _)
215 = getOccName dfun_id1 < getOccName dfun_id2
216 -- The dfuns are assigned names df1, df2, etc, in order of original textual
217 -- occurrence, and this makes as good a sort order as any
220 pp_inst (InstInfo clas tvs ty theta _ dfun_id _ _ _)
222 forall_ty = mkSigmaTy tvs theta (mkDictTy clas ty)
223 renumbered_ty = renumber_ty forall_ty
225 uppBesides [uppPStr SLIT("instance "), ppr_ty renumbered_ty,
226 uppPStr SLIT(" = "), ppr_unqual_name dfun_id, uppSemi]
230 %************************************************************************
232 \subsection{Printing values}
234 %************************************************************************
237 ifaceId :: (Id -> IdInfo) -- This function "knows" the extra info added
238 -- by the STG passes. Sigh
240 -> IdSet -- Set of Ids that are needed by earlier interface
241 -- file emissions. If the Id isn't in this set, and isn't
242 -- exported, there's no need to emit anything
243 -> Bool -- True <=> recursive, so don't print unfolding
245 -> CoreExpr -- The Id's right hand side
246 -> Maybe (Pretty, IdSet) -- The emitted stuff, plus a possibly-augmented set of needed Ids
248 ifaceId get_idinfo needed_ids is_rec id rhs
249 | not (id `elementOfIdSet` needed_ids || -- Needed [no id in needed_ids has omitIfaceSigForId]
250 (isExported id && not (omitIfaceSigForId id))) -- or exported and not to be omitted
251 = Nothing -- Well, that was easy!
253 ifaceId get_idinfo needed_ids is_rec id rhs
254 = Just (ppCat [sig_pretty, prag_pretty, ppStr ";;"], new_needed_ids)
256 idinfo = get_idinfo id
257 inline_pragma = idWantsToBeINLINEd id
259 ty_pretty = pprType PprInterface (initNmbr (nmbrType (idType id)))
260 sig_pretty = ppBesides [ppr PprInterface (getOccName id), ppPStr SLIT(" :: "), ty_pretty]
262 prag_pretty | opt_OmitInterfacePragmas = ppNil
263 | otherwise = ppCat [arity_pretty, strict_pretty, unfold_pretty]
265 ------------ Arity --------------
266 arity_pretty = ppArityInfo PprInterface (arityInfo idinfo)
268 ------------ Strictness --------------
269 strict_info = strictnessInfo idinfo
270 maybe_worker = getWorkerId_maybe strict_info
271 strict_pretty = ppStrictnessInfo PprInterface strict_info
273 ------------ Unfolding --------------
274 unfold_pretty | show_unfold = ppCat [ppStr "_U_", pprIfaceUnfolding rhs]
277 show_unfold = not implicit_unfolding && -- Unnecessary
278 (inline_pragma || not dodgy_unfolding) -- Dangerous
280 implicit_unfolding = maybeToBool maybe_worker ||
281 bottomIsGuaranteed strict_info
283 dodgy_unfolding = is_rec || -- No recursive unfoldings please!
284 case guidance of -- Too big to show
288 guidance = calcUnfoldingGuidance inline_pragma
289 opt_InterfaceUnfoldThreshold
293 ------------ Extra free Ids --------------
294 new_needed_ids = (needed_ids `minusIdSet` unitIdSet id) `unionIdSets`
297 extra_ids | opt_OmitInterfacePragmas = emptyIdSet
298 | otherwise = worker_ids `unionIdSets`
301 worker_ids = case maybe_worker of
302 Just wkr -> unitIdSet wkr
303 Nothing -> emptyIdSet
305 unfold_ids | show_unfold = free_vars
306 | otherwise = emptyIdSet
308 (_,free_vars) = addExprFVs interesting emptyIdSet rhs
309 interesting bound id = isLocallyDefined id &&
310 not (id `elementOfIdSet` bound) &&
311 not (omitIfaceSigForId id)
316 -> IdSet -- These Ids are needed already
317 -> [Id] -- Ids used at code-gen time; they have better pragma info!
318 -> [CoreBinding] -- In dependency order, later depend on earlier
321 ifaceBinds hdl needed_ids final_ids binds
322 = hPutStr hdl (uppShow 0 (prettyToUn (ppAboves pretties))) >>
325 final_id_map = listToUFM [(id,id) | id <- final_ids]
326 get_idinfo id = case lookupUFM final_id_map id of
327 Just id' -> getIdInfo id'
328 Nothing -> pprTrace "ifaceBinds not found:" (ppr PprDebug id) $
331 pretties = go needed_ids (reverse binds) -- Reverse so that later things will
332 -- provoke earlier ones to be emitted
333 go needed [] = if not (isEmptyIdSet needed) then
334 pprTrace "ifaceBinds: free vars:"
335 (ppSep (map (ppr PprDebug) (idSetToList needed))) $
340 go needed (NonRec id rhs : binds)
341 = case ifaceId get_idinfo needed False id rhs of
342 Nothing -> go needed binds
343 Just (pretty, needed') -> pretty : go needed' binds
345 -- Recursive groups are a bit more of a pain. We may only need one to
346 -- start with, but it may call out the next one, and so on. So we
347 -- have to look for a fixed point.
348 go needed (Rec pairs : binds)
349 = pretties ++ go needed'' binds
351 (needed', pretties) = go_rec needed pairs
352 needed'' = needed' `minusIdSet` mkIdSet (map fst pairs)
353 -- Later ones may spuriously cause earlier ones to be "needed" again
355 go_rec :: IdSet -> [(Id,CoreExpr)] -> (IdSet, [Pretty])
357 | null pretties = (needed, [])
358 | otherwise = (final_needed, more_pretties ++ pretties)
360 reduced_pairs = [pair | (pair,Nothing) <- pairs `zip` maybes]
361 pretties = catMaybes maybes
362 (needed', maybes) = mapAccumL do_one needed pairs
363 (final_needed, more_pretties) = go_rec needed' reduced_pairs
365 do_one needed (id,rhs) = case ifaceId get_idinfo needed True id rhs of
366 Nothing -> (needed, Nothing)
367 Just (pretty, needed') -> (needed', Just pretty)
371 %************************************************************************
373 \subsection{Random small things}
375 %************************************************************************
378 upp_avail NotAvailable = uppNil
379 upp_avail (Avail name ns) = uppBesides [upp_occname (getOccName name), upp_export ns]
381 upp_export [] = uppNil
382 upp_export names = uppBesides [uppStr "(",
383 uppIntersperse uppSP (map (upp_occname . getOccName) names),
386 upp_fixity (occ, (Fixity prec dir, prov)) = uppBesides [upp_dir dir, uppSP,
388 upp_occname occ, uppSemi]
389 upp_dir InfixR = uppStr "infixr"
390 upp_dir InfixL = uppStr "infixl"
391 upp_dir InfixN = uppStr "infix"
393 ppr_unqual_name :: NamedThing a => a -> Unpretty -- Just its occurrence name
394 ppr_unqual_name name = upp_occname (getOccName name)
396 ppr_name :: NamedThing a => a -> Unpretty -- Its full name
397 ppr_name n = uppPStr (nameString (getName n))
399 upp_occname :: OccName -> Unpretty
400 upp_occname occ = uppPStr (occNameString occ)
402 upp_module :: Module -> Unpretty
403 upp_module mod = uppPStr mod
405 uppSemid x = uppBeside (prettyToUn (ppr PprInterface x)) uppSemi -- micro util
407 ppr_ty ty = prettyToUn (pprType PprInterface ty)
408 ppr_tyvar tv = prettyToUn (ppr PprInterface tv)
409 ppr_tyvar_bndr tv = prettyToUn (pprTyVarBndr PprInterface tv)
411 ppr_decl decl = prettyToUn (ppr PprInterface decl) `uppBeside` uppSemi
413 renumber_ty ty = initNmbr (nmbrType ty)
417 %************************************************************************
419 \subsection{Comparisons
421 %************************************************************************
424 The various sorts above simply prevent unnecessary "wobbling" when
425 things change that don't have to. We therefore compare lexically, not
429 lt_avail :: AvailInfo -> AvailInfo -> Bool
431 NotAvailable `lt_avail` (Avail _ _) = True
432 (Avail n1 _) `lt_avail` (Avail n2 _) = n1 `lt_name` n2
433 any `lt_avail` NotAvailable = False
435 lt_name :: Name -> Name -> Bool
436 n1 `lt_name` n2 = modAndOcc n1 < modAndOcc n2
438 lt_lexical :: NamedThing a => a -> a -> Bool
439 lt_lexical a1 a2 = getName a1 `lt_name` getName a2
441 lt_imp_vers :: ImportVersion a -> ImportVersion a -> Bool
442 lt_imp_vers (m1,_,_) (m2,_,_) = m1 < m2
444 sort_versions vs = sortLt lt_vers vs
446 lt_vers :: LocalVersion Name -> LocalVersion Name -> Bool
447 lt_vers (n1,v1) (n2,v2) = n1 `lt_name` n2
456 hPutCol hdl fmt xs = hPutStr hdl (uppShow 0 (uppAboves (map fmt xs))) >>