2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section[MkIface]{Print an interface for a module}
9 pprModDetails, 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 HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
24 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
25 TyThing(..), DFunId, Avails,
26 WhatsImported(..), GenAvailInfo(..),
27 ImportVersion, AvailInfo, Deprecations(..),
30 import CmStaticInfo ( GhciMode(..) )
33 import Id ( idType, idInfo, isImplicitId, idCgInfo,
36 import DataCon ( StrictnessMark(..), dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
38 import CoreSyn ( CoreRule(..) )
39 import CoreFVs ( ruleLhsFreeNames )
40 import CoreUnfold ( neverUnfold, unfoldingTemplate )
41 import PprCore ( pprIdCoreRule )
42 import Name ( getName, nameModule, toRdrName, isGlobalName,
43 nameIsLocalOrFrom, Name, NamedThing(..) )
46 import OccName ( pprOccName )
47 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon, isAlgTyCon, tyConGenIds,
48 tyConTheta, tyConTyVars, tyConDataCons, tyConFamilySize, isClassTyCon
50 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
51 import FieldLabel ( fieldLabelType )
52 import Type ( splitSigmaTy, tidyTopType, deNoteType, namesOfType )
53 import SrcLoc ( noSrcLoc )
55 import Module ( ModuleName )
56 import Util ( sortLt, unJust )
57 import ErrUtils ( dumpIfSet_dyn )
60 import IO ( IOMode(..), openFile, hClose )
64 %************************************************************************
66 \subsection{Completing an interface}
68 %************************************************************************
74 mkFinalIface :: GhciMode
77 -> Maybe ModIface -- The old interface, if we have it
78 -> ModIface -- The new one, minus the decls and versions
79 -> ModDetails -- The ModDetails for this module
80 -> IO ModIface -- The new one, complete with decls and versions
82 -- a) completes the interface
83 -- b) writes it out to a file if necessary
85 mkFinalIface ghci_mode dflags location
86 maybe_old_iface new_iface new_details
88 -- Add the new declarations, and the is-orphan flag
89 let iface_w_decls = new_iface { mi_decls = new_decls,
90 mi_orphan = orphan_mod }
92 -- Add version information
93 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
95 -- Write the interface file, if necessary
96 ; when (must_write_hi_file maybe_diffs)
97 (writeIface hi_file_path final_iface)
100 ; write_diffs dflags final_iface maybe_diffs
102 ; return final_iface }
105 must_write_hi_file Nothing = False
106 must_write_hi_file (Just diffs) = ghci_mode /= Interactive
107 -- We must write a new .hi file if there are some changes
108 -- and we're not in interactive mode
109 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
110 -- so there's no need to write a new interface file. But even if
111 -- the usages have changed, the module version may not have.
113 hi_file_path = unJust "mkFinalIface" (ml_hi_file location)
114 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
115 inst_dcls = map ifaceInstance (md_insts new_details)
116 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types new_details)
117 rule_dcls = map ifaceRule (md_rules new_details)
118 orphan_mod = isOrphanModule (mi_module new_iface) new_details
120 write_diffs dflags new_iface Nothing
121 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
122 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
124 write_diffs dflags new_iface (Just sdoc_diffs)
125 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
126 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
130 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
131 = any orphan_inst insts || any orphan_rule rules
133 orphan_inst dfun_id = no_locals (namesOfType (dfun_head_type dfun_id))
134 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
135 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
136 dfun_head_type dfun = case splitSigmaTy (idType dfun) of
137 (_,_,head_ty) -> head_ty
138 -- The 'dfun_head_type' is because of
139 -- instance Foo a => Baz T where ...
140 -- The decl is an orphan if Baz and T are both not locally defined,
141 -- even if Foo *is* locally defined
145 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
146 ifaceTyCls (AClass clas) so_far
149 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
150 tcdName = getName clas,
151 tcdTyVars = toHsTyVars clas_tyvars,
152 tcdFDs = toHsFDs clas_fds,
153 tcdSigs = map toClassOpSig op_stuff,
155 tcdSysNames = sys_names,
158 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
159 tycon = classTyCon clas
160 data_con = head (tyConDataCons tycon)
161 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
162 getName (dataConId data_con), map getName sc_sels)
164 toClassOpSig (sel_id, def_meth)
165 = ASSERT(sel_tyvars == clas_tyvars)
166 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
168 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
169 def_meth' = case def_meth of
170 NoDefMeth -> NoDefMeth
171 GenDefMeth -> GenDefMeth
172 DefMeth id -> DefMeth (getName id)
174 ifaceTyCls (ATyCon tycon) so_far
175 | isClassTyCon tycon = so_far
176 | otherwise = ty_decl : so_far
178 ty_decl | isSynTyCon tycon
179 = TySynonym { tcdName = getName tycon,
180 tcdTyVars = toHsTyVars tyvars,
181 tcdSynRhs = toHsType syn_ty,
185 = TyData { tcdND = new_or_data,
186 tcdCtxt = toHsContext (tyConTheta tycon),
187 tcdName = getName tycon,
188 tcdTyVars = toHsTyVars tyvars,
189 tcdCons = map ifaceConDecl (tyConDataCons tycon),
190 tcdNCons = tyConFamilySize tycon,
192 tcdSysNames = map getName (tyConGenIds tycon),
195 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
197 tyvars = tyConTyVars tycon
198 (_, syn_ty) = getSynTyConDefn tycon
199 new_or_data | isNewTyCon tycon = NewType
200 | otherwise = DataType
202 ifaceConDecl data_con
203 = ConDecl (getName data_con) (getName (dataConId data_con))
204 (toHsTyVars ex_tyvars)
205 (toHsContext ex_theta)
208 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
209 field_labels = dataConFieldLabels data_con
210 strict_marks = dataConStrictMarks data_con
211 details | null field_labels
212 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
213 VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
216 = RecCon (zipWith mk_field strict_marks field_labels)
218 mk_bang_ty NotMarkedStrict ty = Unbanged (toHsType ty)
219 mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
220 mk_bang_ty MarkedStrict ty = Banged (toHsType ty)
222 mk_field strict_mark field_label
223 = ([getName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
225 ifaceTyCls (AnId id) so_far
226 | isImplicitId id = so_far
227 | otherwise = iface_sig : so_far
229 iface_sig = IfaceSig { tcdName = getName id,
230 tcdType = toHsType id_type,
231 tcdIdInfo = hs_idinfo,
236 cg_info = idCgInfo id
237 arity_info = cgArity cg_info
238 caf_info = cgCafInfo cg_info
240 hs_idinfo | opt_OmitInterfacePragmas = []
241 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
242 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
244 ------------ Arity --------------
245 arity_hsinfo | arity_info == 0 = []
246 | otherwise = [HsArity arity_info]
248 ------------ Caf Info --------------
249 caf_hsinfo = case caf_info of
250 NoCafRefs -> [HsNoCafRefs]
253 ------------ CPR Info --------------
254 cpr_hsinfo = case cprInfo id_info of
255 ReturnsCPR -> [HsCprInfo]
258 ------------ Strictness --------------
259 strict_hsinfo = case strictnessInfo id_info of
260 NoStrictnessInfo -> []
261 info -> [HsStrictness info]
263 ------------ Worker --------------
264 work_info = workerInfo id_info
265 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
266 wrkr_hsinfo = case work_info of
267 HasWorker work_id wrap_arity ->
268 [HsWorker (getName work_id) wrap_arity]
271 ------------ Unfolding --------------
272 -- The unfolding is redundant if there is a worker
273 unfold_info = unfoldingInfo id_info
274 inline_prag = inlinePragInfo id_info
275 rhs = unfoldingTemplate unfold_info
276 unfold_hsinfo | neverUnfold unfold_info
278 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
282 ifaceInstance :: DFunId -> RenamedInstDecl
283 ifaceInstance dfun_id
284 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
286 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
287 -- The deNoteType is very important. It removes all type
288 -- synonyms from the instance type in interface files.
289 -- That in turn makes sure that when reading in instance decls
290 -- from interface files that the 'gating' mechanism works properly.
291 -- Otherwise you could have
292 -- type Tibble = T Int
293 -- instance Foo Tibble where ...
294 -- and this instance decl wouldn't get imported into a module
295 -- that mentioned T but not Tibble.
297 ifaceRule (id, BuiltinRule _)
298 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
300 ifaceRule (id, Rule name bndrs args rhs)
301 = IfaceRule name (map toUfBndr bndrs) (getName id)
302 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
305 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
309 %************************************************************************
311 \subsection{Checking if the new interface is up to date
313 %************************************************************************
316 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
317 -> ModIface -- The new interface decls
318 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
319 -- Just mi => Here is the new interface to write
320 -- with correct version numbers
322 -- NB: the fixities, declarations, rules are all assumed
323 -- to be sorted by increasing order of hsDeclName, so that
324 -- we can compare for equality
326 addVersionInfo Nothing new_iface
327 -- No old interface, so definitely write a new one!
328 = (new_iface, Just (text "No old interface available"))
330 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
331 mi_decls = old_decls,
332 mi_fixities = old_fixities,
333 mi_deprecs = old_deprecs }))
334 new_iface@(ModIface { mi_decls = new_decls,
335 mi_fixities = new_fixities,
336 mi_deprecs = new_deprecs })
338 | no_output_change && no_usage_change
339 = (new_iface, Nothing)
340 -- don't return the old iface because it may not have an
341 -- mi_globals field set to anything reasonable.
343 | otherwise -- Add updated version numbers
344 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
345 (final_iface, Just pp_diffs)
348 final_iface = new_iface { mi_version = new_version }
349 old_mod_vers = vers_module old_version
350 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
351 vers_exports = bumpVersion no_export_change (vers_exports old_version),
352 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
353 vers_decls = tc_vers }
355 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
356 no_usage_change = mi_usages old_iface == mi_usages new_iface
358 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
359 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
360 no_deprec_change = old_deprecs == new_deprecs
362 -- Fill in the version number on the new declarations by looking at the old declarations.
363 -- Set the flag if anything changes.
364 -- Assumes that the decls are sorted by hsDeclName.
365 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
366 (dcl_tycl old_decls) (dcl_tycl new_decls)
367 pp_diffs = vcat [pp_tc_diffs,
368 pp_change no_export_change "Export list",
369 pp_change no_rule_change "Rules",
370 pp_change no_deprec_change "Deprecations",
371 pp_change no_usage_change "Usages"]
372 pp_change True what = empty
373 pp_change False what = text what <+> ptext SLIT("changed")
375 diffDecls :: VersionInfo -- Old version
376 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
377 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
378 -> (Bool, -- True <=> no change
379 SDoc, -- Record of differences
380 NameEnv Version) -- New version map
382 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
383 old_fixities new_fixities old new
384 = diff True empty emptyNameEnv old new
386 -- When seeing if two decls are the same,
387 -- remember to check whether any relevant fixity has changed
388 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
389 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
391 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
392 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
393 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
395 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
396 -- When adding a new item, start from the old module version
397 -- This way, if you have version 4 of f, then delete f, then add f again,
398 -- you'll get version 6 of f, which will (correctly) force recompilation of
401 diff ok_so_far pp new_vers (od:ods) (nd:nds)
402 = case od_name `compare` nd_name of
403 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
404 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
405 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
406 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
408 od_name = tyClDeclName od
409 nd_name = tyClDeclName nd
410 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
411 old_version = lookupVersion old_decls_vers od_name
413 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
414 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
415 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
416 (ptext SLIT("New:") <+> ppr nd))
421 %************************************************************************
423 \subsection{Writing ModDetails}
425 %************************************************************************
428 pprModDetails :: ModDetails -> SDoc
429 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
430 = vcat [ dump_types dfun_ids type_env
431 , dump_insts dfun_ids
434 dump_types dfun_ids type_env
435 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
437 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
438 want_sig id | opt_PprStyle_Debug = True
439 | otherwise = isLocalId id &&
440 isGlobalName (idName id) &&
441 not (id `elem` dfun_ids)
442 -- isLocalId ignores data constructors, records selectors etc
443 -- The isGlobalName ignores local dictionary and method bindings
444 -- that the type checker has invented. User-defined things have
447 dump_insts [] = empty
448 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
451 -- Print type signatures
452 -- Convert to HsType so that we get source-language style printing
453 -- And sort by RdrName
454 = vcat $ map ppr_sig $ sortLt lt_sig $
455 [ (toRdrName id, toHsType (idType id))
458 lt_sig (n1,_) (n2,_) = n1 < n2
459 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
461 dump_rules [] = empty
462 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
463 nest 4 (vcat (map pprIdCoreRule rs)),
468 %************************************************************************
470 \subsection{Writing an interface file}
472 %************************************************************************
475 writeIface :: FilePath -> ModIface -> IO ()
476 writeIface hi_path mod_iface
477 = do { if_hdl <- openFile hi_path WriteMode
478 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
482 -- Print names unqualified if they are from this module
483 from_this_mod n = nameModule n == this_mod
484 this_mod = mi_module mod_iface
486 pprIface :: ModIface -> SDoc
488 = vcat [ ptext SLIT("__interface")
489 <+> doubleQuotes (ptext opt_InPackage)
490 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
492 <+> (if mi_orphan iface then char '!' else empty)
493 <+> int opt_HiVersion
494 <+> ptext SLIT("where")
496 , vcat (map pprExport (mi_exports iface))
497 , vcat (map pprUsage (mi_usages iface))
499 , pprFixities (mi_fixities iface) (dcl_tycl decls)
500 , pprIfaceDecls (vers_decls version_info) decls
501 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
504 version_info = mi_version iface
505 decls = mi_decls iface
506 exp_vers = vers_exports version_info
507 rule_vers = vers_rules version_info
509 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
510 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
513 When printing export lists, we print like this:
515 AvailTC C [C, x, y] C(x,y)
516 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
519 pprExport :: (ModuleName, Avails) -> SDoc
520 pprExport (mod, items)
521 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
523 pp_avail :: AvailInfo -> SDoc
524 pp_avail (Avail name) = pprOcc name
525 pp_avail (AvailTC n []) = empty
526 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
527 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
530 pp_export names = braces (hsep (map pprOcc names))
532 pprOcc :: Name -> SDoc -- Print the occurrence name only
533 pprOcc n = pprOccName (nameOccName n)
538 pprUsage :: ImportVersion Name -> SDoc
539 pprUsage (m, has_orphans, is_boot, whats_imported)
540 = hsep [ptext SLIT("import"), ppr m,
542 pp_versions whats_imported
545 pp_orphan | has_orphans = char '!'
547 pp_boot | is_boot = char '@'
550 -- Importing the whole module is indicated by an empty list
551 pp_versions NothingAtAll = empty
552 pp_versions (Everything v) = dcolon <+> int v
553 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
554 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
556 pp_export_version Nothing = empty
557 pp_export_version (Just v) = int v
561 pprIfaceDecls version_map decls
562 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
563 , vcat (map ppr_decl (dcl_tycl decls))
566 ppr_decl d = ppr_vers d <+> ppr d <> semi
568 -- Print the version for the decl
569 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
575 pprFixities fixity_map decls
576 = hsep [ ppr fix <+> ppr n
578 (n,_) <- tyClDeclNames d,
579 Just fix <- [lookupNameEnv fixity_map n]] <> semi
581 -- Disgusting to print these two together, but that's
582 -- the way the interface parser currently expects them.
583 pprRulesAndDeprecs [] NoDeprecs = empty
584 pprRulesAndDeprecs rules deprecs
585 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
588 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
590 pp_deprecs NoDeprecs = empty
591 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
593 guts = case deprecs of
594 DeprecAll txt -> doubleQuotes (ptext txt)
595 DeprecSome env -> ppr_deprec_env env
597 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
599 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)