2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
5 \section[MkIface]{Print an interface for a module}
9 showIface, mkIface, mkUsageInfo,
14 #include "HsVersions.h"
17 import HsCore ( HsIdInfo(..), UfExpr(..), toUfExpr, toUfBndr )
18 import HsTypes ( toHsTyVars )
19 import TysPrim ( alphaTyVars )
20 import BasicTypes ( NewOrData(..), Activation(..), FixitySig(..),
21 Version, initialVersion, bumpVersion
23 import NewDemand ( isTopSig )
25 import TcRnTypes ( ImportAvails(..) )
26 import RnHsSyn ( RenamedInstDecl, RenamedTyClDecl )
27 import HscTypes ( VersionInfo(..), ModIface(..),
29 GhciMode(..), HscEnv(..), Dependencies(..),
30 FixityEnv, lookupFixity, collectFixities,
31 IfaceDecls, mkIfaceDecls, dcl_tycl, dcl_rules, dcl_insts,
33 Avails, AvailInfo, GenAvailInfo(..), availName,
34 ExternalPackageState(..),
35 ParsedIface(..), Usage(..),
36 Deprecations(..), initialVersionInfo,
37 lookupVersion, lookupIfaceByModName
41 import Id ( idType, idInfo, isImplicitId, idCafInfo )
42 import DataCon ( dataConName, dataConSig, dataConFieldLabels, dataConStrictMarks )
44 import CoreSyn ( CoreRule(..), IdCoreRule )
45 import CoreFVs ( ruleLhsFreeNames )
46 import CoreUnfold ( neverUnfold, unfoldingTemplate )
47 import Name ( getName, nameModule, nameModule_maybe, nameOccName,
48 nameIsLocalOrFrom, Name, NamedThing(..) )
51 import OccName ( OccName, pprOccName )
52 import TyCon ( DataConDetails(..), tyConTyVars, tyConDataCons, tyConTheta,
53 isFunTyCon, isPrimTyCon, isNewTyCon, isClassTyCon,
54 isSynTyCon, isAlgTyCon, isForeignTyCon,
55 getSynTyConDefn, tyConGenInfo, tyConDataConDetails, tyConArity )
56 import Class ( classExtraBigSig, classTyCon )
57 import FieldLabel ( fieldLabelType )
58 import TcType ( tcSplitForAllTys, tcFunResultTy, tidyTopType, deNoteType, tyClsNamesOfDFunHead,
59 mkSigmaTy, mkFunTys, mkTyConApp, mkTyVarTys )
60 import SrcLoc ( noSrcLoc )
61 import Module ( Module, ModuleName, moduleNameFS, moduleName, isHomeModule,
62 ModLocation(..), mkSysModuleNameFS,
63 ModuleEnv, emptyModuleEnv, lookupModuleEnv,
64 extendModuleEnv_C, moduleEnvElts
67 import Util ( sortLt, dropList, seqList )
68 import Binary ( getBinFileWithDict )
69 import BinIface ( writeBinIface, v_IgnoreHiVersion )
70 import ErrUtils ( dumpIfSet_dyn )
74 import DATA_IOREF ( writeIORef )
76 import Maybe ( catMaybes, isJust, isNothing )
77 import Maybes ( orElse )
78 import IO ( putStrLn )
82 %************************************************************************
84 \subsection{Print out the contents of a binary interface}
86 %************************************************************************
89 showIface :: FilePath -> IO ()
90 showIface filename = do
91 -- skip the version check; we don't want to worry about profiled vs.
92 -- non-profiled interfaces, for example.
93 writeIORef v_IgnoreHiVersion True
94 parsed_iface <- Binary.getBinFileWithDict filename
96 pi_mod=pi_mod, pi_pkg=pi_pkg, pi_vers=pi_vers,
98 pi_orphan=pi_orphan, pi_usages=pi_usages,
99 pi_exports=pi_exports, pi_decls=pi_decls,
100 pi_fixity=pi_fixity, pi_insts=pi_insts,
101 pi_rules=pi_rules, pi_deprecs=pi_deprecs } = parsed_iface
102 putStrLn (showSDoc (vcat [
103 text "__interface" <+> doubleQuotes (ppr pi_pkg)
104 <+> ppr pi_mod <+> ppr pi_vers
105 <+> (if pi_orphan then char '!' else empty)
106 <+> ptext SLIT("where"),
107 -- no instance Outputable (WhatsImported):
108 pprExports id (snd pi_exports),
110 pprUsages id pi_usages,
111 hsep (map ppr_fix pi_fixity) <> semi,
112 vcat (map ppr_inst pi_insts),
113 vcat (map ppr_decl pi_decls),
115 -- no instance Outputable (Either):
119 ppr_fix (FixitySig n f _) = ppr f <+> ppr n
120 ppr_inst i = ppr i <+> semi
121 ppr_decl (v,d) = int v <+> ppr d <> semi
124 %************************************************************************
126 \subsection{Completing an interface}
128 %************************************************************************
133 -> Maybe ModIface -- The old interface, if we have it
134 -> ModGuts -- The compiled, tidied module
135 -> IO ModIface -- The new one, complete with decls and versions
137 -- a) completes the interface
138 -- b) writes it out to a file if necessary
140 mkIface hsc_env location maybe_old_iface
141 impl@ModGuts{ mg_module = this_mod,
144 mg_exports = exports,
145 mg_rdr_env = rdr_env,
146 mg_fix_env = fix_env,
147 mg_deprecs = deprecs,
151 = do { -- Sort the exports to make them easier to compare for versions
152 let { my_exports = groupAvails this_mod exports ;
154 iface_w_decls = ModIface { mi_module = this_mod,
155 mi_package = opt_InPackage,
156 mi_version = initialVersionInfo,
159 mi_exports = my_exports,
160 mi_decls = new_decls,
161 mi_orphan = orphan_mod,
163 mi_fixities = fix_env,
164 mi_globals = Just rdr_env,
165 mi_deprecs = deprecs } }
167 -- Add version information
168 ; let (final_iface, maybe_diffs) = _scc_ "versioninfo" addVersionInfo maybe_old_iface iface_w_decls
170 -- Write the interface file, if necessary
171 ; when (must_write_hi_file maybe_diffs)
172 (writeBinIface hi_file_path final_iface)
173 -- (writeIface hi_file_path final_iface)
176 ; write_diffs dflags final_iface maybe_diffs
182 dflags = hsc_dflags hsc_env
183 ghci_mode = hsc_mode hsc_env
185 must_write_hi_file Nothing = False
186 must_write_hi_file (Just _diffs) = ghci_mode /= Interactive
187 -- We must write a new .hi file if there are some changes
188 -- and we're not in interactive mode
189 -- maybe_diffs = 'Nothing' means that even the usages havn't changed,
190 -- so there's no need to write a new interface file. But even if
191 -- the usages have changed, the module version may not have.
193 hi_file_path = ml_hi_file location
194 new_decls = mkIfaceDecls ty_cls_dcls rule_dcls inst_dcls
195 inst_dcls = map ifaceInstance insts
196 ty_cls_dcls = foldNameEnv ifaceTyThing_acc [] types
197 rule_dcls = map ifaceRule rules
198 orphan_mod = isOrphanModule impl
200 write_diffs :: DynFlags -> ModIface -> Maybe SDoc -> IO ()
201 write_diffs dflags new_iface Nothing
202 = do when (dopt Opt_D_dump_hi_diffs dflags) (printDump (text "INTERFACE UNCHANGED"))
203 dumpIfSet_dyn dflags Opt_D_dump_hi "UNCHANGED FINAL INTERFACE" (pprIface new_iface)
205 write_diffs dflags new_iface (Just sdoc_diffs)
206 = do dumpIfSet_dyn dflags Opt_D_dump_hi_diffs "INTERFACE HAS CHANGED" sdoc_diffs
207 dumpIfSet_dyn dflags Opt_D_dump_hi "NEW FINAL INTERFACE" (pprIface new_iface)
211 isOrphanModule :: ModGuts -> Bool
212 isOrphanModule (ModGuts {mg_module = this_mod, mg_insts = insts, mg_rules = rules})
213 = any orphan_inst insts || any orphan_rule rules
215 -- A rule is an orphan if the LHS mentions nothing defined locally
216 orphan_inst dfun_id = no_locals (tyClsNamesOfDFunHead (idType dfun_id))
217 -- A instance is an orphan if its head mentions nothing defined locally
218 orphan_rule rule = no_locals (ruleLhsFreeNames rule)
220 no_locals names = isEmptyNameSet (filterNameSet (nameIsLocalOrFrom this_mod) names)
223 Implicit Ids and class tycons aren't included in interface files, so
224 we miss them out of the accumulating parameter here.
227 ifaceTyThing_acc :: TyThing -> [RenamedTyClDecl] -> [RenamedTyClDecl]
228 -- Don't put implicit things into the result
229 ifaceTyThing_acc (ADataCon dc) so_far = so_far
230 ifaceTyThing_acc (AnId id) so_far | isImplicitId id = so_far
231 ifaceTyThing_acc (ATyCon id) so_far | isClassTyCon id = so_far
232 ifaceTyThing_acc other so_far = ifaceTyThing other : so_far
235 Convert *any* TyThing into a RenamedTyClDecl. Used both for
236 generating interface files and for the ':info' command in GHCi.
239 ifaceTyThing :: TyThing -> RenamedTyClDecl
240 ifaceTyThing (AClass clas) = cls_decl
242 cls_decl = ClassDecl { tcdCtxt = toHsContext sc_theta,
243 tcdName = getName clas,
244 tcdTyVars = toHsTyVars clas_tyvars,
245 tcdFDs = toHsFDs clas_fds,
246 tcdSigs = map toClassOpSig op_stuff,
250 (clas_tyvars, clas_fds, sc_theta, sc_sels, op_stuff) = classExtraBigSig clas
251 tycon = classTyCon clas
252 data_con = head (tyConDataCons tycon)
254 toClassOpSig (sel_id, def_meth)
255 = ASSERT(sel_tyvars == clas_tyvars)
256 ClassOpSig (getName sel_id) def_meth (toHsType op_ty) noSrcLoc
258 -- Be careful when splitting the type, because of things
259 -- like class Foo a where
260 -- op :: (?x :: String) => a -> a
261 -- and class Baz a where
262 -- op :: (Ord a) => a -> a
263 (sel_tyvars, rho_ty) = tcSplitForAllTys (idType sel_id)
264 op_ty = tcFunResultTy rho_ty
266 ifaceTyThing (ATyCon tycon) = ty_decl
268 ty_decl | isSynTyCon tycon
269 = TySynonym { tcdName = getName tycon,
270 tcdTyVars = toHsTyVars tyvars,
271 tcdSynRhs = toHsType syn_ty,
275 = TyData { tcdND = new_or_data,
276 tcdCtxt = toHsContext (tyConTheta tycon),
277 tcdName = getName tycon,
278 tcdTyVars = toHsTyVars tyvars,
279 tcdCons = ifaceConDecls (tyConDataConDetails tycon),
281 tcdGeneric = Just (isJust (tyConGenInfo tycon)),
282 -- Just True <=> has generic stuff
285 | isForeignTyCon tycon
286 = ForeignType { tcdName = getName tycon,
287 tcdExtName = Nothing,
288 tcdFoType = DNType, -- The only case at present
291 | isPrimTyCon tycon || isFunTyCon tycon
292 -- needed in GHCi for ':info Int#', for example
293 = TyData { tcdND = DataType,
295 tcdName = getName tycon,
296 tcdTyVars = toHsTyVars (take (tyConArity tycon) alphaTyVars),
299 tcdGeneric = Just False,
302 | otherwise = pprPanic "ifaceTyThing" (ppr tycon)
304 tyvars = tyConTyVars tycon
305 (_, syn_ty) = getSynTyConDefn tycon
306 new_or_data | isNewTyCon tycon = NewType
307 | otherwise = DataType
309 ifaceConDecls Unknown = Unknown
310 ifaceConDecls (HasCons n) = HasCons n
311 ifaceConDecls (DataCons cs) = DataCons (map ifaceConDecl cs)
313 ifaceConDecl data_con
314 = ConDecl (dataConName data_con)
315 (toHsTyVars ex_tyvars)
316 (toHsContext ex_theta)
319 (tyvars1, _, ex_tyvars, ex_theta, arg_tys, tycon1) = dataConSig data_con
320 field_labels = dataConFieldLabels data_con
321 strict_marks = dropList ex_theta (dataConStrictMarks data_con)
322 -- The 'drop' is because dataConStrictMarks
323 -- includes the existential dictionaries
324 details | null field_labels
325 = ASSERT( tycon == tycon1 && tyvars == tyvars1 )
326 PrefixCon (zipWith BangType strict_marks (map toHsType arg_tys))
329 = RecCon (zipWith mk_field strict_marks field_labels)
331 mk_field strict_mark field_label
332 = (getName field_label, BangType strict_mark (toHsType (fieldLabelType field_label)))
334 ifaceTyThing (AnId id) = iface_sig
336 iface_sig = IfaceSig { tcdName = getName id,
337 tcdType = toHsType id_type,
338 tcdIdInfo = hs_idinfo,
343 arity_info = arityInfo id_info
344 caf_info = idCafInfo id
346 hs_idinfo | opt_OmitInterfacePragmas
349 = catMaybes [arity_hsinfo, caf_hsinfo,
350 strict_hsinfo, wrkr_hsinfo,
353 ------------ Arity --------------
354 arity_hsinfo | arity_info == 0 = Nothing
355 | otherwise = Just (HsArity arity_info)
357 ------------ Caf Info --------------
358 caf_hsinfo = case caf_info of
359 NoCafRefs -> Just HsNoCafRefs
362 ------------ Strictness --------------
363 -- No point in explicitly exporting TopSig
364 strict_hsinfo = case newStrictnessInfo id_info of
365 Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
368 ------------ Worker --------------
369 work_info = workerInfo id_info
370 has_worker = case work_info of { HasWorker _ _ -> True; other -> False }
371 wrkr_hsinfo = case work_info of
372 HasWorker work_id wrap_arity ->
373 Just (HsWorker (getName work_id) wrap_arity)
376 ------------ Unfolding --------------
377 -- The unfolding is redundant if there is a worker
378 unfold_info = unfoldingInfo id_info
379 inline_prag = inlinePragInfo id_info
380 rhs = unfoldingTemplate unfold_info
381 unfold_hsinfo | neverUnfold unfold_info
382 || has_worker = Nothing
383 | otherwise = Just (HsUnfold inline_prag (toUfExpr rhs))
386 ifaceTyThing (ADataCon dc)
387 -- This case only happens in the call to ifaceThing in InteractiveUI
388 -- Otherwise DataCons are filtered out in ifaceThing_acc
389 = IfaceSig { tcdName = getName dc,
390 tcdType = toHsType full_ty,
394 (tvs, stupid_theta, ex_tvs, ex_theta, arg_tys, tycon) = dataConSig dc
396 -- The "stupid context" isn't part of the wrapper-Id type
397 -- (for better or worse -- see note in DataCon.lhs), so we
398 -- have to make it up here
399 full_ty = mkSigmaTy (tvs ++ ex_tvs) (stupid_theta ++ ex_theta)
400 (mkFunTys arg_tys (mkTyConApp tycon (mkTyVarTys tvs)))
404 ifaceInstance :: DFunId -> RenamedInstDecl
405 ifaceInstance dfun_id
406 = InstDecl (toHsType tidy_ty) EmptyMonoBinds [] (Just (getName dfun_id)) noSrcLoc
408 tidy_ty = tidyTopType (deNoteType (idType dfun_id))
409 -- The deNoteType is very important. It removes all type
410 -- synonyms from the instance type in interface files.
411 -- That in turn makes sure that when reading in instance decls
412 -- from interface files that the 'gating' mechanism works properly.
413 -- Otherwise you could have
414 -- type Tibble = T Int
415 -- instance Foo Tibble where ...
416 -- and this instance decl wouldn't get imported into a module
417 -- that mentioned T but not Tibble.
419 ifaceRule :: IdCoreRule -> RuleDecl Name
420 ifaceRule (id, BuiltinRule _ _)
421 = pprTrace "toHsRule: builtin" (ppr id) (bogusIfaceRule id)
423 ifaceRule (id, Rule name act bndrs args rhs)
424 = IfaceRule name act (map toUfBndr bndrs) (getName id)
425 (map toUfExpr args) (toUfExpr rhs) noSrcLoc
427 bogusIfaceRule :: (NamedThing a) => a -> RuleDecl Name
429 = IfaceRule FSLIT("bogus") NeverActive [] (getName id) [] (UfVar (getName id)) noSrcLoc
433 %*********************************************************
435 \subsection{Keeping track of what we've slurped, and version numbers}
437 %*********************************************************
439 mkUsageInfo figures out what the ``usage information'' for this
440 moudule is; that is, what it must record in its interface file as the
443 We produce a line for every module B below the module, A, currently being
446 to record the fact that A does import B indirectly. This is used to decide
447 to look to look for B.hi rather than B.hi-boot when compiling a module that
448 imports A. This line says that A imports B, but uses nothing in it.
449 So we'll get an early bale-out when compiling A if B's version changes.
451 The usage information records:
454 \item (a) anything reachable from its body code
455 \item (b) any module exported with a @module Foo@
456 \item (c) anything reachable from an exported item
459 Why (b)? Because if @Foo@ changes then this module's export list
460 will change, so we must recompile this module at least as far as
461 making a new interface file --- but in practice that means complete
464 Why (c)? Consider this:
466 module A( f, g ) where | module B( f ) where
467 import B( f ) | f = h 3
471 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
472 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
473 *identical* to what it was before. If anything about @B.f@ changes
474 than anyone who imports @A@ should be recompiled in case they use
475 @B.f@ (they'll get an early exit if they don't). So, if anything
476 about @B.f@ changes we'd better make sure that something in A.hi
477 changes, and the convenient way to do that is to record the version
478 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
479 complete recompiation of A, which is overkill but it's the only way to
480 write a new, slightly different, A.hi.
482 But the example is tricker. Even if @B.f@ doesn't change at all,
483 @B.h@ may do so, and this change may not be reflected in @f@'s version
484 number. But with -O, a module that imports A must be recompiled if
485 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
486 the occurrence of @B.f@ in the export list *just as if* it were in the
487 code of A, and thereby haul in all the stuff reachable from it.
489 *** Conclusion: if A mentions B.f in its export list,
490 behave just as if A mentioned B.f in its source code,
491 and slurp in B.f and all its transitive closure ***
493 [NB: If B was compiled with -O, but A isn't, we should really *still*
494 haul in all the unfoldings for B, in case the module that imports A *is*
495 compiled with -O. I think this is the case.]
498 mkUsageInfo :: HscEnv -> ExternalPackageState
499 -> ImportAvails -> EntityUsage
502 mkUsageInfo hsc_env eps
503 (ImportAvails { imp_mods = dir_imp_mods,
504 imp_dep_mods = dep_mods })
506 = -- seq the list of Usages returned: occasionally these
507 -- don't get evaluated for a while and we can end up hanging on to
508 -- the entire collection of Ifaces.
509 usages `seqList` usages
511 usages = catMaybes [ mkUsage mod_name
512 | (mod_name,_) <- moduleEnvElts dep_mods]
513 -- ToDo: do we need to sort into canonical order?
515 hpt = hsc_HPT hsc_env
518 import_all mod = case lookupModuleEnv dir_imp_mods mod of
519 Just (_,imp_all) -> imp_all
522 -- ent_map groups together all the things imported and used
523 -- from a particular module in this package
524 ent_map :: ModuleEnv [Name]
525 ent_map = foldNameSet add_mv emptyModuleEnv used_names
526 add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [name]
528 mod = nameModule name
529 add_item names _ = name:names
531 -- We want to create a Usage for a home module if
532 -- a) we used something from; has something in used_names
533 -- b) we imported all of it, even if we used nothing from it
534 -- (need to recompile if its export list changes: export_vers)
535 -- c) is a home-package orphan module (need to recompile if its
536 -- instance decls change: rules_vers)
537 mkUsage :: ModuleName -> Maybe (Usage Name)
539 | isNothing maybe_iface -- We can't depend on it if we didn't
540 || not (isHomeModule mod) -- even open the interface!
544 = Nothing -- Record no usage info
547 = Just (Usage { usg_name = moduleName mod,
549 usg_exports = export_vers,
550 usg_entities = ent_vers,
551 usg_rules = rules_vers })
553 maybe_iface = lookupIfaceByModName hpt pit mod_name
554 -- In one-shot mode, the interfaces for home-package
555 -- modules accumulate in the PIT not HPT. Sigh.
557 Just iface = maybe_iface
558 mod = mi_module iface
559 version_info = mi_version iface
560 orphan_mod = mi_orphan iface
561 version_env = vers_decls version_info
562 mod_vers = vers_module version_info
563 rules_vers = vers_rules version_info
564 all_imported = import_all mod
565 export_vers | all_imported = Just (vers_exports version_info)
566 | otherwise = Nothing
568 -- The sort is to put them into canonical order
569 used_names = lookupModuleEnv ent_map mod `orElse` []
570 ent_vers = [(n, lookupVersion version_env n)
571 | n <- sortLt lt_occ used_names ]
572 lt_occ n1 n2 = nameOccName n1 < nameOccName n2
573 -- ToDo: is '<' on OccNames the right thing; may differ between runs?
577 groupAvails :: Module -> Avails -> [(ModuleName, Avails)]
578 -- Group by module and sort by occurrence
579 -- This keeps the list in canonical order
580 groupAvails this_mod avails
581 = [ (mkSysModuleNameFS fs, sortLt lt avails)
582 | (fs,avails) <- fmToList groupFM
585 groupFM :: FiniteMap FastString Avails
586 -- Deliberately use the FastString so we
587 -- get a canonical ordering
588 groupFM = foldl add emptyFM avails
590 add env avail = addToFM_C combine env mod_fs [avail']
592 mod_fs = moduleNameFS (moduleName avail_mod)
593 avail_mod = case nameModule_maybe (availName avail) of
596 combine old _ = avail':old
597 avail' = sortAvail avail
599 a1 `lt` a2 = occ1 < occ2
601 occ1 = nameOccName (availName a1)
602 occ2 = nameOccName (availName a2)
604 sortAvail :: AvailInfo -> AvailInfo
605 -- Sort the sub-names into canonical order.
606 -- The canonical order has the "main name" at the beginning
607 -- (if it's there at all)
608 sortAvail (Avail n) = Avail n
609 sortAvail (AvailTC n ns) | n `elem` ns = AvailTC n (n : sortLt lt (filter (/= n) ns))
610 | otherwise = AvailTC n ( sortLt lt ns)
612 n1 `lt` n2 = nameOccName n1 < nameOccName n2
615 %************************************************************************
617 \subsection{Checking if the new interface is up to date
619 %************************************************************************
622 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
623 -> ModIface -- The new interface decls
624 -> (ModIface, Maybe SDoc) -- Nothing => no change; no need to write new Iface
625 -- Just mi => Here is the new interface to write
626 -- with correct version numbers
628 -- NB: the fixities, declarations, rules are all assumed
629 -- to be sorted by increasing order of hsDeclName, so that
630 -- we can compare for equality
632 addVersionInfo Nothing new_iface
633 -- No old interface, so definitely write a new one!
634 = (new_iface, Just (text "No old interface available"))
636 addVersionInfo (Just old_iface@(ModIface { mi_version = old_version,
637 mi_decls = old_decls,
638 mi_fixities = old_fixities,
639 mi_deprecs = old_deprecs }))
640 new_iface@(ModIface { mi_decls = new_decls,
641 mi_fixities = new_fixities,
642 mi_deprecs = new_deprecs })
644 | no_output_change && no_usage_change
645 = (new_iface, Nothing)
646 -- don't return the old iface because it may not have an
647 -- mi_globals field set to anything reasonable.
649 | otherwise -- Add updated version numbers
650 = --pprTrace "completeIface" (ppr (dcl_tycl old_decls))
651 (final_iface, Just pp_diffs)
654 final_iface = new_iface { mi_version = new_version }
655 old_mod_vers = vers_module old_version
656 new_version = VersionInfo { vers_module = bumpVersion no_output_change old_mod_vers,
657 vers_exports = bumpVersion no_export_change (vers_exports old_version),
658 vers_rules = bumpVersion no_rule_change (vers_rules old_version),
659 vers_decls = tc_vers }
661 no_output_change = no_tc_change && no_rule_change && no_export_change && no_deprec_change
662 no_usage_change = mi_usages old_iface == mi_usages new_iface
664 no_export_change = mi_exports old_iface == mi_exports new_iface -- Kept sorted
665 no_rule_change = dcl_rules old_decls == dcl_rules new_decls -- Ditto
666 && dcl_insts old_decls == dcl_insts new_decls
667 no_deprec_change = old_deprecs == new_deprecs
669 -- Fill in the version number on the new declarations by looking at the old declarations.
670 -- Set the flag if anything changes.
671 -- Assumes that the decls are sorted by hsDeclName.
672 (no_tc_change, pp_tc_diffs, tc_vers) = diffDecls old_version old_fixities new_fixities
673 (dcl_tycl old_decls) (dcl_tycl new_decls)
674 pp_diffs = vcat [pp_tc_diffs,
675 pp_change no_export_change "Export list",
676 pp_change no_rule_change "Rules",
677 pp_change no_deprec_change "Deprecations",
678 pp_change no_usage_change "Usages"]
679 pp_change True what = empty
680 pp_change False what = text what <+> ptext SLIT("changed")
682 diffDecls :: VersionInfo -- Old version
683 -> FixityEnv -> FixityEnv -- Old and new fixities
684 -> [RenamedTyClDecl] -> [RenamedTyClDecl] -- Old and new decls
685 -> (Bool, -- True <=> no change
686 SDoc, -- Record of differences
687 NameEnv Version) -- New version map
689 diffDecls (VersionInfo { vers_module = old_mod_vers, vers_decls = old_decls_vers })
690 old_fixities new_fixities old new
691 = diff True empty emptyNameEnv old new
693 -- When seeing if two decls are the same,
694 -- remember to check whether any relevant fixity has changed
695 eq_tc d1 d2 = d1 == d2 && all (same_fixity . fst) (tyClDeclNames d1)
696 same_fixity n = lookupFixity old_fixities n == lookupFixity new_fixities n
698 diff ok_so_far pp new_vers [] [] = (ok_so_far, pp, new_vers)
699 diff ok_so_far pp new_vers (od:ods) [] = diff False (pp $$ only_old od) new_vers ods []
700 diff ok_so_far pp new_vers [] (nd:nds) = diff False (pp $$ only_new nd) new_vers_with_new [] nds
702 new_vers_with_new = extendNameEnv new_vers (tyClDeclName nd) (bumpVersion False old_mod_vers)
703 -- When adding a new item, start from the old module version
704 -- This way, if you have version 4 of f, then delete f, then add f again,
705 -- you'll get version 6 of f, which will (correctly) force recompilation of
708 diff ok_so_far pp new_vers (od:ods) (nd:nds)
709 = case od_name `compare` nd_name of
710 LT -> diff False (pp $$ only_old od) new_vers ods (nd:nds)
711 GT -> diff False (pp $$ only_new nd) new_vers (od:ods) nds
712 EQ | od `eq_tc` nd -> diff ok_so_far pp new_vers ods nds
713 | otherwise -> diff False (pp $$ changed od nd) new_vers_with_diff ods nds
715 od_name = tyClDeclName od
716 nd_name = tyClDeclName nd
717 new_vers_with_diff = extendNameEnv new_vers nd_name (bumpVersion False old_version)
718 old_version = lookupVersion old_decls_vers od_name
720 only_old d = ptext SLIT("Only in old iface:") <+> ppr d
721 only_new d = ptext SLIT("Only in new iface:") <+> ppr d
722 changed od nd = ptext SLIT("Changed in iface: ") <+> ((ptext SLIT("Old:") <+> ppr od) $$
723 (ptext SLIT("New:") <+> ppr nd))
727 b%************************************************************************
729 \subsection{Writing an interface file}
731 %************************************************************************
734 pprIface :: ModIface -> SDoc
736 = vcat [ ptext SLIT("__interface")
737 <+> doubleQuotes (ftext (mi_package iface))
738 <+> ppr (mi_module iface) <+> ppr (vers_module version_info)
740 <+> (if mi_orphan iface then char '!' else empty)
741 <+> int opt_HiVersion
742 <+> ptext SLIT("where")
744 , pprExports nameOccName (mi_exports iface)
745 , pprDeps (mi_deps iface)
746 , pprUsages nameOccName (mi_usages iface)
748 , pprFixities (mi_fixities iface) (dcl_tycl decls)
749 , pprIfaceDecls (vers_decls version_info) decls
750 , pprRulesAndDeprecs (dcl_rules decls) (mi_deprecs iface)
753 version_info = mi_version iface
754 decls = mi_decls iface
755 exp_vers = vers_exports version_info
757 rule_vers = vers_rules version_info
759 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
760 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
763 When printing export lists, we print like this:
765 AvailTC C [C, x, y] C(x,y)
766 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
769 pprExports :: Eq a => (a -> OccName) -> [(ModuleName, [GenAvailInfo a])] -> SDoc
770 pprExports getOcc exports = vcat (map (pprExport getOcc) exports)
772 pprExport :: Eq a => (a -> OccName) -> (ModuleName, [GenAvailInfo a]) -> SDoc
773 pprExport getOcc (mod, items)
774 = hsep [ ptext SLIT("__export "), ppr mod, hsep (map pp_avail items) ] <> semi
776 --pp_avail :: GenAvailInfo a -> SDoc
777 pp_avail (Avail name) = ppr (getOcc name)
778 pp_avail (AvailTC _ []) = empty
779 pp_avail (AvailTC n (n':ns))
780 | n==n' = ppr (getOcc n) <> pp_export ns
781 | otherwise = ppr (getOcc n) <> char '|' <> pp_export (n':ns)
784 pp_export names = braces (hsep (map (ppr.getOcc) names))
786 pprOcc :: Name -> SDoc -- Print the occurrence name only
787 pprOcc n = pprOccName (nameOccName n)
792 pprUsages :: (a -> OccName) -> [Usage a] -> SDoc
793 pprUsages getOcc usages = vcat (map (pprUsage getOcc) usages)
795 pprUsage :: (a -> OccName) -> Usage a -> SDoc
796 pprUsage getOcc usage
797 = hsep [ptext SLIT("import"), ppr (usg_name usage),
799 pp_export_version (usg_exports usage),
800 int (usg_rules usage),
801 pp_versions (usg_entities usage)
804 pp_versions nvs = hsep [ ppr (getOcc n) <+> int v | (n,v) <- nvs ]
806 pp_export_version Nothing = empty
807 pp_export_version (Just v) = int v
810 pprDeps :: Dependencies -> SDoc
811 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
812 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
813 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
814 ptext SLIT("orphans:") <+> fsep (map ppr orphs)
817 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
819 ppr_boot True = text "[boot]"
820 ppr_boot False = empty
824 pprIfaceDecls :: NameEnv Int -> IfaceDecls -> SDoc
825 pprIfaceDecls version_map decls
826 = vcat [ vcat [ppr i <+> semi | i <- dcl_insts decls]
827 , vcat (map ppr_decl (dcl_tycl decls))
830 ppr_decl d = ppr_vers d <+> ppr d <> semi
832 -- Print the version for the decl
833 ppr_vers d = case lookupNameEnv version_map (tyClDeclName d) of
839 pprFixities :: FixityEnv
842 pprFixities fixity_map decls
843 = hsep [ ppr fix <+> ppr n
844 | FixitySig n fix _ <- collectFixities fixity_map decls ] <> semi
846 -- Disgusting to print these two together, but that's
847 -- the way the interface parser currently expects them.
848 pprRulesAndDeprecs :: (Outputable a) => [a] -> Deprecations -> SDoc
849 pprRulesAndDeprecs [] NoDeprecs = empty
850 pprRulesAndDeprecs rules deprecs
851 = ptext SLIT("{-##") <+> (pp_rules rules $$ pp_deprecs deprecs) <+> ptext SLIT("##-}")
854 pp_rules rules = ptext SLIT("__R") <+> vcat (map ppr rules)
856 pp_deprecs NoDeprecs = empty
857 pp_deprecs deprecs = ptext SLIT("__D") <+> guts
859 guts = case deprecs of
860 DeprecAll txt -> doubleQuotes (ftext txt)
861 DeprecSome env -> ppr_deprec_env env
863 ppr_deprec_env :: NameEnv (Name, FastString) -> SDoc
864 ppr_deprec_env env = vcat (punctuate semi (map pp_deprec (nameEnvElts env)))
866 pp_deprec (name, txt) = pprOcc name <+> doubleQuotes (ftext txt)