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 writeIfaceFile, -- Write the interface file
16 checkOldIface -- See if recompilation is required, by
17 -- comparing version information
21 -----------------------------------------------
22 MkIface.lhs deals with versioning
23 -----------------------------------------------
25 Here's the version-related info in an interface file
27 module Foo 8 -- module-version
28 3 -- export-list-version
30 Usages: -- Version info for what this compilation of Foo imported
31 Baz 3 -- Module version
32 [4] -- The export-list version if Foo depended on it
33 (g,2) -- Function and its version
34 (T,1) -- Type and its version
36 <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
37 -- The [2] says that f's unfolding
38 -- mentions verison 2 of Wib.t
40 -----------------------------------------------
42 -----------------------------------------------
45 * In the mi_usages information in an interface, we record the
46 version number of each free variable of the module
48 * In mkIface, we compute the version number of each exported thing A.f
49 by comparing its A.f's info with its new info, and bumping its
50 version number if it differs. If A.f mentions B.g, and B.g's version
51 number has changed, then we count A.f as having changed too.
53 * In checkOldIface we compare the mi_usages for the module with
54 the actual version info for all each thing recorded in mi_usages
59 We count A.f as changing if its fixity changes
63 If a rule changes, we want to recompile any module that might be
64 affected by that rule. For non-orphan rules, this is relatively easy.
65 If module M defines f, and a rule for f, just arrange that the version
66 number for M.f changes if any of the rules for M.f change. Any module
67 that does not depend on M.f can't be affected by the rule-change
70 Orphan rules (ones whose 'head function' is not defined in M) are
71 harder. Here's what we do.
73 * We have a per-module orphan-rule version number which changes if
74 any orphan rule changes. (It's unaffected by non-orphan rules.)
76 * We record usage info for any orphan module 'below' this one,
77 giving the orphan-rule version number. We recompile if this
80 The net effect is that if an orphan rule changes, we recompile every
81 module above it. That's very conservative, but it's devilishly hard
82 to know what it might affect, so we just have to be conservative.
86 In an iface file we have
88 instance Eq a => Eq [a] = dfun29
91 We have a version number for dfun29, covering its unfolding
92 etc. Suppose we are compiling a module M that imports A only
93 indirectly. If typechecking M uses this instance decl, we record the
94 dependency on A.dfun29 as if it were a free variable of the module
95 (via the tcg_inst_usages accumulator). That means that A will appear
96 in M's usage list. If the shape of the instance declaration changes,
97 then so will dfun29's version, triggering a recompilation.
99 Adding an instance declaration, or changing an instance decl that is
100 not currently used, is more tricky. (This really only makes a
101 difference when we have overlapping instance decls, because then the
102 new instance decl might kick in to override the old one.) We handle
103 this in a very similar way that we handle rules above.
105 * For non-orphan instance decls, identify one locally-defined tycon/class
106 mentioned in the decl. Treat the instance decl as part of the defn of that
107 tycon/class, so that if the shape of the instance decl changes, so does the
108 tycon/class; that in turn will force recompilation of anything that uses
111 * For orphan instance decls, act the same way as for orphan rules.
112 Indeed, we use the same global orphan-rule version number.
116 mkUsageInfo figures out what the ``usage information'' for this
117 moudule is; that is, what it must record in its interface file as the
120 We produce a line for every module B below the module, A, currently being
123 to record the fact that A does import B indirectly. This is used to decide
124 to look to look for B.hi rather than B.hi-boot when compiling a module that
125 imports A. This line says that A imports B, but uses nothing in it.
126 So we'll get an early bale-out when compiling A if B's version changes.
128 The usage information records:
131 \item (a) anything reachable from its body code
132 \item (b) any module exported with a @module Foo@
133 \item (c) anything reachable from an exported item
136 Why (b)? Because if @Foo@ changes then this module's export list
137 will change, so we must recompile this module at least as far as
138 making a new interface file --- but in practice that means complete
141 Why (c)? Consider this:
143 module A( f, g ) where | module B( f ) where
144 import B( f ) | f = h 3
148 Here, @B.f@ isn't used in A. Should we nevertheless record @B.f@ in
149 @A@'s usages? Our idea is that we aren't going to touch A.hi if it is
150 *identical* to what it was before. If anything about @B.f@ changes
151 than anyone who imports @A@ should be recompiled in case they use
152 @B.f@ (they'll get an early exit if they don't). So, if anything
153 about @B.f@ changes we'd better make sure that something in A.hi
154 changes, and the convenient way to do that is to record the version
155 number @B.f@ in A.hi in the usage list. If B.f changes that'll force a
156 complete recompiation of A, which is overkill but it's the only way to
157 write a new, slightly different, A.hi.
159 But the example is tricker. Even if @B.f@ doesn't change at all,
160 @B.h@ may do so, and this change may not be reflected in @f@'s version
161 number. But with -O, a module that imports A must be recompiled if
162 @B.h@ changes! So A must record a dependency on @B.h@. So we treat
163 the occurrence of @B.f@ in the export list *just as if* it were in the
164 code of A, and thereby haul in all the stuff reachable from it.
166 *** Conclusion: if A mentions B.f in its export list,
167 behave just as if A mentioned B.f in its source code,
168 and slurp in B.f and all its transitive closure ***
170 [NB: If B was compiled with -O, but A isn't, we should really *still*
171 haul in all the unfoldings for B, in case the module that imports A *is*
172 compiled with -O. I think this is the case.]
176 #include "HsVersions.h"
179 import IfaceSyn ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..),
180 IfaceRule(..), IfaceInst(..), IfaceExtName(..),
181 eqIfDecl, eqIfRule, eqIfInst, IfaceEq(..), (&&&), bool,
182 eqMaybeBy, eqListBy, visibleIfConDecls,
183 tyThingToIfaceDecl, instanceToIfaceInst, coreRuleToIfaceRule )
184 import LoadIface ( readIface, loadInterface )
185 import BasicTypes ( Version, initialVersion, bumpVersion )
187 import HscTypes ( ModIface(..), ModDetails(..),
188 ModGuts(..), IfaceExport,
189 HscEnv(..), hscEPS, Dependencies(..), FixItem(..),
190 ModSummary(..), msHiFilePath,
191 mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
193 GenAvailInfo(..), availName,
194 ExternalPackageState(..),
195 Usage(..), IsBootInterface,
196 Deprecs(..), IfaceDeprecs, Deprecations,
201 import DynFlags ( GhcMode(..), DynFlags(..), DynFlag(..), dopt )
202 import StaticFlags ( opt_HiVersion )
203 import Name ( Name, nameModule, nameOccName, nameParent,
204 isExternalName, isInternalName, nameParent_maybe, isWiredInName,
205 isImplicitName, NamedThing(..) )
208 import OccName ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
210 OccSet, emptyOccSet, elemOccSet, occSetElts,
211 extendOccSet, extendOccSetList,
212 isEmptyOccSet, intersectOccSet, intersectsOccSet,
216 import Util ( createDirectoryHierarchy, directoryOf )
217 import Util ( sortLe, seqList )
218 import Binary ( getBinFileWithDict )
219 import BinIface ( writeBinIface, v_IgnoreHiWay )
220 import Unique ( Unique, Uniquable(..) )
221 import ErrUtils ( dumpIfSet_dyn, showPass )
222 import Digraph ( stronglyConnComp, SCC(..) )
223 import SrcLoc ( SrcSpan )
225 import PackageConfig ( PackageId )
229 import DATA_IOREF ( writeIORef )
230 import Monad ( when )
231 import List ( insert )
232 import Maybes ( orElse, mapCatMaybes, isNothing, isJust,
233 expectJust, MaybeErr(..) )
238 %************************************************************************
240 \subsection{Completing an interface}
242 %************************************************************************
246 -> Maybe ModIface -- The old interface, if we have it
247 -> ModGuts -- Usages, deprecations, etc
248 -> ModDetails -- The trimmed, tidied interface
249 -> IO (ModIface, -- The new one, complete with decls and versions
250 Bool) -- True <=> there was an old Iface, and the new one
251 -- is identical, so no need to write it
253 mkIface hsc_env maybe_old_iface
254 (ModGuts{ mg_module = this_mod,
258 mg_rdr_env = rdr_env,
259 mg_fix_env = fix_env,
260 mg_deprecs = src_deprecs })
261 (ModDetails{ md_insts = insts,
264 md_exports = exports })
266 -- NB: notice that mkIface does not look at the bindings
267 -- only at the TypeEnv. The previous Tidy phase has
268 -- put exactly the info into the TypeEnv that we want
269 -- to expose in the interface
271 = do { eps <- hscEPS hsc_env
272 ; let { ext_nm_rhs = mkExtNameFn hsc_env eps this_mod
273 ; ext_nm_lhs = mkLhsNameFn this_mod
275 ; decls = [ tyThingToIfaceDecl ext_nm_rhs thing
276 | thing <- typeEnvElts type_env,
277 let name = getName thing,
278 not (isImplicitName name || isWiredInName name) ]
279 -- Don't put implicit Ids and class tycons in the interface file
280 -- Nor wired-in things; the compiler knows about them anyhow
282 ; fixities = [(occ,fix) | FixItem occ fix _ <- nameEnvElts fix_env]
283 ; deprecs = mkIfaceDeprec src_deprecs
284 ; iface_rules = map (coreRuleToIfaceRule ext_nm_lhs ext_nm_rhs) rules
285 ; iface_insts = map (instanceToIfaceInst ext_nm_lhs) insts
287 ; intermediate_iface = ModIface {
288 mi_module = this_mod,
292 mi_exports = mkIfaceExports exports,
293 mi_insts = sortLe le_inst iface_insts,
294 mi_rules = sortLe le_rule iface_rules,
295 mi_fixities = fixities,
296 mi_deprecs = deprecs,
297 mi_globals = Just rdr_env,
299 -- Left out deliberately: filled in by addVersionInfo
300 mi_mod_vers = initialVersion,
301 mi_exp_vers = initialVersion,
302 mi_rule_vers = initialVersion,
303 mi_orphan = False, -- Always set by addVersionInfo, but
304 -- it's a strict field, so we can't omit it.
305 mi_decls = deliberatelyOmitted "decls",
306 mi_ver_fn = deliberatelyOmitted "ver_fn",
308 -- And build the cached values
309 mi_dep_fn = mkIfaceDepCache deprecs,
310 mi_fix_fn = mkIfaceFixCache fixities }
312 -- Add version information
313 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs)
314 = _scc_ "versioninfo"
315 addVersionInfo maybe_old_iface intermediate_iface decls
319 ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags)
320 (printDump (expectJust "mkIface" pp_orphs))
321 ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
322 ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
323 (pprModIface new_iface)
325 ; return (new_iface, no_change_at_all) }
327 r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
328 i1 `le_inst` i2 = ifDFun i1 <= ifDFun i2
330 dflags = hsc_dflags hsc_env
331 deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
334 -----------------------------
335 writeIfaceFile :: ModLocation -> ModIface -> IO ()
336 writeIfaceFile location new_iface
337 = do createDirectoryHierarchy (directoryOf hi_file_path)
338 writeBinIface hi_file_path new_iface
339 where hi_file_path = ml_hi_file location
342 -----------------------------
343 mkExtNameFn :: HscEnv -> ExternalPackageState -> Module -> Name -> IfaceExtName
344 mkExtNameFn hsc_env eps this_mod
347 hpt = hsc_HPT hsc_env
351 | mod == this_mod = case nameParent_maybe name of
352 Nothing -> LocalTop occ
353 Just par -> LocalTopSub occ (nameOccName par)
354 | isWiredInName name = ExtPkg mod occ
355 | is_home mod = HomePkg mod_name occ vers
356 | otherwise = ExtPkg mod occ
358 dflags = hsc_dflags hsc_env
359 this_pkg = thisPackage dflags
360 is_home mod = modulePackageId mod == this_pkg
362 mod = nameModule name
363 mod_name = moduleName mod
364 occ = nameOccName name
365 par_occ = nameOccName (nameParent name)
366 -- The version of the *parent* is the one want
367 vers = lookupVersion mod par_occ
369 lookupVersion :: Module -> OccName -> Version
370 -- Even though we're looking up a home-package thing, in
371 -- one-shot mode the imported interfaces may be in the PIT
372 lookupVersion mod occ
373 = mi_ver_fn iface occ `orElse`
374 pprPanic "lookupVers1" (ppr mod <+> ppr occ)
376 iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
377 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
380 ---------------------
381 -- mkLhsNameFn ignores versioning info altogether
382 -- It is used for the LHS of instance decls and rules, where we
383 -- there's no point in recording version info
384 mkLhsNameFn :: Module -> Name -> IfaceExtName
385 mkLhsNameFn this_mod name
386 | isInternalName name = pprTrace "mkLhsNameFn: unexpected internal" (ppr name) $
387 LocalTop occ -- Should not happen
388 | mod == this_mod = LocalTop occ
389 | otherwise = ExtPkg mod occ
391 mod = nameModule name
392 occ = nameOccName name
395 -----------------------------
396 -- Compute version numbers for local decls
398 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
399 -> ModIface -- The new interface decls (lacking decls)
400 -> [IfaceDecl] -- The new decls
402 Bool, -- True <=> no changes at all; no need to write new Iface
404 Maybe SDoc) -- Warnings about orphans
406 addVersionInfo Nothing new_iface new_decls
407 -- No old interface, so definitely write a new one!
408 = (new_iface { mi_orphan = anyNothing ifInstOrph (mi_insts new_iface)
409 || anyNothing ifRuleOrph (mi_rules new_iface),
410 mi_decls = [(initialVersion, decl) | decl <- new_decls],
411 mi_ver_fn = \n -> Just initialVersion },
413 ptext SLIT("No old interface file"),
414 pprOrphans orph_insts orph_rules)
416 orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
417 orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
419 addVersionInfo (Just old_iface@(ModIface { mi_mod_vers = old_mod_vers,
420 mi_exp_vers = old_exp_vers,
421 mi_rule_vers = old_rule_vers,
422 mi_decls = old_decls,
423 mi_ver_fn = old_decl_vers,
424 mi_fix_fn = old_fixities }))
425 new_iface@(ModIface { mi_fix_fn = new_fixities })
428 | no_change_at_all = (old_iface, True, ptext SLIT("Interface file unchanged"), pp_orphs)
429 | otherwise = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
430 nest 2 pp_diffs], pp_orphs)
432 final_iface = new_iface { mi_mod_vers = bump_unless no_output_change old_mod_vers,
433 mi_exp_vers = bump_unless no_export_change old_exp_vers,
434 mi_rule_vers = bump_unless no_rule_change old_rule_vers,
435 mi_orphan = not (null new_orph_rules && null new_orph_insts),
436 mi_decls = decls_w_vers,
437 mi_ver_fn = mkIfaceVerCache decls_w_vers }
439 decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
442 (old_non_orph_insts, old_orph_insts) = mkOrphMap ifInstOrph (mi_insts old_iface)
443 (new_non_orph_insts, new_orph_insts) = mkOrphMap ifInstOrph (mi_insts new_iface)
444 same_insts occ = eqMaybeBy (eqListBy eqIfInst)
445 (lookupOccEnv old_non_orph_insts occ)
446 (lookupOccEnv new_non_orph_insts occ)
448 (old_non_orph_rules, old_orph_rules) = mkOrphMap ifRuleOrph (mi_rules old_iface)
449 (new_non_orph_rules, new_orph_rules) = mkOrphMap ifRuleOrph (mi_rules new_iface)
450 same_rules occ = eqMaybeBy (eqListBy eqIfRule)
451 (lookupOccEnv old_non_orph_rules occ)
452 (lookupOccEnv new_non_orph_rules occ)
454 -- Computing what changed
455 no_output_change = no_decl_change && no_rule_change &&
456 no_export_change && no_deprec_change
457 no_export_change = mi_exports new_iface == mi_exports old_iface -- Kept sorted
458 no_decl_change = isEmptyOccSet changed_occs
459 no_rule_change = not (changedWrt changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
460 || changedWrt changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
461 no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
463 -- If the usages havn't changed either, we don't need to write the interface file
464 no_other_changes = mi_usages new_iface == mi_usages old_iface &&
465 mi_deps new_iface == mi_deps old_iface
466 no_change_at_all = no_output_change && no_other_changes
468 pp_diffs = vcat [pp_change no_export_change "Export list"
469 (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
470 pp_change no_rule_change "Rules"
471 (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
472 pp_change no_deprec_change "Deprecations" empty,
473 pp_change no_other_changes "Usages" empty,
475 pp_change True what info = empty
476 pp_change False what info = text what <+> ptext SLIT("changed") <+> info
479 old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
480 same_fixity n = bool (old_fixities n == new_fixities n)
483 -- Adding version info
484 new_version = bumpVersion old_mod_vers -- Start from the old module version, not from zero
485 -- so that if you remove f, and then add it again,
486 -- you don't thereby reduce f's version number
487 add_vers decl | occ `elemOccSet` changed_occs = new_version
488 | otherwise = expectJust "add_vers" (old_decl_vers occ)
489 -- If it's unchanged, there jolly well
490 where -- should be an old version number
494 changed_occs :: OccSet
495 changed_occs = computeChangedOccs eq_info
497 eq_info :: [(OccName, IfaceEq)]
498 eq_info = map check_eq new_decls
499 check_eq new_decl | Just old_decl <- lookupOccEnv old_decl_env occ
500 = (occ, new_decl `eqIfDecl` old_decl &&&
501 eq_indirects new_decl)
502 | otherwise {- No corresponding old decl -}
505 occ = ifName new_decl
507 eq_indirects :: IfaceDecl -> IfaceEq
508 -- When seeing if two decls are the same, remember to
509 -- check whether any relevant fixity or rules have changed
510 eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
511 eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
512 = same_insts cls_occ &&&
513 eq_ind_occs [op | IfaceClassOp op _ _ <- sigs]
514 eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
515 = same_insts tc_occ &&& same_fixity tc_occ &&& -- The TyCon can have a fixity too
516 eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
517 eq_indirects other = Equal -- Synonyms and foreign declarations
519 eq_ind_occ :: OccName -> IfaceEq -- For class ops and Ids; check fixity and rules
520 eq_ind_occ occ = same_fixity occ &&& same_rules occ
521 eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal
525 pp_decl_diffs :: SDoc -- Nothing => no changes
527 | isEmptyOccSet changed_occs = empty
529 = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
530 ptext SLIT("Version change for these decls:"),
531 nest 2 (vcat (map show_change new_decls))]
533 eq_env = mkOccEnv eq_info
535 | not (occ `elemOccSet` changed_occs) = empty
537 = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version,
540 occ = ifName new_decl
541 why = case lookupOccEnv eq_env occ of
542 Just (EqBut occs) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
543 nest 2 (braces (fsep (map ppr (occSetElts
544 (occs `intersectOccSet` changed_occs)))))]
546 | Just old_decl <- lookupOccEnv old_decl_env occ
547 -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
548 ptext SLIT("New:") <+> ppr new_decl]
550 -> ppr occ <+> ptext SLIT("only in new interface")
551 other -> pprPanic "MkIface.show_change" (ppr occ)
553 pp_orphs = pprOrphans new_orph_insts new_orph_rules
555 pprOrphans insts rules
556 | null insts && null rules = Nothing
559 if null insts then empty else
560 hang (ptext SLIT("Warning: orphan instances:"))
561 2 (vcat (map ppr insts)),
562 if null rules then empty else
563 hang (ptext SLIT("Warning: orphan rules:"))
564 2 (vcat (map ppr rules))
567 computeChangedOccs :: [(OccName, IfaceEq)] -> OccSet
568 computeChangedOccs eq_info
569 = foldl add_changes emptyOccSet (stronglyConnComp edges)
571 edges :: [((OccName,IfaceEq), Unique, [Unique])]
572 edges = [ (node, getUnique occ, map getUnique occs)
573 | node@(occ, iface_eq) <- eq_info
574 , let occs = case iface_eq of
575 EqBut occ_set -> occSetElts occ_set
578 -- Changes in declarations
579 add_changes :: OccSet -> SCC (OccName, IfaceEq) -> OccSet
580 add_changes so_far (AcyclicSCC (occ, iface_eq))
581 | changedWrt so_far iface_eq -- This one has changed
582 = extendOccSet so_far occ
583 add_changes so_far (CyclicSCC pairs)
584 | changedWrt so_far (foldr1 (&&&) (map snd pairs)) -- One of this group has changed
585 = extendOccSetList so_far (map fst pairs)
586 add_changes so_far other = so_far
588 changedWrt :: OccSet -> IfaceEq -> Bool
589 changedWrt so_far Equal = False
590 changedWrt so_far NotEqual = True
591 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
593 ----------------------
594 -- mkOrphMap partitions instance decls or rules into
595 -- (a) an OccEnv for ones that are not orphans,
596 -- mapping the local OccName to a list of its decls
597 -- (b) a list of orphan decls
598 mkOrphMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
599 -- Nothing for an orphan decl
600 -> [decl] -- Sorted into canonical order
601 -> (OccEnv [decl], -- Non-orphan decls associated with their key;
602 -- each sublist in canonical order
603 [decl]) -- Orphan decls; in canonical order
604 mkOrphMap get_key decls
605 = foldl go (emptyOccEnv, []) decls
607 go (non_orphs, orphs) d
608 | Just occ <- get_key d
609 = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
610 | otherwise = (non_orphs, d:orphs)
612 anyNothing :: (a -> Maybe b) -> [a] -> Bool
613 anyNothing p [] = False
614 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
616 ----------------------
617 mkIfaceDeprec :: Deprecations -> IfaceDeprecs
618 mkIfaceDeprec NoDeprecs = NoDeprecs
619 mkIfaceDeprec (DeprecAll t) = DeprecAll t
620 mkIfaceDeprec (DeprecSome env) = DeprecSome (sortLe (<=) (nameEnvElts env))
622 ----------------------
623 bump_unless :: Bool -> Version -> Version
624 bump_unless True v = v -- True <=> no change
625 bump_unless False v = bumpVersion v
629 %*********************************************************
631 \subsection{Keeping track of what we've slurped, and version numbers}
633 %*********************************************************
637 mkUsageInfo :: HscEnv
638 -> ModuleEnv (Module, Bool, SrcSpan)
639 -> [(ModuleName, IsBootInterface)]
640 -> NameSet -> IO [Usage]
641 mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
642 = do { eps <- hscEPS hsc_env
643 ; let usages = mk_usage_info (eps_PIT eps) hsc_env
644 dir_imp_mods dep_mods used_names
645 ; usages `seqList` return usages }
646 -- seq the list of Usages returned: occasionally these
647 -- don't get evaluated for a while and we can end up hanging on to
648 -- the entire collection of Ifaces.
650 mk_usage_info pit hsc_env dir_imp_mods dep_mods proto_used_names
651 = mapCatMaybes mkUsage dep_mods
652 -- ToDo: do we need to sort into canonical order?
654 hpt = hsc_HPT hsc_env
655 dflags = hsc_dflags hsc_env
657 used_names = mkNameSet $ -- Eliminate duplicates
658 [ nameParent n -- Just record usage on the 'main' names
659 | n <- nameSetToList proto_used_names
660 , not (isWiredInName n) -- Don't record usages for wired-in names
661 , isExternalName n -- Ignore internal names
664 -- ent_map groups together all the things imported and used
665 -- from a particular module in this package
666 ent_map :: ModuleEnv [OccName]
667 ent_map = foldNameSet add_mv emptyModuleEnv used_names
668 add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [occ]
670 occ = nameOccName name
671 mod = nameModule name
672 add_item occs _ = occ:occs
674 depend_on_exports mod = case lookupModuleEnv dir_imp_mods mod of
675 Just (_,no_imp,_) -> not no_imp
678 -- We want to create a Usage for a home module if
679 -- a) we used something from; has something in used_names
680 -- b) we imported all of it, even if we used nothing from it
681 -- (need to recompile if its export list changes: export_vers)
682 -- c) is a home-package orphan module (need to recompile if its
683 -- instance decls change: rules_vers)
684 mkUsage :: (ModuleName, IsBootInterface) -> Maybe Usage
685 mkUsage (mod_name, _)
686 | isNothing maybe_iface -- We can't depend on it if we didn't
687 || (null used_occs -- load its interface.
688 && isNothing export_vers
690 = Nothing -- Record no usage info
693 = Just (Usage { usg_name = mod_name,
695 usg_exports = export_vers,
696 usg_entities = ent_vers,
697 usg_rules = rules_vers })
699 maybe_iface = lookupIfaceByModule dflags hpt pit mod
700 -- In one-shot mode, the interfaces for home-package
701 -- modules accumulate in the PIT not HPT. Sigh.
703 mod = mkModule (thisPackage dflags) mod_name
705 Just iface = maybe_iface
706 orphan_mod = mi_orphan iface
707 version_env = mi_ver_fn iface
708 mod_vers = mi_mod_vers iface
709 rules_vers = mi_rule_vers iface
710 export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
711 | otherwise = Nothing
713 -- The sort is to put them into canonical order
714 used_occs = lookupModuleEnv ent_map mod `orElse` []
715 ent_vers :: [(OccName,Version)]
716 ent_vers = [ (occ, version_env occ `orElse` initialVersion)
717 | occ <- sortLe (<=) used_occs]
721 mkIfaceExports :: NameSet -> [(Module, [GenAvailInfo OccName])]
722 -- Group by module and sort by occurrence
723 -- This keeps the list in canonical order
724 mkIfaceExports exports
725 = [ (mod, eltsUFM avails)
726 | (mod, avails) <- fmToList groupFM
729 groupFM :: ModuleEnv (UniqFM (GenAvailInfo OccName))
730 -- Deliberately use the FastString so we
731 -- get a canonical ordering
732 groupFM = foldl add emptyModuleEnv (nameSetToList exports)
734 add env name = extendModuleEnv_C add_avail env mod
735 (unitUFM avail_fs avail)
737 occ = nameOccName name
738 mod = nameModule name
739 avail | Just p <- nameParent_maybe name = AvailTC (nameOccName p) [occ]
740 | isTcOcc occ = AvailTC occ [occ]
741 | otherwise = Avail occ
742 avail_fs = occNameFS (availName avail)
743 add_avail avail_fm _ = addToUFM_C add_item avail_fm avail_fs avail
745 add_item (AvailTC p occs) _ = AvailTC p (List.insert occ occs)
746 add_item (Avail n) _ = pprPanic "MkIface.addAvail" (ppr n <+> ppr name)
750 %************************************************************************
752 Load the old interface file for this module (unless
753 we have it aleady), and check whether it is up to date
756 %************************************************************************
759 checkOldIface :: HscEnv
761 -> Bool -- Source unchanged
762 -> Maybe ModIface -- Old interface from compilation manager, if any
763 -> IO (RecompileRequired, Maybe ModIface)
765 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
766 = do { showPass (hsc_dflags hsc_env)
767 ("Checking old interface for " ++
768 showSDoc (ppr (ms_mod mod_summary))) ;
770 ; initIfaceCheck hsc_env $
771 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
774 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
775 = -- CHECK WHETHER THE SOURCE HAS CHANGED
776 ifM (not source_unchanged)
777 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
780 -- If the source has changed and we're in interactive mode, avoid reading
781 -- an interface; just return the one we might have been supplied with.
782 getGhcMode `thenM` \ ghc_mode ->
783 if (ghc_mode == Interactive || ghc_mode == JustTypecheck)
784 && not source_unchanged then
785 returnM (outOfDate, maybe_iface)
788 case maybe_iface of {
789 Just old_iface -> do -- Use the one we already have
790 recomp <- checkVersions hsc_env source_unchanged old_iface
791 return (recomp, Just old_iface)
795 -- Try and read the old interface for the current module
796 -- from the .hi file left from the last time we compiled it
798 iface_path = msHiFilePath mod_summary
800 readIface (ms_mod mod_summary) iface_path False `thenM` \ read_result ->
801 case read_result of {
802 Failed err -> -- Old interface file not found, or garbled; give up
803 traceIf (text "FYI: cannot read old interface file:"
804 $$ nest 4 err) `thenM_`
805 returnM (outOfDate, Nothing)
809 -- We have got the old iface; check its versions
810 checkVersions hsc_env source_unchanged iface `thenM` \ recomp ->
811 returnM (recomp, Just iface)
815 @recompileRequired@ is called from the HscMain. It checks whether
816 a recompilation is required. It needs access to the persistent state,
817 finder, etc, because it may have to load lots of interface files to
818 check their versions.
821 type RecompileRequired = Bool
822 upToDate = False -- Recompile not required
823 outOfDate = True -- Recompile required
825 checkVersions :: HscEnv
826 -> Bool -- True <=> source unchanged
827 -> ModIface -- Old interface
828 -> IfG RecompileRequired
829 checkVersions hsc_env source_unchanged iface
830 | not source_unchanged
833 = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
834 ppr (mi_module iface) <> colon)
836 -- Source code unchanged and no errors yet... carry on
838 -- First put the dependent-module info, read from the old interface, into the envt,
839 -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
841 -- It's just temporary because either the usage check will succeed
842 -- (in which case we are done with this module) or it'll fail (in which
843 -- case we'll compile the module from scratch anyhow).
845 -- We do this regardless of compilation mode
846 ; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
848 ; let this_pkg = thisPackage (hsc_dflags hsc_env)
849 ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
852 -- This is a bit of a hack really
853 mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
854 mod_deps = mkModDeps (dep_mods (mi_deps iface))
856 checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
857 -- Given the usage information extracted from the old
858 -- M.hi file for the module being compiled, figure out
859 -- whether M needs to be recompiled.
861 checkModUsage this_pkg (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
862 usg_rules = old_rule_vers,
863 usg_exports = maybe_old_export_vers,
864 usg_entities = old_decl_vers })
865 = -- Load the imported interface is possible
867 doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
869 traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
872 mod = mkModule this_pkg mod_name
874 loadInterface doc_str mod ImportBySystem `thenM` \ mb_iface ->
875 -- Load the interface, but don't complain on failure;
876 -- Instead, get an Either back which we can test
879 Failed exn -> (out_of_date (sep [ptext SLIT("Can't find version number for module"),
881 -- Couldn't find or parse a module mentioned in the
882 -- old interface file. Don't complain -- it might just be that
883 -- the current module doesn't need that import and it's been deleted
887 new_mod_vers = mi_mod_vers iface
888 new_decl_vers = mi_ver_fn iface
889 new_export_vers = mi_exp_vers iface
890 new_rule_vers = mi_rule_vers iface
893 checkModuleVersion old_mod_vers new_mod_vers `thenM` \ recompile ->
894 if not recompile then
899 if checkExportList maybe_old_export_vers new_export_vers then
900 out_of_date_vers (ptext SLIT(" Export list changed"))
901 (expectJust "checkModUsage" maybe_old_export_vers)
906 if old_rule_vers /= new_rule_vers then
907 out_of_date_vers (ptext SLIT(" Rules changed"))
908 old_rule_vers new_rule_vers
911 -- CHECK ITEMS ONE BY ONE
912 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] `thenM` \ recompile ->
914 returnM outOfDate -- This one failed, so just bail out now
916 up_to_date (ptext SLIT(" Great! The bits I use are up to date"))
919 ------------------------
920 checkModuleVersion old_mod_vers new_mod_vers
921 | new_mod_vers == old_mod_vers
922 = up_to_date (ptext SLIT("Module version unchanged"))
925 = out_of_date_vers (ptext SLIT(" Module version has changed"))
926 old_mod_vers new_mod_vers
928 ------------------------
929 checkExportList Nothing new_vers = upToDate
930 checkExportList (Just v) new_vers = v /= new_vers
932 ------------------------
933 checkEntityUsage new_vers (name,old_vers)
934 = case new_vers name of
936 Nothing -> -- We used it before, but it ain't there now
937 out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
939 Just new_vers -- It's there, but is it up to date?
940 | new_vers == old_vers -> traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
942 | otherwise -> out_of_date_vers (ptext SLIT(" Out of date:") <+> ppr name)
945 up_to_date msg = traceHiDiffs msg `thenM_` returnM upToDate
946 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
947 out_of_date_vers msg old_vers new_vers
948 = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
950 ----------------------
951 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
952 -- This helper is used in two places
953 checkList [] = returnM upToDate
954 checkList (check:checks) = check `thenM` \ recompile ->
961 %************************************************************************
965 %************************************************************************
968 showIface :: FilePath -> IO ()
969 -- Read binary interface, and print it out
970 showIface filename = do
971 -- skip the version check; we don't want to worry about profiled vs.
972 -- non-profiled interfaces, for example.
973 writeIORef v_IgnoreHiWay True
974 iface <- Binary.getBinFileWithDict filename
975 printDump (pprModIface iface)
981 pprModIface :: ModIface -> SDoc
984 = vcat [ ptext SLIT("interface")
985 <+> ppr (mi_module iface) <+> pp_boot
986 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
987 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
988 <+> int opt_HiVersion
989 <+> ptext SLIT("where")
990 , vcat (map pprExport (mi_exports iface))
991 , pprDeps (mi_deps iface)
992 , vcat (map pprUsage (mi_usages iface))
993 , pprFixities (mi_fixities iface)
994 , vcat (map pprIfaceDecl (mi_decls iface))
995 , vcat (map ppr (mi_insts iface))
996 , vcat (map ppr (mi_rules iface))
997 , pprDeprecs (mi_deprecs iface)
1000 pp_boot | mi_boot iface = ptext SLIT("[boot]")
1003 exp_vers = mi_exp_vers iface
1004 rule_vers = mi_rule_vers iface
1006 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
1007 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
1010 When printing export lists, we print like this:
1012 AvailTC C [C, x, y] C(x,y)
1013 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
1016 pprExport :: IfaceExport -> SDoc
1017 pprExport (mod, items)
1018 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
1020 pp_avail :: GenAvailInfo OccName -> SDoc
1021 pp_avail (Avail occ) = ppr occ
1022 pp_avail (AvailTC _ []) = empty
1023 pp_avail (AvailTC n (n':ns))
1024 | n==n' = ppr n <> pp_export ns
1025 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
1027 pp_export [] = empty
1028 pp_export names = braces (hsep (map ppr names))
1030 pprUsage :: Usage -> SDoc
1032 = hsep [ptext SLIT("import"), ppr (usg_name usage),
1033 int (usg_mod usage),
1034 pp_export_version (usg_exports usage),
1035 int (usg_rules usage),
1036 pp_versions (usg_entities usage) ]
1038 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
1039 pp_export_version Nothing = empty
1040 pp_export_version (Just v) = int v
1042 pprDeps :: Dependencies -> SDoc
1043 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
1044 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
1045 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
1046 ptext SLIT("orphans:") <+> fsep (map ppr orphs)
1049 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
1050 ppr_boot True = text "[boot]"
1051 ppr_boot False = empty
1053 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
1054 pprIfaceDecl (ver, decl)
1055 = ppr_vers ver <+> ppr decl
1057 -- Print the version for the decl
1058 ppr_vers v | v == initialVersion = empty
1061 pprFixities :: [(OccName, Fixity)] -> SDoc
1062 pprFixities [] = empty
1063 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
1065 pprFix (occ,fix) = ppr fix <+> ppr occ
1067 pprDeprecs NoDeprecs = empty
1068 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
1069 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
1071 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)