2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
7 pprModIface, showIface, -- Print the iface in Foo.hi
9 mkUsageInfo, -- Construct the usage info for a module
11 mkIface, -- Build a ModIface from a ModGuts,
12 -- including computing version information
14 checkOldIface -- See if recompilation is required, by
15 -- comparing version information
19 -----------------------------------------------
20 MkIface.lhs deals with versioning
21 -----------------------------------------------
23 Here's the version-related info in an interface file
25 module Foo 8 -- module-version
26 3 -- export-list-version
28 Usages: -- Version info for what this compilation of Foo imported
29 Baz 3 -- Module version
30 [4] -- The export-list version if Foo depended on it
31 (g,2) -- Function and its version
32 (T,1) -- Type and its version
34 <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
35 -- The [2] says that f's unfolding
36 -- mentions verison 2 of Wib.t
38 -----------------------------------------------
40 -----------------------------------------------
43 * In the mi_usages information in an interface, we record the
44 version number of each free variable of the module
46 * In mkIface, we compute the version number of each exported thing A.f
47 by comparing its A.f's info with its new info, and bumping its
48 version number if it differs. If A.f mentions B.g, and B.g's version
49 number has changed, then we count A.f as having changed too.
51 * In checkOldIface we compare the mi_usages for the module with
52 the actual version info for all each thing recorded in mi_usages
57 We count A.f as changing if its fixity changes
61 If a rule changes, we want to recompile any module that might be
62 affected by that rule. For non-orphan rules, this is relatively easy.
63 If module M defines f, and a rule for f, just arrange that the version
64 number for M.f changes if any of the rules for M.f change. Any module
65 that does not depend on M.f can't be affected by the rule-change
68 Orphan rules (ones whose 'head function' is not defined in M) are
69 harder. Here's what we do.
71 * We have a per-module orphan-rule version number which changes if
72 any orphan rule changes. (It's unaffected by non-orphan rules.)
74 * We record usage info for any orphan module 'below' this one,
75 giving the orphan-rule version number. We recompile if this
78 The net effect is that if an orphan rule changes, we recompile every
79 module above it. That's very conservative, but it's devilishly hard
80 to know what it might affect, so we just have to be conservative.
84 In an iface file we have
86 instance Eq a => Eq [a] = dfun29
89 We have a version number for dfun29, covering its unfolding
90 etc. Suppose we are compiling a module M that imports A only
91 indirectly. If typechecking M uses this instance decl, we record the
92 dependency on A.dfun29 as if it were a free variable of the module
93 (via the tcg_inst_usages accumulator). That means that A will appear
94 in M's usage list. If the shape of the instance declaration changes,
95 then so will dfun29's version, triggering a recompilation.
97 Adding an instance declaration, or changing an instance decl that is
98 not currently used, is more tricky. (This really only makes a
99 difference when we have overlapping instance decls, because then the
100 new instance decl might kick in to override the old one.) We handle
101 this in a very similar way that we handle rules above.
103 * For non-orphan instance decls, identify one locally-defined tycon/class
104 mentioned in the decl. Treat the instance decl as part of the defn of that
105 tycon/class, so that if the shape of the instance decl changes, so does the
106 tycon/class; that in turn will force recompilation of anything that uses
109 * For orphan instance decls, act the same way as for orphan rules.
110 Indeed, we use the same global orphan-rule version number.
114 mkUsageInfo figures out what the ``usage information'' for this
115 moudule is; that is, what it must record in its interface file as the
118 We produce a line for every module B below the module, A, currently being
121 to record the fact that A does import B indirectly. This is used to decide
122 to look to look for B.hi rather than B.hi-boot when compiling a module that
123 imports A. This line says that A imports B, but uses nothing in it.
124 So we'll get an early bale-out when compiling A if B's version changes.
126 The usage information records:
129 \item (a) anything reachable from its body code
130 \item (b) any module exported with a @module Foo@
131 \item (c) anything reachable from an exported item
134 Why (b)? Because if @Foo@ changes then this module's export list
135 will change, so we must recompile this module at least as far as
136 making a new interface file --- but in practice that means complete
139 Why (c)? Consider this:
141 module A( f, g ) where | module B( f ) where
142 import B( f ) | f = h 3
146 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
147 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
148 *identical* to what it was before. If anything about @B.f@ changes
149 than anyone who imports @A@ should be recompiled in case they use
150 @B.f@ (they'll get an early exit if they don't). So, if anything
151 about @B.f@ changes we'd better make sure that something in A.hi
152 changes, and the convenient way to do that is to record the version
153 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
154 complete recompiation of A, which is overkill but it's the only way to
155 write a new, slightly different, A.hi.
157 But the example is tricker. Even if @B.f@ doesn't change at all,
158 @B.h@ may do so, and this change may not be reflected in @f@'s version
159 number. But with -O, a module that imports A must be recompiled if
160 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
161 the occurrence of @B.f@ in the export list *just as if* it were in the
162 code of A, and thereby haul in all the stuff reachable from it.
164 *** Conclusion: if A mentions B.f in its export list,
165 behave just as if A mentioned B.f in its source code,
166 and slurp in B.f and all its transitive closure ***
168 [NB: If B was compiled with -O, but A isn't, we should really *still*
169 haul in all the unfoldings for B, in case the module that imports A *is*
170 compiled with -O. I think this is the case.]
174 #include "HsVersions.h"
177 import Packages ( isHomeModule, PackageIdH(..) )
178 import IfaceSyn ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..),
179 IfaceRule(..), IfaceInst(..), IfaceExtName(..), IfaceTyCon(..),
180 eqIfDecl, eqIfRule, eqIfInst, IfaceEq(..), (&&&), bool,
181 eqMaybeBy, eqListBy, visibleIfConDecls,
182 tyThingToIfaceDecl, dfunToIfaceInst, coreRuleToIfaceRule )
183 import LoadIface ( readIface, loadInterface, ifaceInstGates )
184 import BasicTypes ( Version, initialVersion, bumpVersion )
186 import TcRnTypes ( mkModDeps )
187 import TcType ( isFFITy )
188 import HscTypes ( ModIface(..), TyThing(..),
189 ModGuts(..), ModGuts, IfaceExport,
190 GhciMode(..), HscEnv(..), hscEPS,
191 Dependencies(..), FixItem(..),
192 ModSummary(..), msHiFilePath,
193 mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
195 GenAvailInfo(..), availName,
196 ExternalPackageState(..),
197 Usage(..), IsBootInterface,
198 Deprecs(..), IfaceDeprecs, Deprecations,
204 import Name ( Name, nameModule, nameOccName, nameParent,
205 isExternalName, nameParent_maybe, isWiredInName,
209 import OccName ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
211 OccSet, emptyOccSet, elemOccSet, occSetElts,
212 extendOccSet, extendOccSetList,
213 isEmptyOccSet, intersectOccSet, intersectsOccSet,
215 import TyCon ( tyConDataCons, isNewTyCon, newTyConRep )
216 import Class ( classSelIds )
217 import DataCon ( dataConName, dataConFieldLabels )
218 import Module ( Module, moduleFS,
219 ModLocation(..), mkSysModuleFS, moduleUserString,
220 ModuleEnv, emptyModuleEnv, lookupModuleEnv,
224 import DriverUtil ( createDirectoryHierarchy, directoryOf )
225 import Util ( sortLe, seqList )
226 import Binary ( getBinFileWithDict )
227 import BinIface ( writeBinIface, v_IgnoreHiWay )
228 import Unique ( Unique, Uniquable(..) )
229 import ErrUtils ( dumpIfSet_dyn, showPass )
230 import Digraph ( stronglyConnComp, SCC(..) )
231 import SrcLoc ( SrcSpan )
235 import DATA_IOREF ( writeIORef )
236 import Monad ( when )
237 import List ( insert )
238 import Maybes ( orElse, mapCatMaybes, isNothing, isJust,
239 fromJust, expectJust, MaybeErr(..) )
244 %************************************************************************
246 \subsection{Completing an interface}
248 %************************************************************************
253 -> Maybe ModIface -- The old interface, if we have it
254 -> ModGuts -- The compiled, tidied module
255 -> IO ModIface -- The new one, complete with decls and versions
257 -- a) Builds the ModIface
258 -- b) Writes it out to a file if necessary
260 mkIface hsc_env location maybe_old_iface
261 guts@ModGuts{ mg_module = this_mod,
265 mg_exports = exports,
266 mg_fix_env = fix_env,
267 mg_deprecs = src_deprecs,
270 mg_types = type_env }
271 = do { eps <- hscEPS hsc_env
272 ; let { ext_nm_rhs = mkExtNameFn hsc_env eps this_mod
273 ; ext_nm_lhs = mkLhsNameFn this_mod
274 ; local_things = [thing | thing <- typeEnvElts type_env,
275 not (isWiredInName (getName thing)) ]
276 -- Do not export anything about wired-in things
277 -- (GHC knows about them already)
279 ; abstract_tcs :: NameSet -- TyCons and Classes whose representation is not exposed
281 | not omit_prags = emptyNameSet -- In the -O case, nothing is abstract
282 | otherwise = mkNameSet [ getName thing
283 | thing <- local_things
284 , not (mustExposeThing exports thing)]
286 ; decls = [ tyThingToIfaceDecl omit_prags abstract_tcs ext_nm_rhs thing
287 | thing <- local_things, wantDeclFor exports abstract_tcs thing ]
288 -- Don't put implicit Ids and class tycons in the interface file
290 ; fixities = [(occ,fix) | FixItem occ fix _ <- nameEnvElts fix_env]
291 ; deprecs = mkIfaceDeprec src_deprecs
294 | otherwise = sortLe le_rule $
295 map (coreRuleToIfaceRule ext_nm_lhs ext_nm_rhs) rules
296 ; iface_insts = sortLe le_inst (map (dfunToIfaceInst ext_nm_lhs) insts)
298 ; intermediate_iface = ModIface {
299 mi_module = this_mod,
300 mi_package = HomePackage,
304 mi_exports = mkIfaceExports exports,
305 mi_insts = iface_insts,
306 mi_rules = iface_rules,
307 mi_fixities = fixities,
308 mi_deprecs = deprecs,
310 -- Left out deliberately: filled in by addVersionInfo
311 mi_mod_vers = initialVersion,
312 mi_exp_vers = initialVersion,
313 mi_rule_vers = initialVersion,
314 mi_orphan = False, -- Always set by addVersionInfo, but
315 -- it's a strict field, so we can't omit it.
316 mi_decls = deliberatelyOmitted "decls",
317 mi_ver_fn = deliberatelyOmitted "ver_fn",
319 -- And build the cached values
320 mi_dep_fn = mkIfaceDepCache deprecs,
321 mi_fix_fn = mkIfaceFixCache fixities }
323 -- Add version information
324 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs)
325 = _scc_ "versioninfo"
326 addVersionInfo maybe_old_iface intermediate_iface decls
329 -- Write the interface file, if necessary
330 ; when (not no_change_at_all && ghci_mode /= Interactive) $ do
331 createDirectoryHierarchy (directoryOf hi_file_path)
332 writeBinIface hi_file_path new_iface
335 ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags)
336 (printDump (fromJust pp_orphs))
337 ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
338 ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
339 (pprModIface new_iface)
343 r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
344 i1 `le_inst` i2 = ifDFun i1 <= ifDFun i2
346 dflags = hsc_dflags hsc_env
347 ghci_mode = hsc_mode hsc_env
348 omit_prags = dopt Opt_OmitInterfacePragmas dflags
349 hi_file_path = ml_hi_file location
352 mustExposeThing :: NameSet -> TyThing -> Bool
353 -- We are compiling without -O, and thus trying to write as little as
354 -- possible into the interface file. But we must expose the details of
355 -- any data types and classes whose constructors, fields, methods are
356 -- visible to an importing module
357 mustExposeThing exports (ATyCon tc)
358 = any exported_data_con (tyConDataCons tc)
359 -- Expose rep if any datacon or field is exported
361 || (isNewTyCon tc && isFFITy (snd (newTyConRep tc)))
362 -- Expose the rep for newtypes if the rep is an FFI type.
363 -- For a very annoying reason. 'Foreign import' is meant to
364 -- be able to look through newtypes transparently, but it
365 -- can only do that if it can "see" the newtype representation
367 exported_data_con con
368 = any (`elemNameSet` exports) (dataConName con : dataConFieldLabels con)
370 mustExposeThing exports (AClass cls)
371 = any exported_class_op (classSelIds cls)
372 where -- Expose rep if any classs op is exported
373 exported_class_op op = getName op `elemNameSet` exports
375 mustExposeThing exports other = False
378 wantDeclFor :: NameSet -- User-exported things
379 -> NameSet -- Abstract things
381 wantDeclFor exports abstracts thing
382 | Just parent <- nameParent_maybe name -- An implicit thing
383 = parent `elemNameSet` abstracts && name `elemNameSet` exports
390 deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
392 -----------------------------
393 mkExtNameFn :: HscEnv -> ExternalPackageState -> Module -> Name -> IfaceExtName
394 mkExtNameFn hsc_env eps this_mod
397 dflags = hsc_dflags hsc_env
398 hpt = hsc_HPT hsc_env
402 | mod == this_mod = case nameParent_maybe name of
403 Nothing -> LocalTop occ
404 Just par -> LocalTopSub occ (nameOccName par)
405 | isWiredInName name = ExtPkg mod occ
406 | isHomeModule dflags mod = HomePkg mod occ vers
407 | otherwise = ExtPkg mod occ
409 mod = nameModule name
410 occ = nameOccName name
411 par_occ = nameOccName (nameParent name)
412 -- The version of the *parent* is the one want
413 vers = lookupVersion mod par_occ
415 lookupVersion :: Module -> OccName -> Version
416 -- Even though we're looking up a home-package thing, in
417 -- one-shot mode the imported interfaces may be in the PIT
418 lookupVersion mod occ
419 = mi_ver_fn iface occ `orElse`
420 pprPanic "lookupVers1" (ppr mod <+> ppr occ)
422 iface = lookupIfaceByModule hpt pit mod `orElse`
423 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
426 ---------------------
427 -- mkLhsNameFn ignores versioning info altogether
428 -- It is used for the LHS of instance decls and rules, where we
429 -- there's no point in recording version info
430 mkLhsNameFn :: Module -> Name -> IfaceExtName
431 mkLhsNameFn this_mod name
432 | mod == this_mod = LocalTop occ
433 | otherwise = ExtPkg mod occ
435 mod = nameModule name
436 occ = nameOccName name
439 -----------------------------
440 -- Compute version numbers for local decls
442 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
443 -> ModIface -- The new interface decls (lacking decls)
444 -> [IfaceDecl] -- The new decls
446 Bool, -- True <=> no changes at all; no need to write new Iface
448 Maybe SDoc) -- Warnings about orphans
450 addVersionInfo Nothing new_iface new_decls
451 -- No old interface, so definitely write a new one!
452 = (new_iface { mi_orphan = anyNothing getInstKey (mi_insts new_iface)
453 || anyNothing getRuleKey (mi_rules new_iface),
454 mi_decls = [(initialVersion, decl) | decl <- new_decls],
455 mi_ver_fn = \n -> Just initialVersion },
457 ptext SLIT("No old interface file"),
458 pprOrphans orph_insts orph_rules)
460 orph_insts = filter (isNothing . getInstKey) (mi_insts new_iface)
461 orph_rules = filter (isNothing . getRuleKey) (mi_rules new_iface)
463 addVersionInfo (Just old_iface@(ModIface { mi_mod_vers = old_mod_vers,
464 mi_exp_vers = old_exp_vers,
465 mi_rule_vers = old_rule_vers,
466 mi_decls = old_decls,
467 mi_ver_fn = old_decl_vers,
468 mi_fix_fn = old_fixities }))
469 new_iface@(ModIface { mi_fix_fn = new_fixities })
472 | no_change_at_all = (old_iface, True, ptext SLIT("Interface file unchanged"), pp_orphs)
473 | otherwise = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
474 nest 2 pp_diffs], pp_orphs)
476 final_iface = new_iface { mi_mod_vers = bump_unless no_output_change old_mod_vers,
477 mi_exp_vers = bump_unless no_export_change old_exp_vers,
478 mi_rule_vers = bump_unless no_rule_change old_rule_vers,
479 mi_orphan = not (null new_orph_rules && null new_orph_insts),
480 mi_decls = decls_w_vers,
481 mi_ver_fn = mkIfaceVerCache decls_w_vers }
483 decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
486 (old_non_orph_insts, old_orph_insts) = mkRuleMap getInstKey (mi_insts old_iface)
487 (new_non_orph_insts, new_orph_insts) = mkRuleMap getInstKey (mi_insts new_iface)
488 same_insts occ = eqMaybeBy (eqListBy eqIfInst)
489 (lookupOccEnv old_non_orph_insts occ)
490 (lookupOccEnv new_non_orph_insts occ)
492 (old_non_orph_rules, old_orph_rules) = mkRuleMap getRuleKey (mi_rules old_iface)
493 (new_non_orph_rules, new_orph_rules) = mkRuleMap getRuleKey (mi_rules new_iface)
494 same_rules occ = eqMaybeBy (eqListBy eqIfRule)
495 (lookupOccEnv old_non_orph_rules occ)
496 (lookupOccEnv new_non_orph_rules occ)
498 -- Computing what changed
499 no_output_change = no_decl_change && no_rule_change &&
500 no_export_change && no_deprec_change
501 no_export_change = mi_exports new_iface == mi_exports old_iface -- Kept sorted
502 no_decl_change = isEmptyOccSet changed_occs
503 no_rule_change = not (changedWrt changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
504 || changedWrt changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
505 no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
507 -- If the usages havn't changed either, we don't need to write the interface file
508 no_other_changes = mi_usages new_iface == mi_usages old_iface &&
509 mi_deps new_iface == mi_deps old_iface
510 no_change_at_all = no_output_change && no_other_changes
512 pp_diffs = vcat [pp_change no_export_change "Export list"
513 (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
514 pp_change no_rule_change "Rules"
515 (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
516 pp_change no_deprec_change "Deprecations" empty,
517 pp_change no_other_changes "Usages" empty,
519 pp_change True what info = empty
520 pp_change False what info = text what <+> ptext SLIT("changed") <+> info
523 old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
524 same_fixity n = bool (old_fixities n == new_fixities n)
527 -- Adding version info
528 new_version = bumpVersion old_mod_vers
529 add_vers decl | occ `elemOccSet` changed_occs = new_version
530 | otherwise = expectJust "add_vers" (old_decl_vers occ)
531 -- If it's unchanged, there jolly well
532 where -- should be an old version number
536 changed_occs :: OccSet
537 changed_occs = computeChangedOccs eq_info
539 eq_info :: [(OccName, IfaceEq)]
540 eq_info = map check_eq new_decls
541 check_eq new_decl | Just old_decl <- lookupOccEnv old_decl_env occ
542 = (occ, new_decl `eqIfDecl` old_decl &&&
543 eq_indirects new_decl)
544 | otherwise {- No corresponding old decl -}
547 occ = ifName new_decl
549 eq_indirects :: IfaceDecl -> IfaceEq
550 -- When seeing if two decls are the same, remember to
551 -- check whether any relevant fixity or rules have changed
552 eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
553 eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
554 = same_insts cls_occ &&&
555 eq_ind_occs [op | IfaceClassOp op _ _ <- sigs]
556 eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
557 = same_insts tc_occ &&& same_fixity tc_occ &&& -- The TyCon can have a fixity too
558 eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
559 eq_indirects other = Equal -- Synonyms and foreign declarations
561 eq_ind_occ :: OccName -> IfaceEq -- For class ops and Ids; check fixity and rules
562 eq_ind_occ occ = same_fixity occ &&& same_rules occ
563 eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal
567 pp_decl_diffs :: SDoc -- Nothing => no changes
569 | isEmptyOccSet changed_occs = empty
571 = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
572 ptext SLIT("Version change for these decls:"),
573 nest 2 (vcat (map show_change new_decls))]
575 eq_env = mkOccEnv eq_info
577 | not (occ `elemOccSet` changed_occs) = empty
579 = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version,
582 occ = ifName new_decl
583 why = case lookupOccEnv eq_env occ of
584 Just (EqBut occs) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
585 nest 2 (braces (fsep (map ppr (occSetElts
586 (occs `intersectOccSet` changed_occs)))))]
588 | Just old_decl <- lookupOccEnv old_decl_env occ
589 -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
590 ptext SLIT("New:") <+> ppr new_decl]
592 -> ppr occ <+> ptext SLIT("only in new interface")
593 other -> pprPanic "MkIface.show_change" (ppr occ)
595 pp_orphs = pprOrphans new_orph_insts new_orph_rules
597 pprOrphans insts rules
598 | null insts && null rules = Nothing
601 if null insts then empty else
602 hang (ptext SLIT("Warning: orphan instances:"))
603 2 (vcat (map ppr insts)),
604 if null rules then empty else
605 hang (ptext SLIT("Warning: orphan rules:"))
606 2 (vcat (map ppr rules))
609 computeChangedOccs :: [(OccName, IfaceEq)] -> OccSet
610 computeChangedOccs eq_info
611 = foldl add_changes emptyOccSet (stronglyConnComp edges)
613 edges :: [((OccName,IfaceEq), Unique, [Unique])]
614 edges = [ (node, getUnique occ, map getUnique occs)
615 | node@(occ, iface_eq) <- eq_info
616 , let occs = case iface_eq of
617 EqBut occ_set -> occSetElts occ_set
620 -- Changes in declarations
621 add_changes :: OccSet -> SCC (OccName, IfaceEq) -> OccSet
622 add_changes so_far (AcyclicSCC (occ, iface_eq))
623 | changedWrt so_far iface_eq -- This one has changed
624 = extendOccSet so_far occ
625 add_changes so_far (CyclicSCC pairs)
626 | changedWrt so_far (foldr1 (&&&) (map snd pairs)) -- One of this group has changed
627 = extendOccSetList so_far (map fst pairs)
628 add_changes so_far other = so_far
630 changedWrt :: OccSet -> IfaceEq -> Bool
631 changedWrt so_far Equal = False
632 changedWrt so_far NotEqual = True
633 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
635 ----------------------
636 -- mkRuleMap partitions instance decls or rules into
637 -- (a) an OccEnv for ones that are not orphans,
638 -- mapping the local OccName to a list of its decls
639 -- (b) a list of orphan decls
640 mkRuleMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
641 -- Nothing for an orphan decl
642 -> [decl] -- Sorted into canonical order
643 -> (OccEnv [decl], -- Non-orphan decls associated with their key;
644 -- each sublist in canonical order
645 [decl]) -- Orphan decls; in canonical order
646 mkRuleMap get_key decls
647 = foldl go (emptyOccEnv, []) decls
649 go (non_orphs, orphs) d
650 | Just occ <- get_key d
651 = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
652 | otherwise = (non_orphs, d:orphs)
654 -- getXxKey: find at least one local OccName that belongs to this decl
656 getInstKey :: IfaceInst -> Maybe OccName
657 getInstKey (IfaceInst {ifInstHead = inst_ty})
658 = case [occ | LocalTop occ <- cls_ext : tc_exts] of
662 (cls_ext, tcs) = ifaceInstGates inst_ty
663 tc_exts = [tc | IfaceTc tc <- tcs]
664 -- Ignore the wired-in IfaceTyCons; the class will do as the key
666 getRuleKey :: IfaceRule -> Maybe OccName
667 getRuleKey (IfaceRule {ifRuleHead = LocalTop occ}) = Just occ
668 getRuleKey other = Nothing
670 anyNothing :: (a -> Maybe b) -> [a] -> Bool
671 anyNothing p [] = False
672 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
674 ----------------------
675 mkIfaceDeprec :: Deprecations -> IfaceDeprecs
676 mkIfaceDeprec NoDeprecs = NoDeprecs
677 mkIfaceDeprec (DeprecAll t) = DeprecAll t
678 mkIfaceDeprec (DeprecSome env) = DeprecSome (sortLe (<=) (nameEnvElts env))
680 ----------------------
681 bump_unless :: Bool -> Version -> Version
682 bump_unless True v = v -- True <=> no change
683 bump_unless False v = bumpVersion v
687 %*********************************************************
689 \subsection{Keeping track of what we've slurped, and version numbers}
691 %*********************************************************
695 mkUsageInfo :: HscEnv
696 -> ModuleEnv (Module, Maybe Bool, SrcSpan)
697 -> [(Module, IsBootInterface)]
698 -> NameSet -> IO [Usage]
699 mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
700 = do { eps <- hscEPS hsc_env
701 ; let usages = mk_usage_info (eps_PIT eps) hsc_env
702 dir_imp_mods dep_mods used_names
703 ; usages `seqList` return usages }
704 -- seq the list of Usages returned: occasionally these
705 -- don't get evaluated for a while and we can end up hanging on to
706 -- the entire collection of Ifaces.
708 mk_usage_info pit hsc_env dir_imp_mods dep_mods proto_used_names
709 = mapCatMaybes mkUsage dep_mods
710 -- ToDo: do we need to sort into canonical order?
712 dflags = hsc_dflags hsc_env
713 hpt = hsc_HPT hsc_env
715 used_names = mkNameSet $ -- Eliminate duplicates
716 [ nameParent n -- Just record usage on the 'main' names
717 | n <- nameSetToList proto_used_names
718 , not (isWiredInName n) -- Don't record usages for wired-in names
719 , isExternalName n -- Ignore internal names
722 -- ent_map groups together all the things imported and used
723 -- from a particular module in this package
724 ent_map :: ModuleEnv [OccName]
725 ent_map = foldNameSet add_mv emptyModuleEnv used_names
726 add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [occ]
728 occ = nameOccName name
729 mod = nameModule name
730 add_item occs _ = occ:occs
732 import_all mod = case lookupModuleEnv dir_imp_mods mod of
733 Just (_,imp_all,_) -> isNothing imp_all
736 -- We want to create a Usage for a home module if
737 -- a) we used something from; has something in used_names
738 -- b) we imported all of it, even if we used nothing from it
739 -- (need to recompile if its export list changes: export_vers)
740 -- c) is a home-package orphan module (need to recompile if its
741 -- instance decls change: rules_vers)
742 mkUsage :: (Module, Bool) -> Maybe Usage
743 mkUsage (mod_name, _)
744 | isNothing maybe_iface -- We can't depend on it if we didn't
745 || not (isHomeModule dflags mod) -- even open the interface!
749 = Nothing -- Record no usage info
752 = Just (Usage { usg_name = mod,
754 usg_exports = export_vers,
755 usg_entities = ent_vers,
756 usg_rules = rules_vers })
758 maybe_iface = lookupIfaceByModule hpt pit mod_name
759 -- In one-shot mode, the interfaces for home-package
760 -- modules accumulate in the PIT not HPT. Sigh.
762 Just iface = maybe_iface
763 mod = mi_module iface
764 orphan_mod = mi_orphan iface
765 version_env = mi_ver_fn iface
766 mod_vers = mi_mod_vers iface
767 rules_vers = mi_rule_vers iface
768 all_imported = import_all mod
769 export_vers | all_imported = Just (mi_exp_vers iface)
770 | otherwise = Nothing
772 -- The sort is to put them into canonical order
773 used_occs = lookupModuleEnv ent_map mod `orElse` []
774 ent_vers :: [(OccName,Version)]
775 ent_vers = [ (occ, version_env occ `orElse` initialVersion)
776 | occ <- sortLe (<=) used_occs]
780 mkIfaceExports :: NameSet -> [(Module, [GenAvailInfo OccName])]
781 -- Group by module and sort by occurrence
782 -- This keeps the list in canonical order
783 mkIfaceExports exports
784 = [ (mkSysModuleFS fs, eltsFM avails)
785 | (fs, avails) <- fmToList groupFM
788 groupFM :: FiniteMap FastString (FiniteMap FastString (GenAvailInfo OccName))
789 -- Deliberately use the FastString so we
790 -- get a canonical ordering
791 groupFM = foldl add emptyFM (nameSetToList exports)
793 add env name = addToFM_C add_avail env mod_fs
794 (unitFM avail_fs avail)
796 occ = nameOccName name
797 mod_fs = moduleFS (nameModule name)
798 avail | Just p <- nameParent_maybe name = AvailTC (nameOccName p) [occ]
799 | isTcOcc occ = AvailTC occ [occ]
800 | otherwise = Avail occ
801 avail_fs = occNameFS (availName avail)
802 add_avail avail_fm _ = addToFM_C add_item avail_fm avail_fs avail
804 add_item (AvailTC p occs) _ = AvailTC p (List.insert occ occs)
805 add_item (Avail n) _ = pprPanic "MkIface.addAvail" (ppr n <+> ppr name)
809 %************************************************************************
811 Load the old interface file for this module (unless
812 we have it aleady), and check whether it is up to date
815 %************************************************************************
818 checkOldIface :: HscEnv
820 -> Bool -- Source unchanged
821 -> Maybe ModIface -- Old interface from compilation manager, if any
822 -> IO (RecompileRequired, Maybe ModIface)
824 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
825 = do { showPass (hsc_dflags hsc_env)
826 ("Checking old interface for " ++ moduleUserString (ms_mod mod_summary)) ;
828 ; initIfaceCheck hsc_env $
829 check_old_iface mod_summary source_unchanged maybe_iface
832 check_old_iface mod_summary source_unchanged maybe_iface
833 = -- CHECK WHETHER THE SOURCE HAS CHANGED
834 ifM (not source_unchanged)
835 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
838 -- If the source has changed and we're in interactive mode, avoid reading
839 -- an interface; just return the one we might have been supplied with.
840 getGhciMode `thenM` \ ghci_mode ->
841 if (ghci_mode == Interactive) && not source_unchanged then
842 returnM (outOfDate, maybe_iface)
845 case maybe_iface of {
846 Just old_iface -> -- Use the one we already have
847 checkVersions source_unchanged old_iface `thenM` \ recomp ->
848 returnM (recomp, Just old_iface)
852 -- Try and read the old interface for the current module
853 -- from the .hi file left from the last time we compiled it
855 iface_path = msHiFilePath mod_summary
857 readIface (ms_mod mod_summary) iface_path False `thenM` \ read_result ->
858 case read_result of {
859 Failed err -> -- Old interface file not found, or garbled; give up
860 traceIf (text "FYI: cannot read old interface file:"
861 $$ nest 4 err) `thenM_`
862 returnM (outOfDate, Nothing)
866 -- We have got the old iface; check its versions
867 checkVersions source_unchanged iface `thenM` \ recomp ->
868 returnM (recomp, Just iface)
872 @recompileRequired@ is called from the HscMain. It checks whether
873 a recompilation is required. It needs access to the persistent state,
874 finder, etc, because it may have to load lots of interface files to
875 check their versions.
878 type RecompileRequired = Bool
879 upToDate = False -- Recompile not required
880 outOfDate = True -- Recompile required
882 checkVersions :: Bool -- True <=> source unchanged
883 -> ModIface -- Old interface
884 -> IfG RecompileRequired
885 checkVersions source_unchanged iface
886 | not source_unchanged
889 = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
890 ppr (mi_module iface) <> colon)
892 -- Source code unchanged and no errors yet... carry on
894 -- First put the dependent-module info, read from the old interface, into the envt,
895 -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
897 -- It's just temporary because either the usage check will succeed
898 -- (in which case we are done with this module) or it'll fail (in which
899 -- case we'll compile the module from scratch anyhow).
901 -- We do this regardless of compilation mode
902 ; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
904 ; checkList [checkModUsage u | u <- mi_usages iface]
907 -- This is a bit of a hack really
908 mod_deps :: ModuleEnv (Module, IsBootInterface)
909 mod_deps = mkModDeps (dep_mods (mi_deps iface))
911 checkModUsage :: Usage -> IfG RecompileRequired
912 -- Given the usage information extracted from the old
913 -- M.hi file for the module being compiled, figure out
914 -- whether M needs to be recompiled.
916 checkModUsage (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
917 usg_rules = old_rule_vers,
918 usg_exports = maybe_old_export_vers,
919 usg_entities = old_decl_vers })
920 = -- Load the imported interface is possible
922 doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
924 traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
926 loadInterface doc_str mod_name ImportBySystem `thenM` \ mb_iface ->
927 -- Load the interface, but don't complain on failure;
928 -- Instead, get an Either back which we can test
931 Failed exn -> (out_of_date (sep [ptext SLIT("Can't find version number for module"),
933 -- Couldn't find or parse a module mentioned in the
934 -- old interface file. Don't complain -- it might just be that
935 -- the current module doesn't need that import and it's been deleted
939 new_mod_vers = mi_mod_vers iface
940 new_decl_vers = mi_ver_fn iface
941 new_export_vers = mi_exp_vers iface
942 new_rule_vers = mi_rule_vers iface
945 checkModuleVersion old_mod_vers new_mod_vers `thenM` \ recompile ->
946 if not recompile then
951 if checkExportList maybe_old_export_vers new_export_vers then
952 out_of_date_vers (ptext SLIT(" Export list changed"))
953 (fromJust maybe_old_export_vers)
958 if old_rule_vers /= new_rule_vers then
959 out_of_date_vers (ptext SLIT(" Rules changed"))
960 old_rule_vers new_rule_vers
963 -- CHECK ITEMS ONE BY ONE
964 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] `thenM` \ recompile ->
966 returnM outOfDate -- This one failed, so just bail out now
968 up_to_date (ptext SLIT(" Great! The bits I use are up to date"))
971 ------------------------
972 checkModuleVersion old_mod_vers new_mod_vers
973 | new_mod_vers == old_mod_vers
974 = up_to_date (ptext SLIT("Module version unchanged"))
977 = out_of_date_vers (ptext SLIT(" Module version has changed"))
978 old_mod_vers new_mod_vers
980 ------------------------
981 checkExportList Nothing new_vers = upToDate
982 checkExportList (Just v) new_vers = v /= new_vers
984 ------------------------
985 checkEntityUsage new_vers (name,old_vers)
986 = case new_vers name of
988 Nothing -> -- We used it before, but it ain't there now
989 out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
991 Just new_vers -- It's there, but is it up to date?
992 | new_vers == old_vers -> traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
994 | otherwise -> out_of_date_vers (ptext SLIT(" Out of date:") <+> ppr name)
997 up_to_date msg = traceHiDiffs msg `thenM_` returnM upToDate
998 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
999 out_of_date_vers msg old_vers new_vers
1000 = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
1002 ----------------------
1003 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
1004 -- This helper is used in two places
1005 checkList [] = returnM upToDate
1006 checkList (check:checks) = check `thenM` \ recompile ->
1013 %************************************************************************
1017 %************************************************************************
1020 showIface :: FilePath -> IO ()
1021 -- Raad binary interface, and print it out
1022 showIface filename = do
1023 -- skip the version check; we don't want to worry about profiled vs.
1024 -- non-profiled interfaces, for example.
1025 writeIORef v_IgnoreHiWay True
1026 iface <- Binary.getBinFileWithDict filename
1027 printDump (pprModIface iface)
1033 pprModIface :: ModIface -> SDoc
1036 = vcat [ ptext SLIT("interface")
1037 <+> ppr_package (mi_package iface)
1038 <+> ppr (mi_module iface) <+> pp_boot
1039 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
1040 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
1041 <+> int opt_HiVersion
1042 <+> ptext SLIT("where")
1043 , vcat (map pprExport (mi_exports iface))
1044 , pprDeps (mi_deps iface)
1045 , vcat (map pprUsage (mi_usages iface))
1046 , pprFixities (mi_fixities iface)
1047 , vcat (map pprIfaceDecl (mi_decls iface))
1048 , vcat (map ppr (mi_insts iface))
1049 , vcat (map ppr (mi_rules iface))
1050 , pprDeprecs (mi_deprecs iface)
1053 pp_boot | mi_boot iface = ptext SLIT("[boot]")
1055 ppr_package HomePackage = empty
1056 ppr_package (ExtPackage id) = doubleQuotes (ppr id)
1058 exp_vers = mi_exp_vers iface
1059 rule_vers = mi_rule_vers iface
1061 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
1062 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
1065 When printing export lists, we print like this:
1067 AvailTC C [C, x, y] C(x,y)
1068 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
1071 pprExport :: IfaceExport -> SDoc
1072 pprExport (mod, items)
1073 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
1075 pp_avail :: GenAvailInfo OccName -> SDoc
1076 pp_avail (Avail occ) = ppr occ
1077 pp_avail (AvailTC _ []) = empty
1078 pp_avail (AvailTC n (n':ns))
1079 | n==n' = ppr n <> pp_export ns
1080 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
1082 pp_export [] = empty
1083 pp_export names = braces (hsep (map ppr names))
1085 pprUsage :: Usage -> SDoc
1087 = hsep [ptext SLIT("import"), ppr (usg_name usage),
1088 int (usg_mod usage),
1089 pp_export_version (usg_exports usage),
1090 int (usg_rules usage),
1091 pp_versions (usg_entities usage) ]
1093 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
1094 pp_export_version Nothing = empty
1095 pp_export_version (Just v) = int v
1097 pprDeps :: Dependencies -> SDoc
1098 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
1099 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
1100 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
1101 ptext SLIT("orphans:") <+> fsep (map ppr orphs)
1104 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
1105 ppr_boot True = text "[boot]"
1106 ppr_boot False = empty
1108 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
1109 pprIfaceDecl (ver, decl)
1110 = ppr_vers ver <+> ppr decl
1112 -- Print the version for the decl
1113 ppr_vers v | v == initialVersion = empty
1116 pprFixities :: [(OccName, Fixity)] -> SDoc
1117 pprFixities [] = empty
1118 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
1120 pprFix (occ,fix) = ppr fix <+> ppr occ
1122 pprDeprecs NoDeprecs = empty
1123 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
1124 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
1126 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)