2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
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 BasicTypes ( Fixity(..), FixityDirection(..), NewOrData(..), IfaceFlavour(..),
24 import RnEnv ( availName, ifaceFlavour )
26 import TcInstUtil ( InstInfo(..) )
27 import WorkWrap ( getWorkerIdAndCons )
30 import Id ( Id, idType, idInfo, omitIfaceSigForId,
35 import DataCon ( dataConSig, dataConFieldLabels, dataConStrictMarks )
36 import IdInfo ( IdInfo, StrictnessInfo, ArityInfo, InlinePragInfo(..), inlinePragInfo,
37 arityInfo, ppArityInfo,
38 strictnessInfo, ppStrictnessInfo,
40 workerExists, isBottomingStrictness
42 import CoreSyn ( CoreExpr, CoreBind, Bind(..) )
43 import CoreUtils ( exprSomeFreeVars )
44 import CoreUnfold ( calcUnfoldingGuidance, UnfoldingGuidance(..),
45 Unfolding, okToUnfoldInHiFile )
46 import Name ( isLocallyDefined, isWiredInName, modAndOcc, nameModule,
47 OccName, pprOccName, pprModule, isExported, moduleString,
50 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
51 tyConTheta, tyConTyVars, tyConDataCons
53 import Class ( Class, classBigSig )
54 import SpecEnv ( specEnvToList )
55 import FieldLabel ( fieldLabelName, fieldLabelType )
56 import Type ( mkSigmaTy, splitSigmaTy, mkDictTy, tidyTopType, deNoteType,
61 import PprCore ( pprIfaceUnfolding )
63 import Bag ( bagToList, isEmptyBag )
64 import Maybes ( catMaybes, maybeToBool )
65 import FiniteMap ( emptyFM, addToFM, addToFM_C, fmToList, FiniteMap )
66 import UniqFM ( lookupUFM, listToUFM )
67 import UniqSet ( uniqSetToList )
68 import Util ( sortLt, 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 -> [CoreBind] -- 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 hPutStr if_hdl ("__interface " ++ moduleString mod ++ ' ':show (opt_HiVersion :: Int))
106 hPutStrLn if_hdl " where"
109 endIface Nothing = return ()
110 endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl
115 ifaceMain Nothing iface_stuff = return ()
116 ifaceMain (Just if_hdl)
117 (import_usages, ExportEnv avails fixities, instance_modules)
119 ifaceImports if_hdl import_usages
120 ifaceInstanceModules if_hdl instance_modules
121 ifaceExports if_hdl avails
122 ifaceFixities if_hdl fixities
125 ifaceDecls Nothing tycons classes inst_info final_ids simplified = return ()
126 ifaceDecls (Just hdl)
130 | null_decls = return ()
131 -- You could have a module with just (re-)exports/instances in it
133 = ifaceClasses hdl classes >>
134 ifaceInstances hdl inst_infos >>= \ needed_ids ->
135 ifaceTyCons hdl tycons >>
136 ifaceBinds hdl needed_ids final_ids binds >>
139 null_decls = null binds &&
142 isEmptyBag inst_infos
146 ifaceImports if_hdl import_usages
147 = hPutCol if_hdl upp_uses (sortLt lt_imp_vers import_usages)
149 upp_uses (m, hif, mv, whats_imported)
150 = ptext SLIT("import ") <>
151 hsep [pprModule m, pp_hif hif, int mv, dcolon,
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 = let sorted = sortLt (<) imods
165 lines = map (\m -> ptext SLIT("__instimport ") <> pprModule m <>
166 ptext SLIT(" ;")) sorted
168 printForIface if_hdl (vcat lines) >>
171 ifaceExports if_hdl [] = return ()
172 ifaceExports if_hdl avails
173 = hPutCol if_hdl do_one_module (fmToList export_fm)
175 -- Sort them into groups by module
176 export_fm :: FiniteMap Module [AvailInfo]
177 export_fm = foldr insert emptyFM avails
179 insert NotAvailable efm = efm
180 insert avail efm = addToFM_C (++) efm mod [avail]
182 mod = nameModule (availName avail)
184 -- Print one module's worth of stuff
185 do_one_module :: (Module, [AvailInfo]) -> SDoc
186 do_one_module (mod_name, avails@(avail1:_))
187 = ptext SLIT("__export ") <>
188 hsep [pp_hif (ifaceFlavour (availName avail1)),
190 hsep (map upp_avail (sortLt lt_avail avails))
193 -- The "!" indicates that the exported things came from a hi-boot interface
194 pp_hif HiFile = empty
195 pp_hif HiBootFile = char '!'
197 ifaceFixities if_hdl [] = return ()
198 ifaceFixities if_hdl fixities
199 = hPutCol if_hdl upp_fixity fixities
202 %************************************************************************
204 \subsection{Instance declarations}
206 %************************************************************************
210 ifaceInstances :: Handle -> Bag InstInfo -> IO IdSet -- The IdSet is the needed dfuns
211 ifaceInstances if_hdl inst_infos
212 | null togo_insts = return emptyVarSet
213 | otherwise = hPutCol if_hdl pp_inst (sortLt lt_inst togo_insts) >>
216 togo_insts = filter is_togo_inst (bagToList inst_infos)
217 needed_ids = mkVarSet [dfun_id | InstInfo _ _ _ _ dfun_id _ _ _ <- togo_insts]
218 is_togo_inst (InstInfo _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
221 lt_inst (InstInfo _ _ _ _ dfun_id1 _ _ _)
222 (InstInfo _ _ _ _ dfun_id2 _ _ _)
223 = getOccName dfun_id1 < getOccName dfun_id2
224 -- The dfuns are assigned names df1, df2, etc, in order of original textual
225 -- occurrence, and this makes as good a sort order as any
228 pp_inst (InstInfo clas tvs tys theta dfun_id _ _ _)
230 -- The deNoteType is very important. It removes all type
231 -- synonyms from the instance type in interface files.
232 -- That in turn makes sure that when reading in instance decls
233 -- from interface files that the 'gating' mechanism works properly.
234 -- Otherwise you could have
235 -- type Tibble = T Int
236 -- instance Foo Tibble where ...
237 -- and this instance decl wouldn't get imported into a module
238 -- that mentioned T but not Tibble.
239 forall_ty = mkSigmaTy tvs theta (deNoteType (mkDictTy clas tys))
240 renumbered_ty = tidyTopType forall_ty
242 hcat [ptext SLIT("instance "), pprType renumbered_ty,
243 ptext SLIT(" = "), ppr_unqual_name dfun_id, semi]
247 %************************************************************************
249 \subsection{Printing values}
251 %************************************************************************
254 ifaceId :: (Id -> IdInfo) -- This function "knows" the extra info added
255 -- by the STG passes. Sigh
257 -> IdSet -- Set of Ids that are needed by earlier interface
258 -- file emissions. If the Id isn't in this set, and isn't
259 -- exported, there's no need to emit anything
260 -> Bool -- True <=> recursive, so don't print unfolding
262 -> CoreExpr -- The Id's right hand side
263 -> Maybe (SDoc, IdSet) -- The emitted stuff, plus a possibly-augmented set of needed Ids
265 ifaceId get_idinfo needed_ids is_rec id rhs
266 | not (id `elemVarSet` needed_ids || -- Needed [no id in needed_ids has omitIfaceSigForId]
267 (isExported id && not (omitIfaceSigForId id))) -- or exported and not to be omitted
268 = Nothing -- Well, that was easy!
270 ifaceId get_idinfo needed_ids is_rec id rhs
271 = Just (hsep [sig_pretty, prag_pretty, char ';'], new_needed_ids)
273 idinfo = get_idinfo id
274 inline_pragma = inlinePragInfo idinfo
276 ty_pretty = pprType (idType id)
277 sig_pretty = hsep [ppr (getOccName id), dcolon, ty_pretty]
280 | opt_OmitInterfacePragmas = empty
281 | otherwise = hsep [ptext SLIT("{-##"),
289 ------------ Arity --------------
290 arity_pretty = ppArityInfo (arityInfo idinfo)
292 ------------ Caf Info --------------
293 caf_pretty = ppCafInfo (cafInfo idinfo)
295 ------------ Strictness --------------
296 strict_info = strictnessInfo idinfo
297 has_worker = workerExists strict_info
298 bottoming_fn = isBottomingStrictness strict_info
299 strict_pretty = ppStrictnessInfo strict_info <+> wrkr_pretty
301 wrkr_pretty | not has_worker = empty
302 | null con_list = ppr work_id
303 | otherwise = ppr work_id <+>
304 braces (hsep (map ppr con_list))
306 (work_id, wrapper_cons) = getWorkerIdAndCons id rhs
307 con_list = uniqSetToList wrapper_cons
309 ------------ Unfolding --------------
310 unfold_pretty | show_unfold = unfold_herald <+> pprIfaceUnfolding rhs
313 show_unfold = not has_worker && -- Not unnecessary
314 not bottoming_fn && -- Not necessary
315 unfolding_needed -- Not dangerous
317 unfolding_needed = case inline_pragma of
318 IMustBeINLINEd -> definitely_ok_to_unfold
319 IWantToBeINLINEd -> definitely_ok_to_unfold
320 NoInlinePragInfo -> rhs_is_small
324 unfold_herald = case inline_pragma of
325 NoInlinePragInfo -> ptext SLIT("__u")
326 other -> ppr inline_pragma
328 rhs_is_small = case calcUnfoldingGuidance opt_InterfaceUnfoldThreshold rhs of
329 UnfoldNever -> False -- Too big
330 other -> definitely_ok_to_unfold -- Small enough
332 definitely_ok_to_unfold = okToUnfoldInHiFile rhs
334 ------------ Specialisations --------------
335 spec_list = specEnvToList (getIdSpecialisation id)
336 spec_pretty = hsep (map pp_spec spec_list)
337 pp_spec (tyvars, tys, rhs) = hsep [ptext SLIT("__P"),
338 if null tyvars then ptext SLIT("[ ]")
339 else brackets (interppSP tyvars),
340 -- The lexer interprets "[]" as a CONID. Sigh.
341 hsep (map pprParendType tys),
343 pprIfaceUnfolding rhs
346 ------------ Extra free Ids --------------
347 new_needed_ids = (needed_ids `minusVarSet` unitVarSet id) `unionVarSet`
350 extra_ids | opt_OmitInterfacePragmas = emptyVarSet
351 | otherwise = worker_ids `unionVarSet`
352 unfold_ids `unionVarSet`
355 worker_ids | has_worker = unitVarSet work_id
356 | otherwise = emptyVarSet
358 spec_ids = foldr add emptyVarSet spec_list
360 add (_, _, rhs) = unionVarSet (find_fvs rhs)
362 unfold_ids | show_unfold = find_fvs rhs
363 | otherwise = emptyVarSet
365 find_fvs expr = free_vars
367 free_vars = exprSomeFreeVars interesting expr
368 interesting id = isId id && isLocallyDefined id &&
369 not (omitIfaceSigForId id)
374 -> IdSet -- These Ids are needed already
375 -> [Id] -- Ids used at code-gen time; they have better pragma info!
376 -> [CoreBind] -- In dependency order, later depend on earlier
379 ifaceBinds hdl needed_ids final_ids binds
380 = mapIO (printForIface hdl) pretties >>
383 final_id_map = listToUFM [(id,id) | id <- final_ids]
384 get_idinfo id = case lookupUFM final_id_map id of
385 Just id' -> idInfo id'
386 Nothing -> pprTrace "ifaceBinds not found:" (ppr id) $
389 pretties = go needed_ids (reverse binds) -- Reverse so that later things will
390 -- provoke earlier ones to be emitted
391 go needed [] = if not (isEmptyVarSet needed) then
392 pprTrace "ifaceBinds: free vars:"
393 (sep (map ppr (varSetElems needed))) $
398 go needed (NonRec id rhs : binds)
399 = case ifaceId get_idinfo needed False id rhs of
400 Nothing -> go needed binds
401 Just (pretty, needed') -> pretty : go needed' binds
403 -- Recursive groups are a bit more of a pain. We may only need one to
404 -- start with, but it may call out the next one, and so on. So we
405 -- have to look for a fixed point.
406 go needed (Rec pairs : binds)
407 = pretties ++ go needed'' binds
409 (needed', pretties) = go_rec needed pairs
410 needed'' = needed' `minusVarSet` mkVarSet (map fst pairs)
411 -- Later ones may spuriously cause earlier ones to be "needed" again
413 go_rec :: IdSet -> [(Id,CoreExpr)] -> (IdSet, [SDoc])
415 | null pretties = (needed, [])
416 | otherwise = (final_needed, more_pretties ++ pretties)
418 reduced_pairs = [pair | (pair,Nothing) <- pairs `zip` maybes]
419 pretties = catMaybes maybes
420 (needed', maybes) = mapAccumL do_one needed pairs
421 (final_needed, more_pretties) = go_rec needed' reduced_pairs
423 do_one needed (id,rhs) = case ifaceId get_idinfo needed True id rhs of
424 Nothing -> (needed, Nothing)
425 Just (pretty, needed') -> (needed', Just pretty)
429 %************************************************************************
431 \subsection{Random small things}
433 %************************************************************************
436 ifaceTyCons hdl tycons = hPutCol hdl upp_tycon (sortLt (<) (filter (for_iface_name . getName) tycons ))
437 ifaceClasses hdl classes = hPutCol hdl upp_class (sortLt (<) (filter (for_iface_name . getName) classes))
439 for_iface_name name = isLocallyDefined name &&
440 not (isWiredInName name)
442 upp_tycon tycon = ifaceTyCon tycon
443 upp_class clas = ifaceClass clas
448 ifaceTyCon :: TyCon -> SDoc
451 = hsep [ ptext SLIT("type"),
453 pprTyVarBndrs tyvars,
459 (tyvars, ty) = getSynTyConDefn tycon
463 = hsep [ ptext keyword,
464 ppr_decl_context (tyConTheta tycon),
466 pprTyVarBndrs (tyConTyVars tycon),
468 hsep (punctuate (ptext SLIT(" | ")) (map ppr_con (tyConDataCons tycon))),
472 keyword | isNewTyCon tycon = SLIT("newtype")
473 | otherwise = SLIT("data")
475 tyvars = tyConTyVars tycon
479 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
480 hsep [ ppr_ex ex_tyvars ex_theta,
482 hsep (map ppr_arg_ty (strict_marks `zip` arg_tys))
486 = hsep [ ppr_ex ex_tyvars ex_theta,
488 braces $ hsep $ punctuate comma (map ppr_field (strict_marks `zip` field_labels))
491 (tyvars1, theta1, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
492 field_labels = dataConFieldLabels data_con
493 strict_marks = dataConStrictMarks data_con
494 name = getName data_con
496 ppr_ex [] ex_theta = ASSERT( null ex_theta ) empty
497 ppr_ex ex_tvs ex_theta = ptext SLIT("__forall") <+> brackets (pprTyVarBndrs ex_tvs)
498 <+> pprIfaceTheta ex_theta <+> ptext SLIT("=>")
500 ppr_arg_ty (strict_mark, ty) = ppr_strict_mark strict_mark <> pprParendType ty
502 ppr_strict_mark NotMarkedStrict = empty
503 ppr_strict_mark MarkedStrict = ptext SLIT("! ")
504 -- The extra space helps the lexical analyser that lexes
505 -- interface files; it doesn't make the rigid operator/identifier
506 -- distinction, so "!a" is a valid identifier so far as it is concerned
508 ppr_field (strict_mark, field_label)
509 = hsep [ ppr (fieldLabelName field_label),
511 ppr_strict_mark strict_mark <> pprParendType (fieldLabelType field_label)
515 = pprPanic "pprIfaceTyDecl" (ppr tycon)
518 = hsep [ptext SLIT("class"),
519 ppr_decl_context sc_theta,
520 ppr clas, -- Print the name
521 pprTyVarBndrs clas_tyvars,
526 (clas_tyvars, sc_theta, _, sel_ids, defms) = classBigSig clas
528 pp_ops | null sel_ids = empty
529 | otherwise = hsep [ptext SLIT("where"),
530 braces (hsep (punctuate semi (zipWith ppr_classop sel_ids defms)))
533 ppr_classop sel_id maybe_defm
534 = ASSERT( sel_tyvars == clas_tyvars)
535 hsep [ppr (getOccName sel_id),
536 if maybeToBool maybe_defm then equals else empty,
541 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
543 ppr_decl_context :: ThetaType -> SDoc
544 ppr_decl_context [] = empty
545 ppr_decl_context theta = pprIfaceTheta theta <+> ptext SLIT(" =>")
547 pprIfaceTheta :: ThetaType -> SDoc -- Use braces rather than parens in interface files
548 pprIfaceTheta theta = braces (hsep (punctuate comma [pprConstraint c tys | (c,tys) <- theta]))
551 %************************************************************************
553 \subsection{Random small things}
555 %************************************************************************
557 When printing export lists, we print like this:
559 AvailTC C [C, x, y] C(x,y)
560 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
563 upp_avail :: AvailInfo -> SDoc
564 upp_avail NotAvailable = empty
565 upp_avail (Avail name) = pprOccName (getOccName name)
566 upp_avail (AvailTC name []) = empty
567 upp_avail (AvailTC name ns) = hcat [pprOccName (getOccName name), bang, upp_export ns']
569 bang | name `elem` ns = empty
570 | otherwise = char '|'
571 ns' = filter (/= name) ns
573 upp_export :: [Name] -> SDoc
574 upp_export [] = empty
575 upp_export names = braces (hsep (map (pprOccName . getOccName) names))
577 upp_fixity :: (Name, Fixity) -> SDoc
578 upp_fixity (name, fixity) = hsep [ptext SLIT("0"), ppr fixity, ppr name, semi]
579 -- Dummy version number!
581 ppr_unqual_name :: NamedThing a => a -> SDoc -- Just its occurrence name
582 ppr_unqual_name name = pprOccName (getOccName name)
586 %************************************************************************
588 \subsection{Comparisons
590 %************************************************************************
593 The various sorts above simply prevent unnecessary "wobbling" when
594 things change that don't have to. We therefore compare lexically, not
598 lt_avail :: AvailInfo -> AvailInfo -> Bool
600 a1 `lt_avail` a2 = availName a1 `lt_name` availName a2
602 lt_name :: Name -> Name -> Bool
603 n1 `lt_name` n2 = modAndOcc n1 < modAndOcc n2
605 lt_lexical :: NamedThing a => a -> a -> Bool
606 lt_lexical a1 a2 = getName a1 `lt_name` getName a2
608 lt_imp_vers :: ImportVersion a -> ImportVersion a -> Bool
609 lt_imp_vers (m1,_,_,_) (m2,_,_,_) = m1 < m2
611 sort_versions vs = sortLt lt_vers vs
613 lt_vers :: LocalVersion Name -> LocalVersion Name -> Bool
614 lt_vers (n1,v1) (n2,v2) = n1 `lt_name` n2
623 hPutCol hdl fmt xs = mapIO (printForIface hdl . fmt) xs
625 mapIO :: (a -> IO b) -> [a] -> IO ()
626 mapIO f [] = return ()
627 mapIO f (x:xs) = f x >> mapIO f xs