2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[MkIface]{Print an interface for a module}
8 mkModDetails, mkModDetailsFromIface, completeIface,
9 writeIface, pprIface, pprUsage
12 #include "HsVersions.h"
15 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
16 import HsTypes ( toHsTyVars )
17 import BasicTypes ( Fixity(..), NewOrData(..),
18 Version, initialVersion, bumpVersion,
21 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
22 import TcHsSyn ( TypecheckedRuleDecl )
23 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
24 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
25 TyThing(..), DFunId, TypeEnv, Avails,
26 WhatsImported(..), GenAvailInfo(..),
27 ImportVersion, AvailInfo, Deprecations(..),
28 extendTypeEnvList, lookupVersion,
32 import Id ( idType, idInfo, isImplicitId, isDictFunId,
33 idSpecialisation, isLocalId, idName, hasNoBinding
37 import DataCon ( StrictnessMark(..), dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
39 import CoreSyn ( CoreBind, CoreRule(..), IdCoreRule,
40 isBuiltinRule, rulesRules,
41 bindersOf, bindersOfBinds
43 import CoreFVs ( ruleSomeLhsFreeVars )
44 import CoreUnfold ( neverUnfold, unfoldingTemplate )
45 import Name ( getName, nameModule, Name, NamedThing(..) )
47 import OccName ( pprOccName )
48 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon, tyConGenIds,
49 tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize, isClassTyCon
51 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
52 import FieldLabel ( fieldLabelType )
53 import Type ( splitSigmaTy, tidyTopType, deNoteType )
54 import SrcLoc ( noSrcLoc )
56 import Module ( ModuleName )
57 import Maybes ( orElse )
59 import IO ( IOMode(..), openFile, hClose )
63 %************************************************************************
65 \subsection{Write a new interface file}
67 %************************************************************************
70 mkModDetails :: TypeEnv -- From typechecker
71 -> [CoreBind] -- Final bindings
72 -- they have authoritative arity info
73 -> [IdCoreRule] -- Tidy orphan rules
75 mkModDetails type_env tidy_binds orphan_rules
76 = ModDetails { md_types = new_type_env,
78 md_insts = filter isDictFunId final_ids }
80 -- The competed type environment is gotten from
81 -- a) keeping the types and classes
82 -- b) removing all Ids,
83 -- c) adding Ids with correct IdInfo, including unfoldings,
84 -- gotten from the bindings
85 -- From (c) we keep only those Ids with Global names;
86 -- the CoreTidy pass makes sure these are all and only
87 -- the externally-accessible ones
88 -- This truncates the type environment to include only the
89 -- exported Ids and things needed from them, which saves space
91 -- However, we do keep things like constructors, which should not appear
92 -- in interface files, because they are needed by importing modules when
93 -- using the compilation manager
94 new_type_env = extendTypeEnvList (filterNameEnv keep_it type_env)
97 -- We keep constructor workers, because they won't appear
98 -- in the bindings from which final_ids are derived!
99 keep_it (AnId id) = hasNoBinding id
102 final_ids = [id | bind <- tidy_binds
103 , id <- bindersOf bind
104 , isGlobalName (idName id)]
106 -- The complete rules are gotten by combining
107 -- a) the orphan rules
108 -- b) rules embedded in the top-level Ids
109 rule_dcls | opt_OmitInterfacePragmas = []
110 | otherwise = getRules orphan_rules tidy_binds (mkVarSet final_ids)
112 -- This version is used when we are re-linking a module
113 -- so we've only run the type checker on its previous interface
114 mkModDetailsFromIface :: TypeEnv
115 -> [TypecheckedRuleDecl]
117 mkModDetailsFromIface type_env rules
118 = ModDetails { md_types = type_env,
119 md_rules = rule_dcls,
120 md_insts = dfun_ids }
122 dfun_ids = [dfun_id | AnId dfun_id <- nameEnvElts type_env, isDictFunId dfun_id]
123 rule_dcls = [(id,rule) | IfaceRuleOut id rule <- rules]
124 -- All the rules from an interface are of the IfaceRuleOut form
128 getRules :: [IdCoreRule] -- Orphan rules
129 -> [CoreBind] -- Bindings, with rules in the top-level Ids
130 -> IdSet -- Ids that are exported, so we need their rules
132 getRules orphan_rules binds emitted
133 = orphan_rules ++ local_rules
135 local_rules = [ (fn, rule)
136 | fn <- bindersOfBinds binds,
137 fn `elemVarSet` emitted,
138 rule <- rulesRules (idSpecialisation fn),
139 not (isBuiltinRule rule),
140 -- We can't print builtin rules in interface files
141 -- Since they are built in, an importing module
142 -- will have access to them anyway
144 -- Sept 00: I've disabled this test. It doesn't stop many, if any, rules
145 -- from coming out, and to make it work properly we need to add ????
146 -- (put it back in for now)
147 all (`elemVarSet` emitted) (varSetElems (ruleSomeLhsFreeVars interestingId rule))
148 -- Spit out a rule only if all its lhs free vars are emitted
149 -- This is a good reason not to do it when we emit the Id itself
152 interestingId id = isId id && isLocalId id
156 %************************************************************************
158 \subsection{Completing an interface}
160 %************************************************************************
163 completeIface :: Maybe ModIface -- The old interface, if we have it
164 -> ModIface -- The new one, minus the decls and versions
165 -> ModDetails -- The ModDetails for this module
166 -> (ModIface, Maybe SDoc) -- The new one, complete with decls and versions
167 -- The SDoc is a debug document giving differences
168 -- Nothing => no change
170 -- NB: 'Nothing' means that even the usages havn't changed, so there's no
171 -- need to write a new interface file. But even if the usages have
172 -- changed, the module version may not have.
173 completeIface maybe_old_iface new_iface mod_details
174 = addVersionInfo maybe_old_iface (new_iface { mi_decls = new_decls })
176 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
177 inst_dcls = map ifaceInstance (md_insts mod_details)
178 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types mod_details)
179 rule_dcls = map ifaceRule (md_rules mod_details)
184 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
185 ifaceTyCls (AClass clas) so_far
188 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
189 tcdName = getName clas,
190 tcdTyVars = toHsTyVars clas_tyvars,
191 tcdFDs = toHsFDs clas_fds,
192 tcdSigs = map toClassOpSig op_stuff,
194 tcdSysNames = sys_names,
197 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
198 tycon = classTyCon clas
199 data_con = head (tyConDataCons tycon)
200 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
201 getName (dataConId data_con), map getName sc_sels)
203 toClassOpSig (sel_id, def_meth)
204 = ASSERT(sel_tyvars == clas_tyvars)
205 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
207 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
208 def_meth' = case def_meth of
209 NoDefMeth -> NoDefMeth
210 GenDefMeth -> GenDefMeth
211 DefMeth id -> DefMeth (getName id)
213 ifaceTyCls (ATyCon tycon) so_far
214 | isClassTyCon tycon = so_far
215 | otherwise = ty_decl : so_far
217 ty_decl | isSynTyCon tycon
218 = TySynonym { tcdName = getName tycon,
219 tcdTyVars = toHsTyVars tyvars,
220 tcdSynRhs = toHsType syn_ty,
224 = TyData { tcdND = new_or_data,
225 tcdCtxt = toHsContext (tyConTheta tycon),
226 tcdName = getName tycon,
227 tcdTyVars = toHsTyVars tyvars,
228 tcdCons = map ifaceConDecl (tyConDataCons tycon),
229 tcdNCons = tyConFamilySize tycon,
231 tcdSysNames = map getName (tyConGenIds tycon),
234 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
236 tyvars = tyConTyVars tycon
237 (_, syn_ty) = getSynTyConDefn tycon
238 new_or_data | isNewTyCon tycon = NewType
239 | otherwise = DataType
241 ifaceConDecl data_con
242 = ConDecl (getName data_con) (getName (dataConId data_con))
243 (toHsTyVars ex_tyvars)
244 (toHsContext ex_theta)
247 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
248 field_labels = dataConFieldLabels data_con
249 strict_marks = dataConStrictMarks data_con
250 details | null field_labels
251 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
252 VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
255 = RecCon (zipWith mk_field strict_marks field_labels)
257 mk_bang_ty NotMarkedStrict ty = Unbanged (toHsType ty)
258 mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
259 mk_bang_ty MarkedStrict ty = Banged (toHsType ty)
261 mk_field strict_mark field_label
262 = ([getName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
264 ifaceTyCls (AnId id) so_far
265 | isImplicitId id = so_far
266 | otherwise = iface_sig : so_far
268 iface_sig = IfaceSig { tcdName = getName id,
269 tcdType = toHsType id_type,
270 tcdIdInfo = hs_idinfo,
276 hs_idinfo | opt_OmitInterfacePragmas = []
277 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
278 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
280 ------------ Arity --------------
281 arity_hsinfo = case arityInfo id_info of
282 a@(ArityExactly n) -> [HsArity a]
285 ------------ Caf Info --------------
286 caf_hsinfo = case cafInfo id_info of
287 NoCafRefs -> [HsNoCafRefs]
290 ------------ CPR Info --------------
291 cpr_hsinfo = case cprInfo id_info of
292 ReturnsCPR -> [HsCprInfo]
295 ------------ Strictness --------------
296 strict_hsinfo = case strictnessInfo id_info of
297 NoStrictnessInfo -> []
298 info -> [HsStrictness info]
300 ------------ Worker --------------
301 work_info = workerInfo id_info
302 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
303 wrkr_hsinfo = case work_info of
304 HasWorker work_id wrap_arity -> [HsWorker (getName work_id)]
307 ------------ Unfolding --------------
308 -- The unfolding is redundant if there is a worker
309 unfold_info = unfoldingInfo id_info
310 inline_prag = inlinePragInfo id_info
311 rhs = unfoldingTemplate unfold_info
312 unfold_hsinfo | neverUnfold unfold_info
314 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
318 ifaceInstance :: DFunId -> RenamedInstDecl
319 ifaceInstance dfun_id
320 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
322 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
323 -- The deNoteType is very important. It removes all type
324 -- synonyms from the instance type in interface files.
325 -- That in turn makes sure that when reading in instance decls
326 -- from interface files that the 'gating' mechanism works properly.
327 -- Otherwise you could have
328 -- type Tibble = T Int
329 -- instance Foo Tibble where ...
330 -- and this instance decl wouldn't get imported into a module
331 -- that mentioned T but not Tibble.
333 ifaceRule (id, BuiltinRule _)
334 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
336 ifaceRule (id, Rule name bndrs args rhs)
337 = IfaceRule name (map toUfBndr bndrs) (getName id)
338 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
341 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
345 %************************************************************************
347 \subsection{Checking if the new interface is up to date
349 %************************************************************************
352 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
353 -> ModIface -- The new interface decls
354 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
355 -- Just mi => Here is the new interface to write
356 -- with correct version numbers
358 -- NB: the fixities, declarations, rules are all assumed
359 -- to be sorted by increasing order of hsDeclName, so that
360 -- we can compare for equality
362 addVersionInfo Nothing new_iface
363 -- No old interface, so definitely write a new one!
364 = (new_iface, Just (text "No old interface available"))
366 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
367 mi_decls = old_decls,
368 mi_fixities = old_fixities,
369 mi_deprecs = old_deprecs }))
370 new_iface@(ModIface { mi_decls = new_decls,
371 mi_fixities = new_fixities,
372 mi_deprecs = new_deprecs })
374 | no_output_change && no_usage_change
375 = (new_iface, Nothing)
376 -- don't return the old iface because it may not have an
377 -- mi_globals field set to anything reasonable.
379 | otherwise -- Add updated version numbers
380 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
381 (final_iface, Just pp_diffs)
384 final_iface = new_iface { mi_version = new_version }
385 old_mod_vers = vers_module old_version
386 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
387 vers_exports = bumpVersion no_export_change (vers_exports old_version),
388 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
389 vers_decls = tc_vers }
391 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
392 no_usage_change = mi_usages old_iface == mi_usages new_iface
394 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
395 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
396 no_deprec_change = old_deprecs == new_deprecs
398 -- Fill in the version number on the new declarations by looking at the old declarations.
399 -- Set the flag if anything changes.
400 -- Assumes that the decls are sorted by hsDeclName.
401 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
402 (dcl_tycl old_decls) (dcl_tycl new_decls)
403 pp_diffs = vcat [pp_tc_diffs,
404 pp_change no_export_change "Export list",
405 pp_change no_rule_change "Rules",
406 pp_change no_deprec_change "Deprecations",
407 pp_change no_usage_change "Usages"]
408 pp_change True what = empty
409 pp_change False what = text what <+> ptext SLIT("changed")
411 diffDecls :: VersionInfo -- Old version
412 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
413 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
414 -> (Bool, -- True <=> no change
415 SDoc, -- Record of differences
416 NameEnv Version) -- New version map
418 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
419 old_fixities new_fixities old new
420 = diff True empty emptyNameEnv old new
422 -- When seeing if two decls are the same,
423 -- remember to check whether any relevant fixity has changed
424 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
425 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
427 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
428 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
429 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
431 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
432 -- When adding a new item, start from the old module version
433 -- This way, if you have version 4 of f, then delete f, then add f again,
434 -- you'll get version 6 of f, which will (correctly) force recompilation of
437 diff ok_so_far pp new_vers (od:ods) (nd:nds)
438 = case od_name `compare` nd_name of
439 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
440 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
441 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
442 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
444 od_name = tyClDeclName od
445 nd_name = tyClDeclName nd
446 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
447 old_version = lookupVersion old_decls_vers od_name
449 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
450 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
451 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
452 (ptext SLIT("New:") <+> ppr nd))
457 %************************************************************************
459 \subsection{Writing an interface file}
461 %************************************************************************
464 writeIface :: FilePath -> ModIface -> IO ()
465 writeIface hi_path mod_iface
466 = do { if_hdl <- openFile hi_path WriteMode
467 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
471 -- Print names unqualified if they are from this module
472 from_this_mod n = nameModule n == this_mod
473 this_mod = mi_module mod_iface
475 pprIface :: ModIface -> SDoc
477 = vcat [ ptext SLIT("__interface")
478 <+> doubleQuotes (ptext opt_InPackage)
479 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
481 <+> (if mi_orphan iface then char '!' else empty)
482 <+> int opt_HiVersion
483 <+> ptext SLIT("where")
485 , vcat (map pprExport (mi_exports iface))
486 , vcat (map pprUsage (mi_usages iface))
488 , pprFixities (mi_fixities iface) (dcl_tycl decls)
489 , pprIfaceDecls (vers_decls version_info) decls
490 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
493 version_info = mi_version iface
494 decls = mi_decls iface
495 exp_vers = vers_exports version_info
496 rule_vers = vers_rules version_info
498 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
499 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
502 When printing export lists, we print like this:
504 AvailTC C [C, x, y] C(x,y)
505 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
508 pprExport :: (ModuleName, Avails) -> SDoc
509 pprExport (mod, items)
510 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
512 pp_avail :: AvailInfo -> SDoc
513 pp_avail (Avail name) = pprOcc name
514 pp_avail (AvailTC n []) = empty
515 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
516 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
519 pp_export names = braces (hsep (map pprOcc names))
521 pprOcc :: Name -> SDoc -- Print the occurrence name only
522 pprOcc n = pprOccName (nameOccName n)
527 pprUsage :: ImportVersion Name -> SDoc
528 pprUsage (m, has_orphans, is_boot, whats_imported)
529 = hsep [ptext SLIT("import"), ppr m,
531 pp_versions whats_imported
534 pp_orphan | has_orphans = char '!'
536 pp_boot | is_boot = char '@'
539 -- Importing the whole module is indicated by an empty list
540 pp_versions NothingAtAll = empty
541 pp_versions (Everything v) = dcolon <+> int v
542 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
543 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
545 pp_export_version Nothing = empty
546 pp_export_version (Just v) = int v
550 pprIfaceDecls version_map decls
551 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
552 , vcat (map ppr_decl (dcl_tycl decls))
555 ppr_decl d = ppr_vers d <+> ppr d <> semi
557 -- Print the version for the decl
558 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
564 pprFixities fixity_map decls
565 = hsep [ ppr fix <+> ppr n
567 (n,_) <- tyClDeclNames d,
568 Just fix <- [lookupNameEnv fixity_map n]] <> semi
570 -- Disgusting to print these two together, but that's
571 -- the way the interface parser currently expects them.
572 pprRulesAndDeprecs [] NoDeprecs = empty
573 pprRulesAndDeprecs rules deprecs
574 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
577 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
579 pp_deprecs NoDeprecs = empty
580 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
582 guts = case deprecs of
583 DeprecAll txt -> doubleQuotes (ptext txt)
584 DeprecSome env -> ppr_deprec_env env
586 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
588 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)