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 ( 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,
50 isClassTyCon, isForeignTyCon
52 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
53 import FieldLabel ( fieldLabelType )
54 import Type ( splitSigmaTy, tidyTopType, deNoteType, namesOfDFunHead )
55 import SrcLoc ( noSrcLoc )
57 import Module ( ModuleName )
58 import Util ( sortLt, unJust )
59 import ErrUtils ( dumpIfSet_dyn )
62 import IO ( IOMode(..), openFile, hClose )
66 %************************************************************************
68 \subsection{Completing an interface}
70 %************************************************************************
76 mkFinalIface :: GhciMode
79 -> Maybe ModIface -- The old interface, if we have it
80 -> ModIface -- The new one, minus the decls and versions
81 -> ModDetails -- The ModDetails for this module
82 -> IO ModIface -- The new one, complete with decls and versions
84 -- a) completes the interface
85 -- b) writes it out to a file if necessary
87 mkFinalIface ghci_mode dflags location
88 maybe_old_iface new_iface new_details
90 -- Add the new declarations, and the is-orphan flag
91 let iface_w_decls = new_iface { mi_decls = new_decls,
92 mi_orphan = orphan_mod }
94 -- Add version information
95 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
97 -- Write the interface file, if necessary
98 ; when (must_write_hi_file maybe_diffs)
99 (writeIface hi_file_path final_iface)
102 ; write_diffs dflags final_iface maybe_diffs
104 ; return final_iface }
107 must_write_hi_file Nothing = False
108 must_write_hi_file (Just diffs) = ghci_mode /= Interactive
109 -- We must write a new .hi file if there are some changes
110 -- and we're not in interactive mode
111 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
112 -- so there's no need to write a new interface file. But even if
113 -- the usages have changed, the module version may not have.
115 hi_file_path = unJust "mkFinalIface" (ml_hi_file location)
116 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
117 inst_dcls = map ifaceInstance (md_insts new_details)
118 ty_cls_dcls = foldNameEnv ifaceTyCls [] (md_types new_details)
119 rule_dcls = map ifaceRule (md_rules new_details)
120 orphan_mod = isOrphanModule (mi_module new_iface) new_details
122 write_diffs dflags new_iface Nothing
123 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
124 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
126 write_diffs dflags new_iface (Just sdoc_diffs)
127 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
128 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
132 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
133 = any orphan_inst insts || any orphan_rule rules
135 orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
136 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
137 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
141 ifaceTyCls :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
142 ifaceTyCls (AClass clas) so_far
145 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
146 tcdName = getName clas,
147 tcdTyVars = toHsTyVars clas_tyvars,
148 tcdFDs = toHsFDs clas_fds,
149 tcdSigs = map toClassOpSig op_stuff,
151 tcdSysNames = sys_names,
154 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
155 tycon = classTyCon clas
156 data_con = head (tyConDataCons tycon)
157 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
158 getName (dataConId data_con), map getName sc_sels)
160 toClassOpSig (sel_id, def_meth)
161 = ASSERT(sel_tyvars == clas_tyvars)
162 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
164 (sel_tyvars, _, op_ty) = splitSigmaTy (idType sel_id)
165 def_meth' = case def_meth of
166 NoDefMeth -> NoDefMeth
167 GenDefMeth -> GenDefMeth
168 DefMeth id -> DefMeth (getName id)
170 ifaceTyCls (ATyCon tycon) so_far
171 | isClassTyCon tycon = so_far
172 | otherwise = ty_decl : so_far
174 ty_decl | isSynTyCon tycon
175 = TySynonym { tcdName = getName tycon,
176 tcdTyVars = toHsTyVars tyvars,
177 tcdSynRhs = toHsType syn_ty,
181 = TyData { tcdND = new_or_data,
182 tcdCtxt = toHsContext (tyConTheta tycon),
183 tcdName = getName tycon,
184 tcdTyVars = toHsTyVars tyvars,
185 tcdCons = map ifaceConDecl (tyConDataCons tycon),
186 tcdNCons = tyConFamilySize tycon,
188 tcdSysNames = map getName (tyConGenIds tycon),
191 | isForeignTyCon tycon
192 = ForeignType { tcdName = getName tycon,
193 tcdFoType = DNType, -- The only case at present
196 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
198 tyvars = tyConTyVars tycon
199 (_, syn_ty) = getSynTyConDefn tycon
200 new_or_data | isNewTyCon tycon = NewType
201 | otherwise = DataType
203 ifaceConDecl data_con
204 = ConDecl (getName data_con) (getName (dataConId data_con))
205 (toHsTyVars ex_tyvars)
206 (toHsContext ex_theta)
209 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
210 field_labels = dataConFieldLabels data_con
211 strict_marks = drop (length ex_theta) (dataConStrictMarks data_con)
212 -- The 'drop' is because dataConStrictMarks
213 -- includes the existential dictionaries
214 details | null field_labels
215 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
216 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
219 = RecCon (zipWith mk_field strict_marks field_labels)
221 mk_field strict_mark field_label
222 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
224 ifaceTyCls (AnId id) so_far
225 | isImplicitId id = so_far
226 | otherwise = iface_sig : so_far
228 iface_sig = IfaceSig { tcdName = getName id,
229 tcdType = toHsType id_type,
230 tcdIdInfo = hs_idinfo,
235 cg_info = idCgInfo id
236 arity_info = cgArity cg_info
237 caf_info = cgCafInfo cg_info
239 hs_idinfo | opt_OmitInterfacePragmas = []
240 | otherwise = arity_hsinfo ++ caf_hsinfo ++ cpr_hsinfo ++
241 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
243 ------------ Arity --------------
244 arity_hsinfo | arity_info == 0 = []
245 | otherwise = [HsArity arity_info]
247 ------------ Caf Info --------------
248 caf_hsinfo = case caf_info of
249 NoCafRefs -> [HsNoCafRefs]
252 ------------ CPR Info --------------
253 cpr_hsinfo = case cprInfo id_info of
254 ReturnsCPR -> [HsCprInfo]
257 ------------ Strictness --------------
258 strict_hsinfo = case strictnessInfo id_info of
259 NoStrictnessInfo -> []
260 info -> [HsStrictness info]
262 ------------ Worker --------------
263 work_info = workerInfo id_info
264 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
265 wrkr_hsinfo = case work_info of
266 HasWorker work_id wrap_arity ->
267 [HsWorker (getName work_id) wrap_arity]
270 ------------ Unfolding --------------
271 -- The unfolding is redundant if there is a worker
272 unfold_info = unfoldingInfo id_info
273 inline_prag = inlinePragInfo id_info
274 rhs = unfoldingTemplate unfold_info
275 unfold_hsinfo | neverUnfold unfold_info
277 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
281 ifaceInstance :: DFunId -> RenamedInstDecl
282 ifaceInstance dfun_id
283 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
285 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
286 -- The deNoteType is very important. It removes all type
287 -- synonyms from the instance type in interface files.
288 -- That in turn makes sure that when reading in instance decls
289 -- from interface files that the 'gating' mechanism works properly.
290 -- Otherwise you could have
291 -- type Tibble = T Int
292 -- instance Foo Tibble where ...
293 -- and this instance decl wouldn't get imported into a module
294 -- that mentioned T but not Tibble.
296 ifaceRule (id, BuiltinRule _)
297 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
299 ifaceRule (id, Rule name bndrs args rhs)
300 = IfaceRule name (map toUfBndr bndrs) (getName id)
301 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
304 = IfaceRule SLIT("bogus") [] (getName id) [] (UfVar (getName id)) noSrcLoc
308 %************************************************************************
310 \subsection{Checking if the new interface is up to date
312 %************************************************************************
315 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
316 -> ModIface -- The new interface decls
317 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
318 -- Just mi => Here is the new interface to write
319 -- with correct version numbers
321 -- NB: the fixities, declarations, rules are all assumed
322 -- to be sorted by increasing order of hsDeclName, so that
323 -- we can compare for equality
325 addVersionInfo Nothing new_iface
326 -- No old interface, so definitely write a new one!
327 = (new_iface, Just (text "No old interface available"))
329 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
330 mi_decls = old_decls,
331 mi_fixities = old_fixities,
332 mi_deprecs = old_deprecs }))
333 new_iface@(ModIface { mi_decls = new_decls,
334 mi_fixities = new_fixities,
335 mi_deprecs = new_deprecs })
337 | no_output_change && no_usage_change
338 = (new_iface, Nothing)
339 -- don't return the old iface because it may not have an
340 -- mi_globals field set to anything reasonable.
342 | otherwise -- Add updated version numbers
343 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
344 (final_iface, Just pp_diffs)
347 final_iface = new_iface { mi_version = new_version }
348 old_mod_vers = vers_module old_version
349 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
350 vers_exports = bumpVersion no_export_change (vers_exports old_version),
351 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
352 vers_decls = tc_vers }
354 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
355 no_usage_change = mi_usages old_iface == mi_usages new_iface
357 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
358 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
359 no_deprec_change = old_deprecs == new_deprecs
361 -- Fill in the version number on the new declarations by looking at the old declarations.
362 -- Set the flag if anything changes.
363 -- Assumes that the decls are sorted by hsDeclName.
364 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
365 (dcl_tycl old_decls) (dcl_tycl new_decls)
366 pp_diffs = vcat [pp_tc_diffs,
367 pp_change no_export_change "Export list",
368 pp_change no_rule_change "Rules",
369 pp_change no_deprec_change "Deprecations",
370 pp_change no_usage_change "Usages"]
371 pp_change True what = empty
372 pp_change False what = text what <+> ptext SLIT("changed")
374 diffDecls :: VersionInfo -- Old version
375 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
376 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
377 -> (Bool, -- True <=> no change
378 SDoc, -- Record of differences
379 NameEnv Version) -- New version map
381 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
382 old_fixities new_fixities old new
383 = diff True empty emptyNameEnv old new
385 -- When seeing if two decls are the same,
386 -- remember to check whether any relevant fixity has changed
387 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
388 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
390 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
391 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
392 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
394 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
395 -- When adding a new item, start from the old module version
396 -- This way, if you have version 4 of f, then delete f, then add f again,
397 -- you'll get version 6 of f, which will (correctly) force recompilation of
400 diff ok_so_far pp new_vers (od:ods) (nd:nds)
401 = case od_name `compare` nd_name of
402 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
403 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
404 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
405 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
407 od_name = tyClDeclName od
408 nd_name = tyClDeclName nd
409 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
410 old_version = lookupVersion old_decls_vers od_name
412 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
413 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
414 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
415 (ptext SLIT("New:") <+> ppr nd))
420 %************************************************************************
422 \subsection{Writing ModDetails}
424 %************************************************************************
427 pprModDetails :: ModDetails -> SDoc
428 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
429 = vcat [ dump_types dfun_ids type_env
430 , dump_insts dfun_ids
433 dump_types dfun_ids type_env
434 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
436 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
437 want_sig id | opt_PprStyle_Debug = True
438 | otherwise = isLocalId id &&
439 isGlobalName (idName id) &&
440 not (id `elem` dfun_ids)
441 -- isLocalId ignores data constructors, records selectors etc
442 -- The isGlobalName ignores local dictionary and method bindings
443 -- that the type checker has invented. User-defined things have
446 dump_insts [] = empty
447 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
450 -- Print type signatures
451 -- Convert to HsType so that we get source-language style printing
452 -- And sort by RdrName
453 = vcat $ map ppr_sig $ sortLt lt_sig $
454 [ (toRdrName id, toHsType (idType id))
457 lt_sig (n1,_) (n2,_) = n1 < n2
458 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
460 dump_rules [] = empty
461 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
462 nest 4 (vcat (map pprIdCoreRule rs)),
467 %************************************************************************
469 \subsection{Writing an interface file}
471 %************************************************************************
474 writeIface :: FilePath -> ModIface -> IO ()
475 writeIface hi_path mod_iface
476 = do { if_hdl <- openFile hi_path WriteMode
477 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
481 -- Print names unqualified if they are from this module
482 from_this_mod n = nameModule n == this_mod
483 this_mod = mi_module mod_iface
485 pprIface :: ModIface -> SDoc
487 = vcat [ ptext SLIT("__interface")
488 <+> doubleQuotes (ptext opt_InPackage)
489 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
491 <+> (if mi_orphan iface then char '!' else empty)
492 <+> int opt_HiVersion
493 <+> ptext SLIT("where")
495 , vcat (map pprExport (mi_exports iface))
496 , vcat (map pprUsage (mi_usages iface))
498 , pprFixities (mi_fixities iface) (dcl_tycl decls)
499 , pprIfaceDecls (vers_decls version_info) decls
500 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
503 version_info = mi_version iface
504 decls = mi_decls iface
505 exp_vers = vers_exports version_info
506 rule_vers = vers_rules version_info
508 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
509 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
512 When printing export lists, we print like this:
514 AvailTC C [C, x, y] C(x,y)
515 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
518 pprExport :: (ModuleName, Avails) -> SDoc
519 pprExport (mod, items)
520 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
522 pp_avail :: AvailInfo -> SDoc
523 pp_avail (Avail name) = pprOcc name
524 pp_avail (AvailTC n []) = empty
525 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
526 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
529 pp_export names = braces (hsep (map pprOcc names))
531 pprOcc :: Name -> SDoc -- Print the occurrence name only
532 pprOcc n = pprOccName (nameOccName n)
537 pprUsage :: ImportVersion Name -> SDoc
538 pprUsage (m, has_orphans, is_boot, whats_imported)
539 = hsep [ptext SLIT("import"), ppr m,
541 pp_versions whats_imported
544 pp_orphan | has_orphans = char '!'
546 pp_boot | is_boot = char '@'
549 -- Importing the whole module is indicated by an empty list
550 pp_versions NothingAtAll = empty
551 pp_versions (Everything v) = dcolon <+> int v
552 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
553 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
555 pp_export_version Nothing = empty
556 pp_export_version (Just v) = int v
560 pprIfaceDecls version_map decls
561 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
562 , vcat (map ppr_decl (dcl_tycl decls))
565 ppr_decl d = ppr_vers d <+> ppr d <> semi
567 -- Print the version for the decl
568 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
574 pprFixities fixity_map decls
575 = hsep [ ppr fix <+> ppr n
577 (n,_) <- tyClDeclNames d,
578 Just fix <- [lookupNameEnv fixity_map n]] <> semi
580 -- Disgusting to print these two together, but that's
581 -- the way the interface parser currently expects them.
582 pprRulesAndDeprecs [] NoDeprecs = empty
583 pprRulesAndDeprecs rules deprecs
584 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
587 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
589 pp_deprecs NoDeprecs = empty
590 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
592 guts = case deprecs of
593 DeprecAll txt -> doubleQuotes (ptext txt)
594 DeprecSome env -> ppr_deprec_env env
596 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
598 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)