2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
7 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 IfaceSyn ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..),
178 IfaceRule(..), IfaceInst(..), IfaceExtName(..), IfaceTyCon(..),
179 eqIfDecl, eqIfRule, eqIfInst, IfaceEq(..), (&&&), bool,
181 tyThingToIfaceDecl, dfunToIfaceInst, coreRuleToIfaceRule )
182 import LoadIface ( readIface, loadInterface, ifaceInstGates )
183 import BasicTypes ( Version, initialVersion, bumpVersion )
185 import TcRnTypes ( ImportAvails(..), mkModDeps )
186 import HscTypes ( ModIface(..), TyThing(..),
187 ModGuts(..), ModGuts, IfaceExport,
190 Dependencies(..), FixItem(..),
191 mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
193 Avails, AvailInfo, GenAvailInfo(..), availName,
194 ExternalPackageState(..),
195 Usage(..), IsBootInterface,
196 Deprecs(..), IfaceDeprecs, Deprecations,
202 import Name ( Name, nameModule, nameOccName, nameParent, isExternalName,
203 nameParent_maybe, isWiredInName, NamedThing(..), nameModuleName )
206 import OccName ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv, extendOccEnv_C,
207 OccSet, emptyOccSet, elemOccSet, occSetElts,
208 extendOccSet, extendOccSetList,
209 isEmptyOccSet, intersectOccSet, intersectsOccSet,
211 import TyCon ( visibleDataCons, tyConDataCons )
212 import Class ( classSelIds )
213 import DataCon ( dataConName )
214 import Module ( Module, ModuleName, moduleNameFS, moduleName, isHomeModule,
215 ModLocation(..), mkSysModuleNameFS, moduleUserString,
216 ModuleEnv, emptyModuleEnv, lookupModuleEnv,
217 extendModuleEnv_C, moduleEnvElts
220 import DriverUtil ( createDirectoryHierarchy, directoryOf )
221 import Util ( sortLt, seqList )
222 import Binary ( getBinFileWithDict )
223 import BinIface ( writeBinIface, v_IgnoreHiWay )
224 import Unique ( Unique, Uniquable(..) )
225 import ErrUtils ( dumpIfSet_dyn, showPass )
226 import Digraph ( stronglyConnComp, SCC(..) )
230 import DATA_IOREF ( writeIORef )
231 import Monad ( when )
232 import List ( insert )
233 import Maybes ( orElse, mapCatMaybes, isNothing, fromJust, expectJust )
238 %************************************************************************
240 \subsection{Completing an interface}
242 %************************************************************************
247 -> Maybe ModIface -- The old interface, if we have it
248 -> ModGuts -- The compiled, tidied module
249 -> IO ModIface -- The new one, complete with decls and versions
251 -- a) completes the interface
252 -- b) writes it out to a file if necessary
254 mkIface hsc_env location maybe_old_iface
255 guts@ModGuts{ mg_module = this_mod,
258 mg_exports = exports,
259 mg_fix_env = fix_env,
260 mg_deprecs = src_deprecs,
263 mg_types = type_env }
264 = do { eps <- hscEPS hsc_env
265 ; let { this_mod_name = moduleName this_mod
266 ; ext_nm = mkExtNameFn hsc_env eps this_mod_name
267 ; local_things = [thing | thing <- typeEnvElts type_env,
268 not (isWiredInName (getName thing)) ]
269 -- Do not export anything about wired-in things
270 -- (GHC knows about them already)
272 ; abstract_tcs :: NameSet -- TyCons and Classes whose representation is not exposed
274 | not omit_prags = emptyNameSet -- In the -O case, nothing is abstract
275 | otherwise = mkNameSet [ getName thing
276 | thing <- local_things
277 , isAbstractThing exports thing]
279 ; decls = [ tyThingToIfaceDecl omit_prags abstract_tcs ext_nm thing
280 | thing <- local_things, wantDeclFor exports abstract_tcs thing ]
281 -- Don't put implicit Ids and class tycons in the interface file
283 ; fixities = [(occ,fix) | FixItem occ fix _ <- nameEnvElts fix_env]
284 ; deprecs = mkIfaceDeprec src_deprecs
287 | otherwise = sortLt lt_rule $
288 map (coreRuleToIfaceRule this_mod_name ext_nm) rules
289 ; iface_insts = sortLt lt_inst (map (dfunToIfaceInst this_mod_name) insts)
291 ; intermediate_iface = ModIface {
292 mi_module = this_mod,
293 mi_package = opt_InPackage,
297 mi_exports = mkIfaceExports exports,
298 mi_insts = iface_insts,
299 mi_rules = iface_rules,
300 mi_fixities = fixities,
301 mi_deprecs = deprecs,
303 -- Left out deliberately: filled in by addVersionInfo
304 mi_mod_vers = initialVersion,
305 mi_exp_vers = initialVersion,
306 mi_rule_vers = initialVersion,
307 mi_orphan = False, -- Always set by addVersionInfo, but
308 -- it's a strict field, so we can't omit it.
309 mi_decls = deliberatelyOmitted "decls",
310 mi_ver_fn = deliberatelyOmitted "ver_fn",
312 -- And build the cached values
313 mi_dep_fn = mkIfaceDepCache deprecs,
314 mi_fix_fn = mkIfaceFixCache fixities }
316 -- Add version information
317 ; (new_iface, no_change_at_all, pp_diffs)
318 = _scc_ "versioninfo"
319 addVersionInfo maybe_old_iface intermediate_iface decls
322 -- Write the interface file, if necessary
323 ; when (not no_change_at_all && ghci_mode /= Interactive) $ do
324 createDirectoryHierarchy (directoryOf hi_file_path)
325 writeBinIface hi_file_path new_iface
328 ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
329 ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
330 (pprModIface new_iface)
334 r1 `lt_rule` r2 = ifRuleName r1 < ifRuleName r2
335 i1 `lt_inst` i2 = ifDFun i1 < ifDFun i2
337 dflags = hsc_dflags hsc_env
338 ghci_mode = hsc_mode hsc_env
339 hi_file_path = ml_hi_file location
340 omit_prags = dopt Opt_OmitInterfacePragmas dflags
343 isAbstractThing :: NameSet -> TyThing -> Bool
344 isAbstractThing exports (ATyCon tc) = not (any exported_data_con (tyConDataCons tc))
345 where -- Don't expose rep if no datacons are exported
346 exported_data_con con = dataConName con `elemNameSet` exports
348 isAbstractThing exports (AClass cls) = not (any exported_class_op (classSelIds cls))
349 where -- Don't expose rep if no classs op is exported
350 exported_class_op op = getName op `elemNameSet` exports
352 isAbstractThing exports other = False
354 wantDeclFor :: NameSet -- User-exported things
355 -> NameSet -- Abstract things
357 wantDeclFor exports abstracts thing
358 | Just parent <- nameParent_maybe name -- An implicit thing
359 = parent `elemNameSet` abstracts && name `elemNameSet` exports
366 deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
368 -----------------------------
369 mkExtNameFn :: HscEnv -> ExternalPackageState -> ModuleName -> Name -> IfaceExtName
370 mkExtNameFn hsc_env eps this_mod
373 hpt = hsc_HPT hsc_env
377 | mod_nm == this_mod = case nameParent_maybe name of
378 Nothing -> LocalTop occ
379 Just par -> LocalTopSub occ (nameOccName par)
380 | isWiredInName name = ExtPkg mod_nm occ
381 | isHomeModule mod = HomePkg mod_nm occ vers
382 | otherwise = ExtPkg mod_nm occ
384 mod = nameModule name
385 mod_nm = moduleName mod
386 occ = nameOccName name
387 par_occ = nameOccName (nameParent name)
388 -- The version of the *parent* is the one want
389 vers = lookupVersion mod_nm par_occ
391 lookupVersion :: ModuleName -> OccName -> Version
392 -- Even though we're looking up a home-package thing, in
393 -- one-shot mode the imported interfaces may be in the PIT
394 lookupVersion mod occ
395 = mi_ver_fn iface occ `orElse`
396 pprPanic "lookupVers1" (ppr mod <+> ppr occ)
398 iface = lookupIfaceByModName hpt pit mod `orElse`
399 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
401 -----------------------------
402 -- Compute version numbers for local decls
404 addVersionInfo :: Maybe ModIface -- The old interface, read from M.hi
405 -> ModIface -- The new interface decls (lacking decls)
406 -> [IfaceDecl] -- The new decls
408 Bool, -- True <=> no changes at all; no need to write new Iface
411 addVersionInfo Nothing new_iface new_decls
412 -- No old interface, so definitely write a new one!
413 = (new_iface { mi_orphan = anyNothing getInstKey (mi_insts new_iface)
414 || anyNothing getRuleKey (mi_rules new_iface),
415 mi_decls = [(initialVersion, decl) | decl <- new_decls],
416 mi_ver_fn = \n -> Just initialVersion },
417 False, ptext SLIT("No old interface file") $$
418 pprOrphans orph_insts orph_rules)
420 orph_insts = filter (isNothing . getInstKey) (mi_insts new_iface)
421 orph_rules = filter (isNothing . getRuleKey) (mi_rules new_iface)
423 addVersionInfo (Just old_iface@(ModIface { mi_mod_vers = old_mod_vers,
424 mi_exp_vers = old_exp_vers,
425 mi_rule_vers = old_rule_vers,
426 mi_decls = old_decls,
427 mi_ver_fn = old_decl_vers,
428 mi_fix_fn = old_fixities }))
429 new_iface@(ModIface { mi_fix_fn = new_fixities })
432 | no_change_at_all = (old_iface, True, ptext SLIT("Interface file unchanged") $$ pp_orphs)
433 | otherwise = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
435 text "" $$ pp_orphs])
437 final_iface = new_iface { mi_mod_vers = bump_unless no_output_change old_mod_vers,
438 mi_exp_vers = bump_unless no_export_change old_exp_vers,
439 mi_rule_vers = bump_unless no_rule_change old_rule_vers,
440 mi_orphan = not (null new_orph_rules && null new_orph_insts),
441 mi_decls = decls_w_vers,
442 mi_ver_fn = mkIfaceVerCache decls_w_vers }
444 decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
447 (old_non_orph_insts, old_orph_insts) = mkRuleMap getInstKey (mi_insts old_iface)
448 (new_non_orph_insts, new_orph_insts) = mkRuleMap getInstKey (mi_insts new_iface)
449 same_insts occ = eqMaybeBy (eqListBy eqIfInst)
450 (lookupOccEnv old_non_orph_insts occ)
451 (lookupOccEnv new_non_orph_insts occ)
453 (old_non_orph_rules, old_orph_rules) = mkRuleMap getRuleKey (mi_rules old_iface)
454 (new_non_orph_rules, new_orph_rules) = mkRuleMap getRuleKey (mi_rules new_iface)
455 same_rules occ = eqMaybeBy (eqListBy eqIfRule)
456 (lookupOccEnv old_non_orph_rules occ)
457 (lookupOccEnv new_non_orph_rules occ)
459 -- Computing what changed
460 no_output_change = no_decl_change && no_rule_change &&
461 no_export_change && no_deprec_change
462 no_export_change = mi_exports new_iface == mi_exports old_iface -- Kept sorted
463 no_decl_change = isEmptyOccSet changed_occs
464 no_rule_change = not (changedWrt changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
465 || changedWrt changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
466 no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
468 -- If the usages havn't changed either, we don't need to write the interface file
469 -- Question: should we also check for equality of mi_deps?
470 no_other_changes = mi_usages new_iface == mi_usages old_iface
471 no_change_at_all = no_output_change && no_other_changes
473 pp_diffs = vcat [pp_change no_export_change "Export list"
474 (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
475 pp_change no_rule_change "Rules"
476 (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
477 pp_change no_deprec_change "Deprecations" empty,
478 pp_change no_other_changes "Usages" empty,
480 pp_change True what info = empty
481 pp_change False what info = text what <+> ptext SLIT("changed") <+> info
484 old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
485 same_fixity n = bool (old_fixities n == new_fixities n)
488 -- Adding version info
489 new_version = bumpVersion old_mod_vers
490 add_vers decl | occ `elemOccSet` changed_occs = new_version
491 | otherwise = expectJust "add_vers" (old_decl_vers occ)
492 -- If it's unchanged, there jolly well
493 where -- should be an old version number
497 changed_occs :: OccSet
498 changed_occs = computeChangedOccs eq_info
500 eq_info :: [(OccName, IfaceEq)]
501 eq_info = map check_eq new_decls
502 check_eq new_decl | Just old_decl <- lookupOccEnv old_decl_env occ
503 = (occ, new_decl `eqIfDecl` old_decl &&&
504 eq_indirects new_decl)
505 | otherwise {- No corresponding old decl -}
508 occ = ifName new_decl
510 eq_indirects :: IfaceDecl -> IfaceEq
511 -- When seeing if two decls are the same, remember to
512 -- check whether any relevant fixity or rules have changed
513 eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
514 eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
515 = same_insts cls_occ &&&
516 eq_ind_occs [op | IfaceClassOp op _ _ <- sigs]
517 eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
518 = same_insts tc_occ &&& same_fixity tc_occ &&& -- The TyCon can have a fixity too
519 eq_ind_occs [occ | IfaceConDecl occ _ _ _ _ _ <- visibleDataCons cons]
520 eq_indirects other = Equal -- Synonyms and foreign declarations
522 eq_ind_occ :: OccName -> IfaceEq -- For class ops and Ids; check fixity and rules
523 eq_ind_occ occ = same_fixity occ &&& same_rules occ
524 eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal
528 pp_decl_diffs :: SDoc -- Nothing => no changes
530 | isEmptyOccSet changed_occs = empty
532 = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
533 ptext SLIT("Version change for these decls:"),
534 nest 2 (vcat (map show_change new_decls))]
536 eq_env = mkOccEnv eq_info
538 | not (occ `elemOccSet` changed_occs) = empty
540 = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version,
543 occ = ifName new_decl
544 why = case lookupOccEnv eq_env occ of
545 Just (EqBut occs) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
546 nest 2 (braces (fsep (map ppr (occSetElts
547 (occs `intersectOccSet` changed_occs)))))]
549 | Just old_decl <- lookupOccEnv old_decl_env occ
550 -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
551 ptext SLIT("New:") <+> ppr new_decl]
553 -> ppr occ <+> ptext SLIT("only in new interface")
554 other -> pprPanic "MkIface.show_change" (ppr occ)
556 pp_orphs = pprOrphans new_orph_insts new_orph_rules
558 pprOrphans insts rules
559 = vcat [if null insts then empty else
560 ptext SLIT("Orphan instances:") <+> vcat (map ppr insts),
561 if null rules then empty else
562 ptext SLIT("Orphan rules:") <+> vcat (map ppr rules)]
564 computeChangedOccs :: [(OccName, IfaceEq)] -> OccSet
565 computeChangedOccs eq_info
566 = foldl add_changes emptyOccSet (stronglyConnComp edges)
568 edges :: [((OccName,IfaceEq), Unique, [Unique])]
569 edges = [ (node, getUnique occ, map getUnique occs)
570 | node@(occ, iface_eq) <- eq_info
571 , let occs = case iface_eq of
572 EqBut occ_set -> occSetElts occ_set
575 -- Changes in declarations
576 add_changes :: OccSet -> SCC (OccName, IfaceEq) -> OccSet
577 add_changes so_far (AcyclicSCC (occ, iface_eq))
578 | changedWrt so_far iface_eq -- This one has changed
579 = extendOccSet so_far occ
580 add_changes so_far (CyclicSCC pairs)
581 | changedWrt so_far (foldr1 (&&&) (map snd pairs)) -- One of this group has changed
582 = extendOccSetList so_far (map fst pairs)
583 add_changes so_far other = so_far
585 changedWrt :: OccSet -> IfaceEq -> Bool
586 changedWrt so_far Equal = False
587 changedWrt so_far NotEqual = True
588 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
590 ----------------------
591 -- mkRuleMap partitions instance decls or rules into
592 -- (a) an OccEnv for ones that are not orphans,
593 -- mapping the local OccName to a list of its decls
594 -- (b) a list of orphan decls
595 mkRuleMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
596 -- Nothing for an orphan decl
597 -> [decl] -- Sorted into canonical order
598 -> (OccEnv [decl], -- Non-orphan decls associated with their key;
599 -- each sublist in canonical order
600 [decl]) -- Orphan decls; in canonical order
601 mkRuleMap get_key decls
602 = foldl go (emptyOccEnv, []) decls
604 go (non_orphs, orphs) d
605 | Just occ <- get_key d
606 = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
607 | otherwise = (non_orphs, d:orphs)
609 -- getXxKey: find at least one local OccName that belongs to this decl
611 getInstKey :: IfaceInst -> Maybe OccName
612 getInstKey (IfaceInst {ifInstHead = inst_ty})
613 = case [occ | LocalTop occ <- cls_ext : tc_exts] of
617 (cls_ext, tcs) = ifaceInstGates inst_ty
618 tc_exts = [tc | IfaceTc tc <- tcs]
619 -- Ignore the wired-in IfaceTyCons; the class will do as the key
621 getRuleKey :: IfaceRule -> Maybe OccName
622 getRuleKey (IfaceRule {ifRuleHead = LocalTop occ}) = Just occ
623 getRuleKey other = Nothing
625 anyNothing :: (a -> Maybe b) -> [a] -> Bool
626 anyNothing p [] = False
627 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
629 ----------------------
630 mkIfaceDeprec :: Deprecations -> IfaceDeprecs
631 mkIfaceDeprec NoDeprecs = NoDeprecs
632 mkIfaceDeprec (DeprecAll t) = DeprecAll t
633 mkIfaceDeprec (DeprecSome env) = DeprecSome (sortLt (<) (nameEnvElts env))
635 ----------------------
636 bump_unless :: Bool -> Version -> Version
637 bump_unless True v = v -- True <=> no change
638 bump_unless False v = bumpVersion v
642 %*********************************************************
644 \subsection{Keeping track of what we've slurped, and version numbers}
646 %*********************************************************
650 mkUsageInfo :: HscEnv -> ImportAvails -> NameSet -> IO [Usage]
652 (ImportAvails { imp_mods = dir_imp_mods,
653 imp_dep_mods = dep_mods })
655 = do { eps <- hscEPS hsc_env
656 ; return (mk_usage_info (eps_PIT eps) (hsc_HPT hsc_env)
657 dir_imp_mods dep_mods used_names) }
659 mk_usage_info pit hpt dir_imp_mods dep_mods proto_used_names
660 = -- seq the list of Usages returned: occasionally these
661 -- don't get evaluated for a while and we can end up hanging on to
662 -- the entire collection of Ifaces.
663 usages `seqList` usages
665 used_names = mkNameSet $ -- Eliminate duplicates
666 [ nameParent n -- Just record usage on the 'main' names
667 | n <- nameSetToList proto_used_names
668 , not (isWiredInName n) -- Don't record usages for wired-in names
669 , isExternalName n -- Ignore internal names
672 -- ent_map groups together all the things imported and used
673 -- from a particular module in this package
674 ent_map :: ModuleEnv [OccName]
675 ent_map = foldNameSet add_mv emptyModuleEnv used_names
676 add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [occ]
678 occ = nameOccName name
679 mod = nameModule name
680 add_item occs _ = occ:occs
682 usages = mapCatMaybes mkUsage (moduleEnvElts dep_mods)
683 -- ToDo: do we need to sort into canonical order?
685 import_all mod = case lookupModuleEnv dir_imp_mods mod of
686 Just (_,imp_all) -> isNothing imp_all
689 -- We want to create a Usage for a home module if
690 -- a) we used something from; has something in used_names
691 -- b) we imported all of it, even if we used nothing from it
692 -- (need to recompile if its export list changes: export_vers)
693 -- c) is a home-package orphan module (need to recompile if its
694 -- instance decls change: rules_vers)
695 mkUsage :: (ModuleName, Bool) -> Maybe Usage
696 mkUsage (mod_name, _)
697 | isNothing maybe_iface -- We can't depend on it if we didn't
698 || not (isHomeModule mod) -- even open the interface!
702 = Nothing -- Record no usage info
705 = Just (Usage { usg_name = moduleName mod,
707 usg_exports = export_vers,
708 usg_entities = ent_vers,
709 usg_rules = rules_vers })
711 maybe_iface = lookupIfaceByModName hpt pit mod_name
712 -- In one-shot mode, the interfaces for home-package
713 -- modules accumulate in the PIT not HPT. Sigh.
715 Just iface = maybe_iface
716 mod = mi_module iface
717 orphan_mod = mi_orphan iface
718 version_env = mi_ver_fn iface
719 mod_vers = mi_mod_vers iface
720 rules_vers = mi_rule_vers iface
721 all_imported = import_all mod
722 export_vers | all_imported = Just (mi_exp_vers iface)
723 | otherwise = Nothing
725 -- The sort is to put them into canonical order
726 used_occs = lookupModuleEnv ent_map mod `orElse` []
727 ent_vers :: [(OccName,Version)]
728 ent_vers = [ (occ, version_env occ `orElse` initialVersion)
729 | occ <- sortLt (<) used_occs]
733 mkIfaceExports :: NameSet -> [(ModuleName, [GenAvailInfo OccName])]
734 -- Group by module and sort by occurrence
735 -- This keeps the list in canonical order
736 mkIfaceExports exports
737 = [ (mkSysModuleNameFS fs, eltsFM avails)
738 | (fs, avails) <- fmToList groupFM
741 groupFM :: FiniteMap FastString (FiniteMap FastString (GenAvailInfo OccName))
742 -- Deliberately use the FastString so we
743 -- get a canonical ordering
744 groupFM = foldl add emptyFM (nameSetToList exports)
746 add env name = addToFM_C add_avail env mod_fs
747 (unitFM avail_fs avail)
749 occ = nameOccName name
750 occ_fs = occNameFS occ
751 mod_fs = moduleNameFS (nameModuleName name)
752 avail | Just p <- nameParent_maybe name = AvailTC (nameOccName p) [occ]
753 | isTcOcc occ = AvailTC occ [occ]
754 | otherwise = Avail occ
755 avail_fs = occNameFS (availName avail)
756 add_avail avail_fm _ = addToFM_C add_item avail_fm avail_fs avail
758 add_item (AvailTC p occs) _ = AvailTC p (insert occ occs)
759 add_item (Avail n) _ = pprPanic "MkIface.addAvail" (ppr n <+> ppr name)
763 %************************************************************************
765 Load the old interface file for this module (unless
766 we have it aleady), and check whether it is up to date
769 %************************************************************************
772 checkOldIface :: HscEnv
774 -> FilePath -- Where the interface file is
775 -> Bool -- Source unchanged
776 -> Maybe ModIface -- Old interface from compilation manager, if any
777 -> IO (RecompileRequired, Maybe ModIface)
779 checkOldIface hsc_env mod iface_path source_unchanged maybe_iface
780 = do { showPass (hsc_dflags hsc_env)
781 ("Checking old interface for " ++ moduleUserString mod) ;
783 ; initIfaceCheck hsc_env $
784 check_old_iface mod iface_path source_unchanged maybe_iface
787 check_old_iface this_mod iface_path source_unchanged maybe_iface
788 = -- CHECK WHETHER THE SOURCE HAS CHANGED
789 ifM (not source_unchanged)
790 (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
793 -- If the source has changed and we're in interactive mode, avoid reading
794 -- an interface; just return the one we might have been supplied with.
795 getGhciMode `thenM` \ ghci_mode ->
796 if (ghci_mode == Interactive) && not source_unchanged then
797 returnM (outOfDate, maybe_iface)
800 case maybe_iface of {
801 Just old_iface -> -- Use the one we already have
802 checkVersions source_unchanged old_iface `thenM` \ recomp ->
803 returnM (recomp, Just old_iface)
807 -- Try and read the old interface for the current module
808 -- from the .hi file left from the last time we compiled it
809 readIface (moduleName this_mod) iface_path False `thenM` \ read_result ->
810 case read_result of {
811 Left err -> -- Old interface file not found, or garbled; give up
812 traceIf (text "FYI: cannot read old interface file:"
813 $$ nest 4 err) `thenM_`
814 returnM (outOfDate, Nothing)
818 -- We have got the old iface; check its versions
819 checkVersions source_unchanged iface `thenM` \ recomp ->
820 returnM (recomp, Just iface)
824 @recompileRequired@ is called from the HscMain. It checks whether
825 a recompilation is required. It needs access to the persistent state,
826 finder, etc, because it may have to load lots of interface files to
827 check their versions.
830 type RecompileRequired = Bool
831 upToDate = False -- Recompile not required
832 outOfDate = True -- Recompile required
834 checkVersions :: Bool -- True <=> source unchanged
835 -> ModIface -- Old interface
836 -> IfG RecompileRequired
837 checkVersions source_unchanged iface
838 | not source_unchanged
841 = traceHiDiffs (text "Considering whether compilation is required for" <+>
842 ppr (mi_module iface) <> colon) `thenM_`
844 -- Source code unchanged and no errors yet... carry on
845 -- First put the dependent-module info in the envt, just temporarily,
846 -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
847 -- It's just temporary because either the usage check will succeed
848 -- (in which case we are done with this module) or it'll fail (in which
849 -- case we'll compile the module from scratch anyhow).
850 updGblEnv (\ gbl -> gbl { if_is_boot = mod_deps }) (
851 checkList [checkModUsage u | u <- mi_usages iface]
854 -- This is a bit of a hack really
855 mod_deps :: ModuleEnv (ModuleName, IsBootInterface)
856 mod_deps = mkModDeps (dep_mods (mi_deps iface))
858 checkModUsage :: Usage -> IfG RecompileRequired
859 -- Given the usage information extracted from the old
860 -- M.hi file for the module being compiled, figure out
861 -- whether M needs to be recompiled.
863 checkModUsage (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
864 usg_rules = old_rule_vers,
865 usg_exports = maybe_old_export_vers,
866 usg_entities = old_decl_vers })
867 = -- Load the imported interface is possible
869 doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
871 traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
873 loadInterface doc_str mod_name ImportBySystem `thenM` \ mb_iface ->
874 -- Load the interface, but don't complain on failure;
875 -- Instead, get an Either back which we can test
878 Left exn -> (out_of_date (sep [ptext SLIT("Can't find version number for module"),
880 -- Couldn't find or parse a module mentioned in the
881 -- old interface file. Don't complain -- it might just be that
882 -- the current module doesn't need that import and it's been deleted
886 new_mod_vers = mi_mod_vers iface
887 new_decl_vers = mi_ver_fn iface
888 new_export_vers = mi_exp_vers iface
889 new_rule_vers = mi_rule_vers iface
892 checkModuleVersion old_mod_vers new_mod_vers `thenM` \ recompile ->
893 if not recompile then
898 if checkExportList maybe_old_export_vers new_export_vers then
899 out_of_date_vers (ptext SLIT(" Export list changed"))
900 (fromJust maybe_old_export_vers)
905 if old_rule_vers /= new_rule_vers then
906 out_of_date_vers (ptext SLIT(" Rules changed"))
907 old_rule_vers new_rule_vers
910 -- CHECK ITEMS ONE BY ONE
911 checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers] `thenM` \ recompile ->
913 returnM outOfDate -- This one failed, so just bail out now
915 up_to_date (ptext SLIT(" Great! The bits I use are up to date"))
918 ------------------------
919 checkModuleVersion old_mod_vers new_mod_vers
920 | new_mod_vers == old_mod_vers
921 = up_to_date (ptext SLIT("Module version unchanged"))
924 = out_of_date_vers (ptext SLIT(" Module version has changed"))
925 old_mod_vers new_mod_vers
927 ------------------------
928 checkExportList Nothing new_vers = upToDate
929 checkExportList (Just v) new_vers = v /= new_vers
931 ------------------------
932 checkEntityUsage new_vers (name,old_vers)
933 = case new_vers name of
935 Nothing -> -- We used it before, but it ain't there now
936 out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
938 Just new_vers -- It's there, but is it up to date?
939 | new_vers == old_vers -> traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
941 | otherwise -> out_of_date_vers (ptext SLIT(" Out of date:") <+> ppr name)
944 up_to_date msg = traceHiDiffs msg `thenM_` returnM upToDate
945 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
946 out_of_date_vers msg old_vers new_vers
947 = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
949 ----------------------
950 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
951 -- This helper is used in two places
952 checkList [] = returnM upToDate
953 checkList (check:checks) = check `thenM` \ recompile ->
960 %************************************************************************
964 %************************************************************************
967 showIface :: FilePath -> IO ()
968 -- Raad binary interface, and print it out
969 showIface filename = do
970 -- skip the version check; we don't want to worry about profiled vs.
971 -- non-profiled interfaces, for example.
972 writeIORef v_IgnoreHiWay True
973 iface <- Binary.getBinFileWithDict filename
974 printDump (pprModIface iface)
980 pprModIface :: ModIface -> SDoc
983 = vcat [ ptext SLIT("interface")
984 <+> doubleQuotes (ftext (mi_package iface))
985 <+> ppr (mi_module iface) <+> ppr (mi_mod_vers iface)
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 exp_vers = mi_exp_vers iface
1001 rule_vers = mi_rule_vers iface
1003 pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
1004 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
1007 When printing export lists, we print like this:
1009 AvailTC C [C, x, y] C(x,y)
1010 AvailTC C [x, y] C!(x,y) -- Exporting x, y but not C
1013 pprExport :: IfaceExport -> SDoc
1014 pprExport (mod, items)
1015 = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
1017 pp_avail :: GenAvailInfo OccName -> SDoc
1018 pp_avail (Avail occ) = ppr occ
1019 pp_avail (AvailTC _ []) = empty
1020 pp_avail (AvailTC n (n':ns))
1021 | n==n' = ppr n <> pp_export ns
1022 | otherwise = ppr n <> char '|' <> pp_export (n':ns)
1024 pp_export [] = empty
1025 pp_export names = braces (hsep (map ppr names))
1027 pprUsage :: Usage -> SDoc
1029 = hsep [ptext SLIT("import"), ppr (usg_name usage),
1030 int (usg_mod usage),
1031 pp_export_version (usg_exports usage),
1032 int (usg_rules usage),
1033 pp_versions (usg_entities usage) ]
1035 pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
1036 pp_export_version Nothing = empty
1037 pp_export_version (Just v) = int v
1039 pprDeps :: Dependencies -> SDoc
1040 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
1041 = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
1042 ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs),
1043 ptext SLIT("orphans:") <+> fsep (map ppr orphs)
1046 ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
1047 ppr_boot True = text "[boot]"
1048 ppr_boot False = empty
1050 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
1051 pprIfaceDecl (ver, decl)
1052 = ppr_vers ver <+> ppr decl
1054 -- Print the version for the decl
1055 ppr_vers v | v == initialVersion = empty
1058 pprFixities :: [(OccName, Fixity)] -> SDoc
1059 pprFixities [] = empty
1060 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
1062 pprFix (occ,fix) = ppr fix <+> ppr occ
1064 pprDeprecs NoDeprecs = empty
1065 pprDeprecs (DeprecAll txt) = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
1066 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
1068 pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)