2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[MkIface]{Print an interface for a module}
8 startIface, endIface, ifaceDecls
11 #include "HsVersions.h"
13 import IO ( Handle, hPutStr, openFile,
14 hClose, hPutStrLn, IOMode(..) )
17 import BasicTypes ( Fixity(..), FixityDirection(..), NewOrData(..) )
19 import RnEnv ( availName )
21 import TcInstUtil ( InstInfo(..) )
24 import Id ( Id, idType, idInfo, omitIfaceSigForId, isUserExportedId,
29 import DataCon ( StrictnessMark(..), dataConSig, dataConFieldLabels, dataConStrictMarks )
30 import IdInfo ( IdInfo, StrictnessInfo(..), ArityInfo, InlinePragInfo(..), inlinePragInfo,
31 arityInfo, ppArityInfo, arityLowerBound,
32 strictnessInfo, ppStrictnessInfo, isBottomingStrictness,
33 cafInfo, ppCafInfo, specInfo,
34 cprInfo, ppCprInfo, pprInlinePragInfo,
36 workerExists, workerInfo, ppWorkerInfo
38 import CoreSyn ( CoreExpr, CoreBind, Bind(..), rulesRules, rulesRhsFreeVars )
39 import CoreFVs ( exprSomeFreeVars, ruleSomeLhsFreeVars, ruleSomeFreeVars )
40 import CoreUnfold ( calcUnfoldingGuidance, okToUnfoldInHiFile, couldBeSmallEnoughToInline )
41 import Module ( moduleString, pprModule, pprModuleName )
42 import Name ( isLocallyDefined, isWiredInName, nameRdrName, nameModule,
45 import OccName ( OccName, pprOccName )
46 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon,
47 tyConTheta, tyConTyVars, tyConDataCons
49 import Class ( Class, classExtraBigSig )
50 import FieldLabel ( fieldLabelName, fieldLabelType )
51 import Type ( mkSigmaTy, splitSigmaTy, mkDictTy, tidyTopType, deNoteType,
56 import PprCore ( pprIfaceUnfolding, pprCoreRule )
57 import FunDeps ( pprFundeps )
58 import Rules ( pprProtoCoreRule, ProtoCoreRule(..) )
60 import Bag ( bagToList, isEmptyBag )
61 import Maybes ( catMaybes, maybeToBool )
62 import FiniteMap ( emptyFM, addToFM, addToFM_C, fmToList, FiniteMap )
63 import UniqFM ( lookupUFM, listToUFM )
64 import UniqSet ( uniqSetToList )
65 import Util ( sortLt, mapAccumL )
70 We have a function @startIface@ to open the output file and put
71 (something like) ``interface Foo'' in it. It gives back a handle
72 for subsequent additions to the interface file.
74 We then have one-function-per-block-of-interface-stuff, e.g.,
75 @ifaceExportList@ produces the @__exports__@ section; it appends
76 to the handle provided by @startIface@.
79 startIface :: Module -> InterfaceDetails
80 -> IO (Maybe Handle) -- Nothing <=> don't do an interface
82 ifaceDecls :: Maybe Handle
85 -> [Id] -- Ids used at code-gen time; they have better pragma info!
86 -> [CoreBind] -- In dependency order, later depend on earlier
87 -> [ProtoCoreRule] -- Rules
90 endIface :: Maybe Handle -> IO ()
94 startIface mod (has_orphans, import_usages, ExportEnv avails fixities)
95 = case opt_ProduceHi of
96 Nothing -> return Nothing ; -- not producing any .hi file
99 if_hdl <- openFile fn WriteMode
100 hPutStr if_hdl ("__interface " ++ moduleString mod)
101 hPutStr if_hdl (' ' : show (opt_HiVersion :: Int) ++ orphan_indicator)
102 hPutStrLn if_hdl " where"
103 ifaceExports if_hdl avails
104 ifaceImports if_hdl import_usages
105 ifaceFixities if_hdl fixities
108 orphan_indicator | has_orphans = " !"
111 endIface Nothing = return ()
112 endIface (Just if_hdl) = hPutStr if_hdl "\n" >> hClose if_hdl
117 ifaceDecls Nothing tycons classes inst_info final_ids simplified rules = return ()
118 ifaceDecls (Just hdl)
122 orphan_rules -- Rules defined locally for an Id that is *not* defined locally
123 | null_decls = return ()
124 -- You could have a module with just (re-)exports/instances in it
126 = ifaceClasses hdl classes >>
127 ifaceInstances hdl inst_infos >>= \ inst_ids ->
128 ifaceTyCons hdl tycons >>
129 ifaceBinds hdl (inst_ids `unionVarSet` orphan_rule_ids)
130 final_ids binds >>= \ emitted_ids ->
131 ifaceRules hdl orphan_rules emitted_ids >>
134 orphan_rule_ids = unionVarSets [ ruleSomeFreeVars interestingId rule
135 | ProtoCoreRule _ _ rule <- orphan_rules]
137 null_decls = null binds &&
140 isEmptyBag inst_infos &&
145 ifaceImports if_hdl import_usages
146 = hPutCol if_hdl upp_uses (sortLt lt_imp_vers import_usages)
148 upp_uses (m, mv, has_orphans, whats_imported)
149 = hsep [ptext SLIT("import"), pprModuleName m,
151 upp_import_versions whats_imported
154 pp_orphan | has_orphans = ptext SLIT("!")
157 -- Importing the whole module is indicated by an empty list
158 upp_import_versions Everything = empty
160 -- For imported versions we do print the version number
161 upp_import_versions (Specifically nvs)
162 = dcolon <+> hsep [ hsep [ppr_unqual_name n, int v] | (n,v) <- sort_versions nvs ]
164 ifaceModuleDeps if_hdl [] = return ()
165 ifaceModuleDeps if_hdl mod_deps
167 lines = map ppr_mod_dep mod_deps
168 ppr_mod_dep (mod, contains_orphans)
169 | contains_orphans = pprModuleName mod <+> ptext SLIT("!")
170 | otherwise = pprModuleName mod
172 printForIface if_hdl (ptext SLIT("__depends") <+> vcat lines <> ptext SLIT(" ;")) >>
175 ifaceExports if_hdl [] = return ()
176 ifaceExports if_hdl avails
177 = hPutCol if_hdl do_one_module (fmToList export_fm)
179 -- Sort them into groups by module
180 export_fm :: FiniteMap Module [AvailInfo]
181 export_fm = foldr insert emptyFM avails
183 insert avail efm = addToFM_C (++) efm mod [avail]
185 mod = nameModule (availName avail)
187 -- Print one module's worth of stuff
188 do_one_module :: (Module, [AvailInfo]) -> SDoc
189 do_one_module (mod_name, avails@(avail1:_))
190 = ptext SLIT("__export ") <>
191 hsep [pprModule mod_name,
192 hsep (map upp_avail (sortLt lt_avail avails))
195 ifaceFixities if_hdl [] = return ()
196 ifaceFixities if_hdl fixities
197 = hPutCol if_hdl upp_fixity fixities
199 ifaceRules if_hdl rules emitted
200 | null orphan_rule_pretties && null local_id_pretties
203 = do printForIface if_hdl (vcat [
204 ptext SLIT("{-## __R"),
206 vcat orphan_rule_pretties,
208 vcat local_id_pretties,
215 orphan_rule_pretties = [ pprCoreRule (Just fn) rule <+> semi
216 | ProtoCoreRule _ fn rule <- rules
218 local_id_pretties = [ pprCoreRule (Just fn) rule <+> semi
219 | fn <- varSetElems emitted,
220 rule <- rulesRules (getIdSpecialisation fn),
221 all (`elemVarSet` emitted) (varSetElems (ruleSomeLhsFreeVars interestingId rule))
222 -- Spit out a rule only if all its lhs free vars are eemitted
226 %************************************************************************
228 \subsection{Instance declarations}
230 %************************************************************************
234 ifaceInstances :: Handle -> Bag InstInfo -> IO IdSet -- The IdSet is the needed dfuns
235 ifaceInstances if_hdl inst_infos
236 | null togo_insts = return emptyVarSet
237 | otherwise = hPutCol if_hdl pp_inst (sortLt lt_inst togo_insts) >>
240 togo_insts = filter is_togo_inst (bagToList inst_infos)
241 needed_ids = mkVarSet [dfun_id | InstInfo _ _ _ _ dfun_id _ _ _ <- togo_insts]
242 is_togo_inst (InstInfo _ _ _ _ dfun_id _ _ _) = isLocallyDefined dfun_id
245 lt_inst (InstInfo _ _ _ _ dfun_id1 _ _ _)
246 (InstInfo _ _ _ _ dfun_id2 _ _ _)
247 = getOccName dfun_id1 < getOccName dfun_id2
248 -- The dfuns are assigned names df1, df2, etc, in order of original textual
249 -- occurrence, and this makes as good a sort order as any
252 pp_inst (InstInfo clas tvs tys theta dfun_id _ _ _)
254 -- The deNoteType is very important. It removes all type
255 -- synonyms from the instance type in interface files.
256 -- That in turn makes sure that when reading in instance decls
257 -- from interface files that the 'gating' mechanism works properly.
258 -- Otherwise you could have
259 -- type Tibble = T Int
260 -- instance Foo Tibble where ...
261 -- and this instance decl wouldn't get imported into a module
262 -- that mentioned T but not Tibble.
263 forall_ty = mkSigmaTy tvs theta (deNoteType (mkDictTy clas tys))
264 renumbered_ty = tidyTopType forall_ty
266 hcat [ptext SLIT("instance "), pprType renumbered_ty,
267 ptext SLIT(" = "), ppr_unqual_name dfun_id, semi]
271 %************************************************************************
273 \subsection{Printing values}
275 %************************************************************************
278 ifaceId :: (Id -> IdInfo) -- This function "knows" the extra info added
279 -- by the STG passes. Sigh
281 -> IdSet -- Set of Ids that are needed by earlier interface
282 -- file emissions. If the Id isn't in this set, and isn't
283 -- exported, there's no need to emit anything
284 -> Bool -- True <=> recursive, so don't print unfolding
286 -> CoreExpr -- The Id's right hand side
287 -> Maybe (SDoc, IdSet) -- The emitted stuff, plus any *extra* needed Ids
289 ifaceId get_idinfo needed_ids is_rec id rhs
290 | not (id `elemVarSet` needed_ids || -- Needed [no id in needed_ids has omitIfaceSigForId]
291 (isUserExportedId id && not (omitIfaceSigForId id))) -- or exported and not to be omitted
292 = Nothing -- Well, that was easy!
294 ifaceId get_idinfo needed_ids is_rec id rhs
295 = ASSERT2( arity_matches_strictness, ppr id )
296 Just (hsep [sig_pretty, prag_pretty, char ';'], new_needed_ids)
298 core_idinfo = idInfo id
299 stg_idinfo = get_idinfo id
301 ty_pretty = pprType (idType id)
302 sig_pretty = hsep [ppr (getOccName id), dcolon, ty_pretty]
305 | opt_OmitInterfacePragmas = empty
306 | otherwise = hsep [ptext SLIT("{-##"),
315 ------------ Arity --------------
316 arity_info = arityInfo stg_idinfo
317 arity_pretty = ppArityInfo arity_info
319 ------------ Caf Info --------------
320 caf_pretty = ppCafInfo (cafInfo stg_idinfo)
322 ------------ CPR Info --------------
323 cpr_pretty = ppCprInfo (cprInfo core_idinfo)
325 ------------ Strictness --------------
326 strict_info = strictnessInfo core_idinfo
327 bottoming_fn = isBottomingStrictness strict_info
328 strict_pretty = ppStrictnessInfo strict_info
330 ------------ Worker --------------
331 work_info = workerInfo core_idinfo
332 has_worker = workerExists work_info
333 wrkr_pretty = ppWorkerInfo work_info
334 Just work_id = work_info
337 ------------ Occ info --------------
338 loop_breaker = case occInfo core_idinfo of
339 IAmALoopBreaker -> True
342 ------------ Unfolding --------------
343 inline_pragma = inlinePragInfo core_idinfo
344 dont_inline = case inline_pragma of
345 IMustNotBeINLINEd False Nothing -> True -- Unconditional NOINLINE
349 unfold_pretty | show_unfold = ptext SLIT("__U") <> pprInlinePragInfo inline_pragma <+> pprIfaceUnfolding rhs
352 show_unfold = not has_worker && -- Not unnecessary
353 not bottoming_fn && -- Not necessary
356 rhs_is_small && -- Small enough
357 okToUnfoldInHiFile rhs -- No casms etc
359 rhs_is_small = couldBeSmallEnoughToInline (calcUnfoldingGuidance opt_UF_HiFileThreshold rhs)
361 ------------ Specialisations --------------
362 spec_info = specInfo core_idinfo
364 ------------ Extra free Ids --------------
365 new_needed_ids | opt_OmitInterfacePragmas = emptyVarSet
366 | otherwise = worker_ids `unionVarSet`
367 unfold_ids `unionVarSet`
370 worker_ids | has_worker && interestingId work_id = unitVarSet work_id
371 -- Conceivably, the worker might come from
373 | otherwise = emptyVarSet
375 spec_ids = filterVarSet interestingId (rulesRhsFreeVars spec_info)
377 unfold_ids | show_unfold = find_fvs rhs
378 | otherwise = emptyVarSet
380 find_fvs expr = exprSomeFreeVars interestingId expr
382 ------------ Sanity checking --------------
383 -- The arity of a wrapper function should match its strictness,
384 -- or else an importing module will get very confused indeed.
385 -- [later: actually all that is necessary is for strictness to exceed arity]
386 arity_matches_strictness
389 StrictnessInfo ds _ -> length ds >= arityLowerBound arity_info
392 interestingId id = isId id && isLocallyDefined id &&
393 not (omitIfaceSigForId id)
398 -> IdSet -- These Ids are needed already
399 -> [Id] -- Ids used at code-gen time; they have better pragma info!
400 -> [CoreBind] -- In dependency order, later depend on earlier
401 -> IO IdSet -- Set of Ids actually spat out
403 ifaceBinds hdl needed_ids final_ids binds
404 = mapIO (printForIface hdl) (bagToList pretties) >>
408 final_id_map = listToUFM [(id,id) | id <- final_ids]
409 get_idinfo id = case lookupUFM final_id_map id of
410 Just id' -> idInfo id'
411 Nothing -> pprTrace "ifaceBinds not found:" (ppr id) $
414 (pretties, emitted) = go needed_ids (reverse binds) emptyBag emptyVarSet
415 -- Reverse so that later things will
416 -- provoke earlier ones to be emitted
417 go needed [] pretties emitted
418 | not (isEmptyVarSet needed) = pprTrace "ifaceBinds: free vars:"
419 (sep (map ppr (varSetElems needed)))
421 | otherwise = (pretties, emitted)
423 go needed (NonRec id rhs : binds) pretties emitted
424 = case ifaceId get_idinfo needed False id rhs of
425 Nothing -> go needed binds pretties emitted
426 Just (pretty, extras) -> let
427 needed' = (needed `unionVarSet` extras) `delVarSet` id
428 -- 'extras' can include the Id itself via a rule
429 emitted' = emitted `extendVarSet` id
431 go needed' binds (pretty `consBag` pretties) emitted'
433 -- Recursive groups are a bit more of a pain. We may only need one to
434 -- start with, but it may call out the next one, and so on. So we
435 -- have to look for a fixed point.
436 go needed (Rec pairs : binds) pretties emitted
437 = go needed' binds pretties' emitted'
439 (new_pretties, new_emitted, extras) = go_rec needed pairs
440 pretties' = new_pretties `unionBags` pretties
441 needed' = (needed `unionVarSet` extras) `minusVarSet` mkVarSet (map fst pairs)
442 emitted' = emitted `unionVarSet` new_emitted
444 go_rec :: IdSet -> [(Id,CoreExpr)] -> (Bag SDoc, IdSet, IdSet)
446 | null pretties = (emptyBag, emptyVarSet, emptyVarSet)
447 | otherwise = (more_pretties `unionBags` listToBag pretties,
448 more_emitted `unionVarSet` mkVarSet emitted,
449 more_extras `unionVarSet` extras)
451 maybes = map do_one pairs
452 emitted = [id | ((id,_), Just _) <- pairs `zip` maybes]
453 reduced_pairs = [pair | (pair, Nothing) <- pairs `zip` maybes]
454 (pretties, extras_s) = unzip (catMaybes maybes)
455 extras = unionVarSets extras_s
456 (more_pretties, more_emitted, more_extras) = go_rec extras reduced_pairs
458 do_one (id,rhs) = ifaceId get_idinfo needed True id rhs
462 %************************************************************************
464 \subsection{Random small things}
466 %************************************************************************
469 ifaceTyCons hdl tycons = hPutCol hdl upp_tycon (sortLt (<) (filter (for_iface_name . getName) tycons ))
470 ifaceClasses hdl classes = hPutCol hdl upp_class (sortLt (<) (filter (for_iface_name . getName) classes))
472 for_iface_name name = isLocallyDefined name &&
473 not (isWiredInName name)
475 upp_tycon tycon = ifaceTyCon tycon
476 upp_class clas = ifaceClass clas
481 ifaceTyCon :: TyCon -> SDoc
484 = hsep [ ptext SLIT("type"),
486 pprTyVarBndrs tyvars,
492 (tyvars, ty) = getSynTyConDefn tycon
496 = hsep [ ptext keyword,
497 ppr_decl_context (tyConTheta tycon),
499 pprTyVarBndrs (tyConTyVars tycon),
501 hsep (punctuate (ptext SLIT(" | ")) (map ppr_con (tyConDataCons tycon))),
505 keyword | isNewTyCon tycon = SLIT("newtype")
506 | otherwise = SLIT("data")
508 tyvars = tyConTyVars tycon
512 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
513 hsep [ ppr_ex ex_tyvars ex_theta,
515 hsep (map ppr_arg_ty (strict_marks `zip` arg_tys))
519 = hsep [ ppr_ex ex_tyvars ex_theta,
521 braces $ hsep $ punctuate comma (map ppr_field (strict_marks `zip` field_labels))
524 (tyvars1, theta1, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
525 field_labels = dataConFieldLabels data_con
526 strict_marks = dataConStrictMarks data_con
527 name = getName data_con
529 ppr_ex [] ex_theta = ASSERT( null ex_theta ) empty
530 ppr_ex ex_tvs ex_theta = ptext SLIT("__forall") <+> brackets (pprTyVarBndrs ex_tvs)
531 <+> pprIfaceTheta ex_theta <+> ptext SLIT("=>")
533 ppr_arg_ty (strict_mark, ty) = ppr_strict_mark strict_mark <> pprParendType ty
535 ppr_strict_mark NotMarkedStrict = empty
536 ppr_strict_mark (MarkedUnboxed _ _) = ptext SLIT("! ! ")
537 ppr_strict_mark MarkedStrict = ptext SLIT("! ")
539 ppr_field (strict_mark, field_label)
540 = hsep [ ppr (fieldLabelName field_label),
542 ppr_strict_mark strict_mark <> pprParendType (fieldLabelType field_label)
546 = pprPanic "pprIfaceTyDecl" (ppr tycon)
549 = hsep [ptext SLIT("class"),
550 ppr_decl_context sc_theta,
551 ppr clas, -- Print the name
552 pprTyVarBndrs clas_tyvars,
558 (clas_tyvars, clas_fds, sc_theta, _, op_stuff) = classExtraBigSig clas
560 pp_ops | null op_stuff = empty
561 | otherwise = hsep [ptext SLIT("where"),
562 braces (hsep (punctuate semi (map ppr_classop op_stuff)))
565 ppr_classop (sel_id, dm_id, explicit_dm)
566 = ASSERT( sel_tyvars == clas_tyvars)
567 hsep [ppr (getOccName sel_id),
568 if explicit_dm then equals else empty,
573 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
575 ppr_decl_context :: ThetaType -> SDoc
576 ppr_decl_context [] = empty
577 ppr_decl_context theta = pprIfaceTheta theta <+> ptext SLIT(" =>")
579 pprIfaceTheta :: ThetaType -> SDoc -- Use braces rather than parens in interface files
580 pprIfaceTheta [] = empty
581 pprIfaceTheta theta = braces (hsep (punctuate comma [pprConstraint c tys | (c,tys) <- theta]))
584 %************************************************************************
586 \subsection{Random small things}
588 %************************************************************************
590 When printing export lists, we print like this:
592 AvailTC C [C, x, y] C(x,y)
593 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
596 upp_avail :: AvailInfo -> SDoc
597 upp_avail (Avail name) = pprOccName (getOccName name)
598 upp_avail (AvailTC name []) = empty
599 upp_avail (AvailTC name ns) = hcat [pprOccName (getOccName name), bang, upp_export ns']
601 bang | name `elem` ns = empty
602 | otherwise = char '|'
603 ns' = filter (/= name) ns
605 upp_export :: [Name] -> SDoc
606 upp_export [] = empty
607 upp_export names = braces (hsep (map (pprOccName . getOccName) names))
609 upp_fixity :: (Name, Fixity) -> SDoc
610 upp_fixity (name, fixity) = hsep [ptext SLIT("0"), ppr fixity, ppr name, semi]
611 -- Dummy version number!
613 ppr_unqual_name :: NamedThing a => a -> SDoc -- Just its occurrence name
614 ppr_unqual_name name = pprOccName (getOccName name)
618 %************************************************************************
620 \subsection{Comparisons}
622 %************************************************************************
625 The various sorts above simply prevent unnecessary "wobbling" when
626 things change that don't have to. We therefore compare lexically, not
630 lt_avail :: AvailInfo -> AvailInfo -> Bool
632 a1 `lt_avail` a2 = availName a1 `lt_name` availName a2
634 lt_name :: Name -> Name -> Bool
635 n1 `lt_name` n2 = nameRdrName n1 < nameRdrName n2
637 lt_lexical :: NamedThing a => a -> a -> Bool
638 lt_lexical a1 a2 = getName a1 `lt_name` getName a2
640 lt_imp_vers :: ImportVersion a -> ImportVersion a -> Bool
641 lt_imp_vers (m1,_,_,_) (m2,_,_,_) = m1 < m2
643 sort_versions vs = sortLt lt_vers vs
645 lt_vers :: LocalVersion Name -> LocalVersion Name -> Bool
646 lt_vers (n1,v1) (n2,v2) = n1 `lt_name` n2
655 hPutCol hdl fmt xs = mapIO (printForIface hdl . fmt) xs
657 mapIO :: (a -> IO b) -> [a] -> IO ()
658 mapIO f [] = return ()
659 mapIO f (x:xs) = f x >> mapIO f xs