2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 \section[MkIface]{Print an interface for a module}
10 pprModDetails, pprIface, pprUsage
13 #include "HsVersions.h"
16 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
17 import HsTypes ( toHsTyVars )
18 import BasicTypes ( Fixity(..), NewOrData(..),
19 Version, initialVersion, bumpVersion,
22 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
23 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
25 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
26 TyThing(..), DFunId, Avails,
27 WhatsImported(..), GenAvailInfo(..),
28 ImportVersion, AvailInfo, Deprecations(..),
31 import CmStaticInfo ( GhciMode(..) )
34 import Id ( idType, idInfo, isImplicitId, idCgInfo,
37 import DataCon ( StrictnessMark(..), dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
39 import CoreSyn ( CoreRule(..) )
40 import CoreFVs ( ruleLhsFreeNames )
41 import CoreUnfold ( neverUnfold, unfoldingTemplate )
42 import PprCore ( pprIdCoreRule )
43 import Name ( getName, nameModule, toRdrName, isGlobalName,
44 nameIsLocalOrFrom, 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, namesOfDFunHead )
54 import SrcLoc ( noSrcLoc )
56 import Module ( ModuleName )
57 import Util ( sortLt, unJust )
58 import ErrUtils ( dumpIfSet_dyn )
61 import IO ( IOMode(..), openFile, hClose )
65 %************************************************************************
67 \subsection{Completing an interface}
69 %************************************************************************
75 mkFinalIface :: GhciMode
78 -> Maybe ModIface -- The old interface, if we have it
79 -> ModIface -- The new one, minus the decls and versions
80 -> ModDetails -- The ModDetails for this module
81 -> IO ModIface -- The new one, complete with decls and versions
83 -- a) completes the interface
84 -- b) writes it out to a file if necessary
86 mkFinalIface ghci_mode dflags location
87 maybe_old_iface new_iface new_details
89 -- Add the new declarations, and the is-orphan flag
90 let iface_w_decls = new_iface { mi_decls = new_decls,
91 mi_orphan = orphan_mod }
93 -- Add version information
94 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
96 -- Write the interface file, if necessary
97 ; when (must_write_hi_file maybe_diffs)
98 (writeIface hi_file_path final_iface)
101 ; write_diffs dflags final_iface maybe_diffs
103 ; return final_iface }
106 must_write_hi_file Nothing = False
107 must_write_hi_file (Just diffs) = ghci_mode /= Interactive
108 -- We must write a new .hi file if there are some changes
109 -- and we're not in interactive mode
110 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
111 -- so there's no need to write a new interface file. But even if
112 -- the usages have changed, the module version may not have.
114 hi_file_path = unJust "mkFinalIface" (ml_hi_file location)
115 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
116 inst_dcls = map ifaceInstance (md_insts new_details)
117 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types new_details)
118 rule_dcls = map ifaceRule (md_rules new_details)
119 orphan_mod = isOrphanModule (mi_module new_iface) new_details
121 write_diffs dflags new_iface Nothing
122 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
123 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
125 write_diffs dflags new_iface (Just sdoc_diffs)
126 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
127 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
131 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
132 = any orphan_inst insts || any orphan_rule rules
134 orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
135 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
136 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
140 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
141 ifaceTyCls (AClass clas) so_far
144 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
145 tcdName = getName clas,
146 tcdTyVars = toHsTyVars clas_tyvars,
147 tcdFDs = toHsFDs clas_fds,
148 tcdSigs = map toClassOpSig op_stuff,
150 tcdSysNames = sys_names,
153 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
154 tycon = classTyCon clas
155 data_con = head (tyConDataCons tycon)
156 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
157 getName (dataConId data_con), map getName sc_sels)
159 toClassOpSig (sel_id, def_meth)
160 = ASSERT(sel_tyvars == clas_tyvars)
161 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
163 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
164 def_meth' = case def_meth of
165 NoDefMeth -> NoDefMeth
166 GenDefMeth -> GenDefMeth
167 DefMeth id -> DefMeth (getName id)
169 ifaceTyCls (ATyCon tycon) so_far
170 | isClassTyCon tycon = so_far
171 | otherwise = ty_decl : so_far
173 ty_decl | isSynTyCon tycon
174 = TySynonym { tcdName = getName tycon,
175 tcdTyVars = toHsTyVars tyvars,
176 tcdSynRhs = toHsType syn_ty,
180 = TyData { tcdND = new_or_data,
181 tcdCtxt = toHsContext (tyConTheta tycon),
182 tcdName = getName tycon,
183 tcdTyVars = toHsTyVars tyvars,
184 tcdCons = map ifaceConDecl (tyConDataCons tycon),
185 tcdNCons = tyConFamilySize tycon,
187 tcdSysNames = map getName (tyConGenIds tycon),
190 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
192 tyvars = tyConTyVars tycon
193 (_, syn_ty) = getSynTyConDefn tycon
194 new_or_data | isNewTyCon tycon = NewType
195 | otherwise = DataType
197 ifaceConDecl data_con
198 = ConDecl (getName data_con) (getName (dataConId data_con))
199 (toHsTyVars ex_tyvars)
200 (toHsContext ex_theta)
203 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
204 field_labels = dataConFieldLabels data_con
205 strict_marks = dataConStrictMarks data_con
206 details | null field_labels
207 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
208 VanillaCon (zipWith mk_bang_ty strict_marks arg_tys)
211 = RecCon (zipWith mk_field strict_marks field_labels)
213 mk_bang_ty NotMarkedStrict ty = Unbanged (toHsType ty)
214 mk_bang_ty (MarkedUnboxed _ _) ty = Unpacked (toHsType ty)
215 mk_bang_ty MarkedStrict ty = Banged (toHsType ty)
217 mk_field strict_mark field_label
218 = ([getName field_label], mk_bang_ty strict_mark (fieldLabelType field_label))
220 ifaceTyCls (AnId id) so_far
221 | isImplicitId id = so_far
222 | otherwise = iface_sig : so_far
224 iface_sig = IfaceSig { tcdName = getName id,
225 tcdType = toHsType id_type,
226 tcdIdInfo = hs_idinfo,
231 cg_info = idCgInfo id
232 arity_info = cgArity cg_info
233 caf_info = cgCafInfo cg_info
235 hs_idinfo | opt_OmitInterfacePragmas = []
236 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
237 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
239 ------------ Arity --------------
240 arity_hsinfo | arity_info == 0 = []
241 | otherwise = [HsArity arity_info]
243 ------------ Caf Info --------------
244 caf_hsinfo = case caf_info of
245 NoCafRefs -> [HsNoCafRefs]
248 ------------ CPR Info --------------
249 cpr_hsinfo = case cprInfo id_info of
250 ReturnsCPR -> [HsCprInfo]
253 ------------ Strictness --------------
254 strict_hsinfo = case strictnessInfo id_info of
255 NoStrictnessInfo -> []
256 info -> [HsStrictness info]
258 ------------ Worker --------------
259 work_info = workerInfo id_info
260 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
261 wrkr_hsinfo = case work_info of
262 HasWorker work_id wrap_arity ->
263 [HsWorker (getName work_id) wrap_arity]
266 ------------ Unfolding --------------
267 -- The unfolding is redundant if there is a worker
268 unfold_info = unfoldingInfo id_info
269 inline_prag = inlinePragInfo id_info
270 rhs = unfoldingTemplate unfold_info
271 unfold_hsinfo | neverUnfold unfold_info
273 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
277 ifaceInstance :: DFunId -> RenamedInstDecl
278 ifaceInstance dfun_id
279 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
281 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
282 -- The deNoteType is very important. It removes all type
283 -- synonyms from the instance type in interface files.
284 -- That in turn makes sure that when reading in instance decls
285 -- from interface files that the 'gating' mechanism works properly.
286 -- Otherwise you could have
287 -- type Tibble = T Int
288 -- instance Foo Tibble where ...
289 -- and this instance decl wouldn't get imported into a module
290 -- that mentioned T but not Tibble.
292 ifaceRule (id, BuiltinRule _)
293 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
295 ifaceRule (id, Rule name bndrs args rhs)
296 = IfaceRule name (map toUfBndr bndrs) (getName id)
297 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
300 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
304 %************************************************************************
306 \subsection{Checking if the new interface is up to date
308 %************************************************************************
311 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
312 -> ModIface -- The new interface decls
313 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
314 -- Just mi => Here is the new interface to write
315 -- with correct version numbers
317 -- NB: the fixities, declarations, rules are all assumed
318 -- to be sorted by increasing order of hsDeclName, so that
319 -- we can compare for equality
321 addVersionInfo Nothing new_iface
322 -- No old interface, so definitely write a new one!
323 = (new_iface, Just (text "No old interface available"))
325 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
326 mi_decls = old_decls,
327 mi_fixities = old_fixities,
328 mi_deprecs = old_deprecs }))
329 new_iface@(ModIface { mi_decls = new_decls,
330 mi_fixities = new_fixities,
331 mi_deprecs = new_deprecs })
333 | no_output_change && no_usage_change
334 = (new_iface, Nothing)
335 -- don't return the old iface because it may not have an
336 -- mi_globals field set to anything reasonable.
338 | otherwise -- Add updated version numbers
339 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
340 (final_iface, Just pp_diffs)
343 final_iface = new_iface { mi_version = new_version }
344 old_mod_vers = vers_module old_version
345 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
346 vers_exports = bumpVersion no_export_change (vers_exports old_version),
347 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
348 vers_decls = tc_vers }
350 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
351 no_usage_change = mi_usages old_iface == mi_usages new_iface
353 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
354 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
355 no_deprec_change = old_deprecs == new_deprecs
357 -- Fill in the version number on the new declarations by looking at the old declarations.
358 -- Set the flag if anything changes.
359 -- Assumes that the decls are sorted by hsDeclName.
360 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
361 (dcl_tycl old_decls) (dcl_tycl new_decls)
362 pp_diffs = vcat [pp_tc_diffs,
363 pp_change no_export_change "Export list",
364 pp_change no_rule_change "Rules",
365 pp_change no_deprec_change "Deprecations",
366 pp_change no_usage_change "Usages"]
367 pp_change True what = empty
368 pp_change False what = text what <+> ptext SLIT("changed")
370 diffDecls :: VersionInfo -- Old version
371 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
372 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
373 -> (Bool, -- True <=> no change
374 SDoc, -- Record of differences
375 NameEnv Version) -- New version map
377 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
378 old_fixities new_fixities old new
379 = diff True empty emptyNameEnv old new
381 -- When seeing if two decls are the same,
382 -- remember to check whether any relevant fixity has changed
383 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
384 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
386 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
387 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
388 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
390 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
391 -- When adding a new item, start from the old module version
392 -- This way, if you have version 4 of f, then delete f, then add f again,
393 -- you'll get version 6 of f, which will (correctly) force recompilation of
396 diff ok_so_far pp new_vers (od:ods) (nd:nds)
397 = case od_name `compare` nd_name of
398 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
399 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
400 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
401 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
403 od_name = tyClDeclName od
404 nd_name = tyClDeclName nd
405 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
406 old_version = lookupVersion old_decls_vers od_name
408 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
409 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
410 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
411 (ptext SLIT("New:") <+> ppr nd))
416 %************************************************************************
418 \subsection{Writing ModDetails}
420 %************************************************************************
423 pprModDetails :: ModDetails -> SDoc
424 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
425 = vcat [ dump_types dfun_ids type_env
426 , dump_insts dfun_ids
429 dump_types dfun_ids type_env
430 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
432 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
433 want_sig id | opt_PprStyle_Debug = True
434 | otherwise = isLocalId id &&
435 isGlobalName (idName id) &&
436 not (id `elem` dfun_ids)
437 -- isLocalId ignores data constructors, records selectors etc
438 -- The isGlobalName ignores local dictionary and method bindings
439 -- that the type checker has invented. User-defined things have
442 dump_insts [] = empty
443 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
446 -- Print type signatures
447 -- Convert to HsType so that we get source-language style printing
448 -- And sort by RdrName
449 = vcat $ map ppr_sig $ sortLt lt_sig $
450 [ (toRdrName id, toHsType (idType id))
453 lt_sig (n1,_) (n2,_) = n1 < n2
454 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
456 dump_rules [] = empty
457 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
458 nest 4 (vcat (map pprIdCoreRule rs)),
463 %************************************************************************
465 \subsection{Writing an interface file}
467 %************************************************************************
470 writeIface :: FilePath -> ModIface -> IO ()
471 writeIface hi_path mod_iface
472 = do { if_hdl <- openFile hi_path WriteMode
473 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
477 -- Print names unqualified if they are from this module
478 from_this_mod n = nameModule n == this_mod
479 this_mod = mi_module mod_iface
481 pprIface :: ModIface -> SDoc
483 = vcat [ ptext SLIT("__interface")
484 <+> doubleQuotes (ptext opt_InPackage)
485 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
487 <+> (if mi_orphan iface then char '!' else empty)
488 <+> int opt_HiVersion
489 <+> ptext SLIT("where")
491 , vcat (map pprExport (mi_exports iface))
492 , vcat (map pprUsage (mi_usages iface))
494 , pprFixities (mi_fixities iface) (dcl_tycl decls)
495 , pprIfaceDecls (vers_decls version_info) decls
496 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
499 version_info = mi_version iface
500 decls = mi_decls iface
501 exp_vers = vers_exports version_info
502 rule_vers = vers_rules version_info
504 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
505 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
508 When printing export lists, we print like this:
510 AvailTC C [C, x, y] C(x,y)
511 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
514 pprExport :: (ModuleName, Avails) -> SDoc
515 pprExport (mod, items)
516 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
518 pp_avail :: AvailInfo -> SDoc
519 pp_avail (Avail name) = pprOcc name
520 pp_avail (AvailTC n []) = empty
521 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
522 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
525 pp_export names = braces (hsep (map pprOcc names))
527 pprOcc :: Name -> SDoc -- Print the occurrence name only
528 pprOcc n = pprOccName (nameOccName n)
533 pprUsage :: ImportVersion Name -> SDoc
534 pprUsage (m, has_orphans, is_boot, whats_imported)
535 = hsep [ptext SLIT("import"), ppr m,
537 pp_versions whats_imported
540 pp_orphan | has_orphans = char '!'
542 pp_boot | is_boot = char '@'
545 -- Importing the whole module is indicated by an empty list
546 pp_versions NothingAtAll = empty
547 pp_versions (Everything v) = dcolon <+> int v
548 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
549 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
551 pp_export_version Nothing = empty
552 pp_export_version (Just v) = int v
556 pprIfaceDecls version_map decls
557 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
558 , vcat (map ppr_decl (dcl_tycl decls))
561 ppr_decl d = ppr_vers d <+> ppr d <> semi
563 -- Print the version for the decl
564 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
570 pprFixities fixity_map decls
571 = hsep [ ppr fix <+> ppr n
573 (n,_) <- tyClDeclNames d,
574 Just fix <- [lookupNameEnv fixity_map n]] <> semi
576 -- Disgusting to print these two together, but that's
577 -- the way the interface parser currently expects them.
578 pprRulesAndDeprecs [] NoDeprecs = empty
579 pprRulesAndDeprecs rules deprecs
580 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
583 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
585 pp_deprecs NoDeprecs = empty
586 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
588 guts = case deprecs of
589 DeprecAll txt -> doubleQuotes (ptext txt)
590 DeprecSome env -> ppr_deprec_env env
592 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
594 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)