2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 \section[MkIface]{Print an interface for a module}
10 pprModDetails, pprIface, pprUsage,
14 #include "HsVersions.h"
17 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
18 import HsTypes ( toHsTyVars )
19 import TysPrim ( alphaTyVars )
20 import BasicTypes ( Fixity(..), NewOrData(..), Activation(..),
21 Version, initialVersion, bumpVersion
23 import NewDemand ( isTopSig )
25 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
26 import HscTypes ( VersionInfo(..), ModIface(..), ModDetails(..),
27 ModuleLocation(..), GhciMode(..),
28 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
29 TyThing(..), DFunId, Avails,
30 WhatsImported(..), GenAvailInfo(..),
31 ImportVersion, AvailInfo, Deprecations(..),
36 import Id ( idType, idInfo, isImplicitId, idCgInfo,
39 import DataCon ( dataConId, dataConSig, dataConFieldLabels, dataConStrictMarks )
41 import CoreSyn ( CoreRule(..) )
42 import CoreFVs ( ruleLhsFreeNames )
43 import CoreUnfold ( neverUnfold, unfoldingTemplate )
44 import PprCore ( pprIdCoreRule )
45 import Name ( getName, nameModule, toRdrName, isGlobalName,
46 nameIsLocalOrFrom, Name, NamedThing(..) )
49 import OccName ( pprOccName )
50 import TyCon ( TyCon, getSynTyConDefn, isSynTyCon, isNewTyCon,
51 isAlgTyCon, tyConGenIds, tyConTheta, tyConTyVars,
52 tyConDataCons, tyConFamilySize, isPrimTyCon,
53 isClassTyCon, isForeignTyCon, tyConArity
55 import Class ( classExtraBigSig, classTyCon, DefMeth(..) )
56 import FieldLabel ( fieldLabelType )
57 import TcType ( tcSplitSigmaTy, tidyTopType, deNoteType, namesOfDFunHead )
58 import SrcLoc ( noSrcLoc )
60 import Module ( ModuleName )
61 import Util ( sortLt )
62 import ErrUtils ( dumpIfSet_dyn )
65 import IO ( IOMode(..), openFile, hClose )
69 %************************************************************************
71 \subsection{Completing an interface}
73 %************************************************************************
79 mkFinalIface :: GhciMode
82 -> Maybe ModIface -- The old interface, if we have it
83 -> ModIface -- The new one, minus the decls and versions
84 -> ModDetails -- The ModDetails for this module
85 -> IO ModIface -- The new one, complete with decls and versions
87 -- a) completes the interface
88 -- b) writes it out to a file if necessary
90 mkFinalIface ghci_mode dflags location
91 maybe_old_iface new_iface new_details
93 -- Add the new declarations, and the is-orphan flag
94 let iface_w_decls = new_iface { mi_decls = new_decls,
95 mi_orphan = orphan_mod }
97 -- Add version information
98 ; let (final_iface, maybe_diffs) = addVersionInfo maybe_old_iface iface_w_decls
100 -- Write the interface file, if necessary
101 ; when (must_write_hi_file maybe_diffs)
102 (writeIface hi_file_path final_iface)
105 ; write_diffs dflags final_iface maybe_diffs
107 ; return final_iface }
110 must_write_hi_file Nothing = False
111 must_write_hi_file (Just diffs) = ghci_mode /= Interactive
112 -- We must write a new .hi file if there are some changes
113 -- and we're not in interactive mode
114 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
115 -- so there's no need to write a new interface file. But even if
116 -- the usages have changed, the module version may not have.
118 hi_file_path = ml_hi_file location
119 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
120 inst_dcls = map ifaceInstance (md_insts new_details)
121 ty_cls_dcls = foldNameEnv ifaceTyCls_acc [] (md_types new_details)
122 rule_dcls = map ifaceRule (md_rules new_details)
123 orphan_mod = isOrphanModule (mi_module new_iface) new_details
125 write_diffs dflags new_iface Nothing
126 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
127 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
129 write_diffs dflags new_iface (Just sdoc_diffs)
130 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
131 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
135 isOrphanModule this_mod (ModDetails {md_insts = insts, md_rules = rules})
136 = any orphan_inst insts || any orphan_rule rules
138 orphan_inst dfun_id = no_locals (namesOfDFunHead (idType dfun_id))
139 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
140 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
143 Implicit Ids and class tycons aren't included in interface files, so
144 we miss them out of the accumulating parameter here.
147 ifaceTyCls_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
148 ifaceTyCls_acc (AnId id) so_far | isImplicitId id = so_far
149 ifaceTyCls_acc (ATyCon id) so_far | isClassTyCon id = so_far
150 ifaceTyCls_acc other so_far = ifaceTyCls other : so_far
153 Convert *any* TyThing into a RenamedTyClDecl. Used both for
154 generating interface files and for the ':info' command in GHCi.
157 ifaceTyCls :: TyThing -> RenamedTyClDecl
158 ifaceTyCls (AClass clas) = cls_decl
160 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
161 tcdName = getName clas,
162 tcdTyVars = toHsTyVars clas_tyvars,
163 tcdFDs = toHsFDs clas_fds,
164 tcdSigs = map toClassOpSig op_stuff,
166 tcdSysNames = sys_names,
169 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
170 tycon = classTyCon clas
171 data_con = head (tyConDataCons tycon)
172 sys_names = mkClassDeclSysNames (getName tycon, getName data_con,
173 getName (dataConId data_con), map getName sc_sels)
175 toClassOpSig (sel_id, def_meth)
176 = ASSERT(sel_tyvars == clas_tyvars)
177 ClassOpSig (getName sel_id) def_meth' (toHsType op_ty) noSrcLoc
179 (sel_tyvars, _, op_ty) = tcSplitSigmaTy (idType sel_id)
180 def_meth' = case def_meth of
181 NoDefMeth -> NoDefMeth
182 GenDefMeth -> GenDefMeth
183 DefMeth id -> DefMeth (getName id)
185 ifaceTyCls (ATyCon tycon) = ty_decl
187 ty_decl | isSynTyCon tycon
188 = TySynonym { tcdName = getName tycon,
189 tcdTyVars = toHsTyVars tyvars,
190 tcdSynRhs = toHsType syn_ty,
194 = TyData { tcdND = new_or_data,
195 tcdCtxt = toHsContext (tyConTheta tycon),
196 tcdName = getName tycon,
197 tcdTyVars = toHsTyVars tyvars,
198 tcdCons = map ifaceConDecl (tyConDataCons tycon),
199 tcdNCons = tyConFamilySize tycon,
201 tcdSysNames = map getName (tyConGenIds tycon),
204 | isForeignTyCon tycon
205 = ForeignType { tcdName = getName tycon,
206 tcdFoType = DNType, -- The only case at present
210 -- needed in GHCi for ':info Int#', for example
211 = TyData { tcdND = DataType,
213 tcdName = getName tycon,
214 tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
221 | otherwise = pprPanic "ifaceTyCls" (ppr tycon)
223 tyvars = tyConTyVars tycon
224 (_, syn_ty) = getSynTyConDefn tycon
225 new_or_data | isNewTyCon tycon = NewType
226 | otherwise = DataType
228 ifaceConDecl data_con
229 = ConDecl (getName data_con) (getName (dataConId data_con))
230 (toHsTyVars ex_tyvars)
231 (toHsContext ex_theta)
234 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
235 field_labels = dataConFieldLabels data_con
236 strict_marks = drop (length ex_theta) (dataConStrictMarks data_con)
237 -- The 'drop' is because dataConStrictMarks
238 -- includes the existential dictionaries
239 details | null field_labels
240 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
241 VanillaCon (zipWith BangType strict_marks (map toHsType arg_tys))
244 = RecCon (zipWith mk_field strict_marks field_labels)
246 mk_field strict_mark field_label
247 = ([getName field_label], BangType strict_mark (toHsType (fieldLabelType field_label)))
249 ifaceTyCls (AnId id) = iface_sig
251 iface_sig = IfaceSig { tcdName = getName id,
252 tcdType = toHsType id_type,
253 tcdIdInfo = hs_idinfo,
258 cg_info = idCgInfo id
259 arity_info = cgArity cg_info
260 caf_info = cgCafInfo cg_info
262 hs_idinfo | opt_OmitInterfacePragmas = []
263 | otherwise = arity_hsinfo ++ caf_hsinfo ++
264 strict_hsinfo ++ wrkr_hsinfo ++ unfold_hsinfo
266 ------------ Arity --------------
267 arity_hsinfo | arity_info == 0 = []
268 | otherwise = [HsArity arity_info]
270 ------------ Caf Info --------------
271 caf_hsinfo = case caf_info of
272 NoCafRefs -> [HsNoCafRefs]
275 ------------ Strictness --------------
276 -- No point in explicitly exporting TopSig
277 strict_hsinfo = case newStrictnessInfo id_info of
278 Just sig | not (isTopSig sig) -> [HsStrictness sig]
281 ------------ Worker --------------
282 work_info = workerInfo id_info
283 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
284 wrkr_hsinfo = case work_info of
285 HasWorker work_id wrap_arity ->
286 [HsWorker (getName work_id) wrap_arity]
289 ------------ Unfolding --------------
290 -- The unfolding is redundant if there is a worker
291 unfold_info = unfoldingInfo id_info
292 inline_prag = inlinePragInfo id_info
293 rhs = unfoldingTemplate unfold_info
294 unfold_hsinfo | neverUnfold unfold_info
296 | otherwise = [HsUnfold inline_prag (toUfExpr rhs)]
300 ifaceInstance :: DFunId -> RenamedInstDecl
301 ifaceInstance dfun_id
302 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
304 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
305 -- The deNoteType is very important. It removes all type
306 -- synonyms from the instance type in interface files.
307 -- That in turn makes sure that when reading in instance decls
308 -- from interface files that the 'gating' mechanism works properly.
309 -- Otherwise you could have
310 -- type Tibble = T Int
311 -- instance Foo Tibble where ...
312 -- and this instance decl wouldn't get imported into a module
313 -- that mentioned T but not Tibble.
315 ifaceRule (id, BuiltinRule _ _)
316 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
318 ifaceRule (id, Rule name act bndrs args rhs)
319 = IfaceRule name act (map toUfBndr bndrs) (getName id)
320 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
323 = IfaceRule SLIT("bogus") NeverActive [] (getName id) [] (UfVar (getName id)) noSrcLoc
327 %************************************************************************
329 \subsection{Checking if the new interface is up to date
331 %************************************************************************
334 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
335 -> ModIface -- The new interface decls
336 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
337 -- Just mi => Here is the new interface to write
338 -- with correct version numbers
340 -- NB: the fixities, declarations, rules are all assumed
341 -- to be sorted by increasing order of hsDeclName, so that
342 -- we can compare for equality
344 addVersionInfo Nothing new_iface
345 -- No old interface, so definitely write a new one!
346 = (new_iface, Just (text "No old interface available"))
348 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
349 mi_decls = old_decls,
350 mi_fixities = old_fixities,
351 mi_deprecs = old_deprecs }))
352 new_iface@(ModIface { mi_decls = new_decls,
353 mi_fixities = new_fixities,
354 mi_deprecs = new_deprecs })
356 | no_output_change && no_usage_change
357 = (new_iface, Nothing)
358 -- don't return the old iface because it may not have an
359 -- mi_globals field set to anything reasonable.
361 | otherwise -- Add updated version numbers
362 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
363 (final_iface, Just pp_diffs)
366 final_iface = new_iface { mi_version = new_version }
367 old_mod_vers = vers_module old_version
368 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
369 vers_exports = bumpVersion no_export_change (vers_exports old_version),
370 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
371 vers_decls = tc_vers }
373 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
374 no_usage_change = mi_usages old_iface == mi_usages new_iface
376 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
377 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
378 no_deprec_change = old_deprecs == new_deprecs
380 -- Fill in the version number on the new declarations by looking at the old declarations.
381 -- Set the flag if anything changes.
382 -- Assumes that the decls are sorted by hsDeclName.
383 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
384 (dcl_tycl old_decls) (dcl_tycl new_decls)
385 pp_diffs = vcat [pp_tc_diffs,
386 pp_change no_export_change "Export list",
387 pp_change no_rule_change "Rules",
388 pp_change no_deprec_change "Deprecations",
389 pp_change no_usage_change "Usages"]
390 pp_change True what = empty
391 pp_change False what = text what <+> ptext SLIT("changed")
393 diffDecls :: VersionInfo -- Old version
394 -> NameEnv Fixity -> NameEnv Fixity -- Old and new fixities
395 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
396 -> (Bool, -- True <=> no change
397 SDoc, -- Record of differences
398 NameEnv Version) -- New version map
400 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
401 old_fixities new_fixities old new
402 = diff True empty emptyNameEnv old new
404 -- When seeing if two decls are the same,
405 -- remember to check whether any relevant fixity has changed
406 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
407 same_fixity n = lookupNameEnv old_fixities n == lookupNameEnv new_fixities n
409 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
410 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
411 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
413 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
414 -- When adding a new item, start from the old module version
415 -- This way, if you have version 4 of f, then delete f, then add f again,
416 -- you'll get version 6 of f, which will (correctly) force recompilation of
419 diff ok_so_far pp new_vers (od:ods) (nd:nds)
420 = case od_name `compare` nd_name of
421 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
422 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
423 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
424 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
426 od_name = tyClDeclName od
427 nd_name = tyClDeclName nd
428 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
429 old_version = lookupVersion old_decls_vers od_name
431 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
432 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
433 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
434 (ptext SLIT("New:") <+> ppr nd))
439 %************************************************************************
441 \subsection{Writing ModDetails}
443 %************************************************************************
446 pprModDetails :: ModDetails -> SDoc
447 pprModDetails (ModDetails { md_types = type_env, md_insts = dfun_ids, md_rules = rules })
448 = vcat [ dump_types dfun_ids type_env
449 , dump_insts dfun_ids
452 dump_types dfun_ids type_env
453 = text "TYPE SIGNATURES" $$ nest 4 (dump_sigs ids)
455 ids = [id | AnId id <- nameEnvElts type_env, want_sig id]
456 want_sig id | opt_PprStyle_Debug = True
457 | otherwise = isLocalId id &&
458 isGlobalName (idName id) &&
459 not (id `elem` dfun_ids)
460 -- isLocalId ignores data constructors, records selectors etc
461 -- The isGlobalName ignores local dictionary and method bindings
462 -- that the type checker has invented. User-defined things have
465 dump_insts [] = empty
466 dump_insts dfun_ids = text "INSTANCES" $$ nest 4 (dump_sigs dfun_ids)
469 -- Print type signatures
470 -- Convert to HsType so that we get source-language style printing
471 -- And sort by RdrName
472 = vcat $ map ppr_sig $ sortLt lt_sig $
473 [ (toRdrName id, toHsType (idType id))
476 lt_sig (n1,_) (n2,_) = n1 < n2
477 ppr_sig (n,t) = ppr n <+> dcolon <+> ppr t
479 dump_rules [] = empty
480 dump_rules rs = vcat [ptext SLIT("{-# RULES"),
481 nest 4 (vcat (map pprIdCoreRule rs)),
486 %************************************************************************
488 \subsection{Writing an interface file}
490 %************************************************************************
493 writeIface :: FilePath -> ModIface -> IO ()
494 writeIface hi_path mod_iface
495 = do { if_hdl <- openFile hi_path WriteMode
496 ; printForIface if_hdl from_this_mod (pprIface mod_iface)
500 -- Print names unqualified if they are from this module
501 from_this_mod n = nameModule n == this_mod
502 this_mod = mi_module mod_iface
504 pprIface :: ModIface -> SDoc
506 = vcat [ ptext SLIT("__interface")
507 <+> doubleQuotes (ptext opt_InPackage)
508 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
510 <+> (if mi_orphan iface then char '!' else empty)
511 <+> int opt_HiVersion
512 <+> ptext SLIT("where")
514 , vcat (map pprExport (mi_exports iface))
515 , vcat (map pprUsage (mi_usages iface))
517 , pprFixities (mi_fixities iface) (dcl_tycl decls)
518 , pprIfaceDecls (vers_decls version_info) decls
519 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
522 version_info = mi_version iface
523 decls = mi_decls iface
524 exp_vers = vers_exports version_info
525 rule_vers = vers_rules version_info
527 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
528 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
531 When printing export lists, we print like this:
533 AvailTC C [C, x, y] C(x,y)
534 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
537 pprExport :: (ModuleName, Avails) -> SDoc
538 pprExport (mod, items)
539 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
541 pp_avail :: AvailInfo -> SDoc
542 pp_avail (Avail name) = pprOcc name
543 pp_avail (AvailTC n []) = empty
544 pp_avail (AvailTC n (n':ns)) | n==n' = pprOcc n <> pp_export ns
545 | otherwise = pprOcc n <> char '|' <> pp_export (n':ns)
548 pp_export names = braces (hsep (map pprOcc names))
550 pprOcc :: Name -> SDoc -- Print the occurrence name only
551 pprOcc n = pprOccName (nameOccName n)
556 pprUsage :: ImportVersion Name -> SDoc
557 pprUsage (m, has_orphans, is_boot, whats_imported)
558 = hsep [ptext SLIT("import"), ppr m,
560 pp_versions whats_imported
563 pp_orphan | has_orphans = char '!'
565 pp_boot | is_boot = char '@'
568 -- Importing the whole module is indicated by an empty list
569 pp_versions NothingAtAll = empty
570 pp_versions (Everything v) = dcolon <+> int v
571 pp_versions (Specifically vm ve nvs vr) = dcolon <+> int vm <+> pp_export_version ve <+> int vr
572 <+> hsep [ pprOcc n <+> int v | (n,v) <- nvs ]
574 pp_export_version Nothing = empty
575 pp_export_version (Just v) = int v
579 pprIfaceDecls version_map decls
580 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
581 , vcat (map ppr_decl (dcl_tycl decls))
584 ppr_decl d = ppr_vers d <+> ppr d <> semi
586 -- Print the version for the decl
587 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
593 pprFixities fixity_map decls
594 = hsep [ ppr fix <+> ppr n
596 (n,_) <- tyClDeclNames d,
597 Just fix <- [lookupNameEnv fixity_map n]] <> semi
599 -- Disgusting to print these two together, but that's
600 -- the way the interface parser currently expects them.
601 pprRulesAndDeprecs [] NoDeprecs = empty
602 pprRulesAndDeprecs rules deprecs
603 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
606 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
608 pp_deprecs NoDeprecs = empty
609 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
611 guts = case deprecs of
612 DeprecAll txt -> doubleQuotes (ptext txt)
613 DeprecSome env -> ppr_deprec_env env
615 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
617 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ptext txt)