[project @ 2005-06-21 10:44:37 by simonmar]
[ghc-hetmet.git] / ghc / compiler / iface / MkIface.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4
5 \begin{code}
6 module MkIface ( 
7         pprModIface, showIface,         -- Print the iface in Foo.hi
8
9         mkUsageInfo,    -- Construct the usage info for a module
10
11         mkIface,        -- Build a ModIface from a ModGuts, 
12                         -- including computing version information
13
14         writeIfaceFile, -- Write the interface file
15
16         checkOldIface   -- See if recompilation is required, by
17                         -- comparing version information
18  ) where
19 \end{code}
20
21         -----------------------------------------------
22                 MkIface.lhs deals with versioning
23         -----------------------------------------------
24
25 Here's the version-related info in an interface file
26
27   module Foo 8          -- module-version 
28              3          -- export-list-version
29              2          -- rule-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
35
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
39         
40         -----------------------------------------------
41                         Basic idea
42         -----------------------------------------------
43
44 Basic idea: 
45   * In the mi_usages information in an interface, we record the 
46     version number of each free variable of the module
47
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.
52
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
55
56
57 Fixities
58 ~~~~~~~~
59 We count A.f as changing if its fixity changes
60
61 Rules
62 ~~~~~
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
68 either.
69
70 Orphan rules (ones whose 'head function' is not defined in M) are
71 harder.  Here's what we do.
72
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.)
75
76   * We record usage info for any orphan module 'below' this one,
77     giving the orphan-rule version number.  We recompile if this 
78     changes. 
79
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.
83
84 Instance decls
85 ~~~~~~~~~~~~~~
86 In an iface file we have
87      module A where
88         instance Eq a => Eq [a]  =  dfun29
89         dfun29 :: ... 
90
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.
98
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.
104
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
109     that tycon/class.
110
111   * For orphan instance decls, act the same way as for orphan rules.
112     Indeed, we use the same global orphan-rule version number.
113
114 mkUsageInfo
115 ~~~~~~~~~~~
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
118 things it uses.  
119
120 We produce a line for every module B below the module, A, currently being
121 compiled:
122         import B <n> ;
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.
127
128 The usage information records:
129
130 \begin{itemize}
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
134 \end{itemize}
135
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
139 recompilation.
140
141 Why (c)?  Consider this:
142 \begin{verbatim}
143         module A( f, g ) where  |       module B( f ) where
144           import B( f )         |         f = h 3
145           g = ...               |         h = ...
146 \end{verbatim}
147
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.
158
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.
165
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 ***
169
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.]
173
174
175 \begin{code}
176 #include "HsVersions.h"
177
178 import HsSyn
179 import Packages         ( isHomeModule, PackageIdH(..) )
180 import IfaceSyn         ( IfaceDecl(..), IfaceClassOp(..), IfaceConDecl(..),
181                           IfaceRule(..), IfaceInst(..), IfaceExtName(..), 
182                           eqIfDecl, eqIfRule, eqIfInst, IfaceEq(..), (&&&), bool, 
183                           eqMaybeBy, eqListBy, visibleIfConDecls,
184                           tyThingToIfaceDecl, instanceToIfaceInst, coreRuleToIfaceRule )
185 import LoadIface        ( readIface, loadInterface )
186 import BasicTypes       ( Version, initialVersion, bumpVersion )
187 import TcRnMonad
188 import TcRnTypes        ( mkModDeps )
189 import HscTypes         ( ModIface(..), ModDetails(..), 
190                           ModGuts(..), IfaceExport,
191                           HscEnv(..), hscEPS, Dependencies(..), FixItem(..), 
192                           ModSummary(..), msHiFilePath, 
193                           mkIfaceDepCache, mkIfaceFixCache, mkIfaceVerCache,
194                           typeEnvElts, 
195                           GenAvailInfo(..), availName, 
196                           ExternalPackageState(..),
197                           Usage(..), IsBootInterface,
198                           Deprecs(..), IfaceDeprecs, Deprecations,
199                           lookupIfaceByModule
200                         )
201
202
203 import Packages         ( HomeModules )
204 import DynFlags         ( GhcMode(..), DynFlags(..), DynFlag(..), dopt )
205 import StaticFlags      ( opt_HiVersion )
206 import Name             ( Name, nameModule, nameOccName, nameParent,
207                           isExternalName, isInternalName, nameParent_maybe, isWiredInName,
208                           isImplicitName, NamedThing(..) )
209 import NameEnv
210 import NameSet
211 import OccName          ( OccName, OccEnv, mkOccEnv, lookupOccEnv, emptyOccEnv,
212                           extendOccEnv_C,
213                           OccSet, emptyOccSet, elemOccSet, occSetElts, 
214                           extendOccSet, extendOccSetList,
215                           isEmptyOccSet, intersectOccSet, intersectsOccSet,
216                           occNameFS, isTcOcc )
217 import Module           ( Module, moduleFS,
218                           ModLocation(..), mkSysModuleFS, moduleUserString,
219                           ModuleEnv, emptyModuleEnv, lookupModuleEnv,
220                           extendModuleEnv_C
221                         )
222 import Outputable
223 import Util             ( createDirectoryHierarchy, directoryOf )
224 import Util             ( sortLe, seqList )
225 import Binary           ( getBinFileWithDict )
226 import BinIface         ( writeBinIface, v_IgnoreHiWay )
227 import Unique           ( Unique, Uniquable(..) )
228 import ErrUtils         ( dumpIfSet_dyn, showPass )
229 import Digraph          ( stronglyConnComp, SCC(..) )
230 import SrcLoc           ( SrcSpan )
231 import FiniteMap
232 import FastString
233
234 import DATA_IOREF       ( writeIORef )
235 import Monad            ( when )
236 import List             ( insert )
237 import Maybes           ( orElse, mapCatMaybes, isNothing, isJust, 
238                           fromJust, expectJust, MaybeErr(..) )
239 \end{code}
240
241
242
243 %************************************************************************
244 %*                                                                      *
245 \subsection{Completing an interface}
246 %*                                                                      *
247 %************************************************************************
248
249 \begin{code}
250 mkIface :: HscEnv
251         -> Maybe ModIface       -- The old interface, if we have it
252         -> ModGuts              -- Usages, deprecations, etc
253         -> ModDetails           -- The trimmed, tidied interface
254         -> IO (ModIface,        -- The new one, complete with decls and versions
255                Bool)            -- True <=> there was an old Iface, and the new one
256                                 --          is identical, so no need to write it
257
258 mkIface hsc_env maybe_old_iface 
259         (ModGuts{     mg_module  = this_mod,
260                       mg_boot    = is_boot,
261                       mg_usages  = usages,
262                       mg_deps    = deps,
263                       mg_home_mods = home_mods,
264                       mg_rdr_env = rdr_env,
265                       mg_fix_env = fix_env,
266                       mg_deprecs = src_deprecs })
267         (ModDetails{  md_insts   = insts, 
268                       md_rules   = rules,
269                       md_types   = type_env,
270                       md_exports = exports })
271         
272 -- NB:  notice that mkIface does not look at the bindings
273 --      only at the TypeEnv.  The previous Tidy phase has
274 --      put exactly the info into the TypeEnv that we want
275 --      to expose in the interface
276
277   = do  { eps <- hscEPS hsc_env
278         ; let   { ext_nm_rhs = mkExtNameFn hsc_env home_mods eps this_mod
279                 ; ext_nm_lhs = mkLhsNameFn this_mod
280
281                 ; decls  = [ tyThingToIfaceDecl ext_nm_rhs thing 
282                            | thing <- typeEnvElts type_env, 
283                              not (isImplicitName (getName thing)) ]
284                         -- Don't put implicit Ids and class tycons in the interface file
285
286                 ; fixities    = [(occ,fix) | FixItem occ fix _ <- nameEnvElts fix_env]
287                 ; deprecs     = mkIfaceDeprec src_deprecs
288                 ; iface_rules = map (coreRuleToIfaceRule ext_nm_lhs ext_nm_rhs) rules
289                 ; iface_insts = map (instanceToIfaceInst ext_nm_lhs) insts
290
291                 ; intermediate_iface = ModIface { 
292                         mi_module   = this_mod,
293                         mi_package  = HomePackage,
294                         mi_boot     = is_boot,
295                         mi_deps     = deps,
296                         mi_usages   = usages,
297                         mi_exports  = mkIfaceExports exports,
298                         mi_insts    = sortLe le_inst iface_insts,
299                         mi_rules    = sortLe le_rule iface_rules,
300                         mi_fixities = fixities,
301                         mi_deprecs  = deprecs,
302                         mi_globals  = Just rdr_env,
303
304                         -- Left out deliberately: filled in by addVersionInfo
305                         mi_mod_vers  = initialVersion,
306                         mi_exp_vers  = initialVersion,
307                         mi_rule_vers = initialVersion,
308                         mi_orphan    = False,   -- Always set by addVersionInfo, but
309                                                 -- it's a strict field, so we can't omit it.
310                         mi_decls     = deliberatelyOmitted "decls",
311                         mi_ver_fn    = deliberatelyOmitted "ver_fn",
312
313                         -- And build the cached values
314                         mi_dep_fn = mkIfaceDepCache deprecs,
315                         mi_fix_fn = mkIfaceFixCache fixities }
316
317                 -- Add version information
318                 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs) 
319                         = _scc_ "versioninfo" 
320                          addVersionInfo maybe_old_iface intermediate_iface decls
321                 }
322
323                 -- Debug printing
324         ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags) 
325                (printDump (fromJust pp_orphs))
326         ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
327         ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE" 
328                         (pprModIface new_iface)
329
330         ; return (new_iface, no_change_at_all) }
331   where
332      r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
333      i1 `le_inst` i2 = ifDFun     i1 <= ifDFun     i2
334
335      dflags = hsc_dflags hsc_env
336      deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
337
338                                               
339 -----------------------------
340 writeIfaceFile :: HscEnv -> ModLocation -> ModIface -> Bool -> IO ()
341 -- Write the interface file, if necessary
342 writeIfaceFile hsc_env location new_iface no_change_at_all
343   | no_change_at_all          = return ()
344   | ghc_mode == Interactive   = return ()
345   | ghc_mode == JustTypecheck = return ()
346   | otherwise
347   = do  { createDirectoryHierarchy (directoryOf hi_file_path)
348         ; writeBinIface hi_file_path new_iface }
349   where
350      ghc_mode = ghcMode (hsc_dflags hsc_env)
351      hi_file_path = ml_hi_file location
352
353
354 -----------------------------
355 mkExtNameFn :: HscEnv -> HomeModules -> ExternalPackageState -> Module -> Name -> IfaceExtName
356 mkExtNameFn hsc_env hmods eps this_mod
357   = ext_nm
358   where
359     hpt = hsc_HPT hsc_env
360     pit = eps_PIT eps
361
362     ext_nm name 
363       | mod == this_mod = case nameParent_maybe name of
364                                 Nothing  -> LocalTop occ
365                                 Just par -> LocalTopSub occ (nameOccName par)
366       | isWiredInName name       = ExtPkg  mod occ
367       | isHomeModule hmods mod   = HomePkg mod occ vers
368       | otherwise                = ExtPkg  mod occ
369       where
370         mod      = nameModule name
371         occ      = nameOccName name
372         par_occ  = nameOccName (nameParent name)
373                 -- The version of the *parent* is the one want
374         vers     = lookupVersion mod par_occ
375               
376     lookupVersion :: Module -> OccName -> Version
377         -- Even though we're looking up a home-package thing, in
378         -- one-shot mode the imported interfaces may be in the PIT
379     lookupVersion mod occ
380       = mi_ver_fn iface occ `orElse` 
381         pprPanic "lookupVers1" (ppr mod <+> ppr occ)
382       where
383         iface = lookupIfaceByModule hpt pit mod `orElse` 
384                 pprPanic "lookupVers2" (ppr mod <+> ppr occ)
385
386
387 ---------------------
388 -- mkLhsNameFn ignores versioning info altogether
389 -- It is used for the LHS of instance decls and rules, where we 
390 -- there's no point in recording version info
391 mkLhsNameFn :: Module -> Name -> IfaceExtName
392 mkLhsNameFn this_mod name       
393   | isInternalName name = pprTrace "mkLhsNameFn: unexpected internal" (ppr name) $
394                           LocalTop occ  -- Should not happen
395   | mod == this_mod = LocalTop occ
396   | otherwise       = ExtPkg mod occ
397   where
398     mod = nameModule name
399     occ = nameOccName name
400
401
402 -----------------------------
403 -- Compute version numbers for local decls
404
405 addVersionInfo :: Maybe ModIface        -- The old interface, read from M.hi
406                -> ModIface              -- The new interface decls (lacking decls)
407                -> [IfaceDecl]           -- The new decls
408                -> (ModIface, 
409                    Bool,                -- True <=> no changes at all; no need to write new Iface
410                    SDoc,                -- Differences
411                    Maybe SDoc)          -- Warnings about orphans
412
413 addVersionInfo Nothing new_iface new_decls
414 -- No old interface, so definitely write a new one!
415   = (new_iface { mi_orphan = anyNothing ifInstOrph (mi_insts new_iface)
416                           || anyNothing ifRuleOrph (mi_rules new_iface),
417                  mi_decls  = [(initialVersion, decl) | decl <- new_decls],
418                  mi_ver_fn = \n -> Just initialVersion },
419      False, 
420      ptext SLIT("No old interface file"),
421      pprOrphans orph_insts orph_rules)
422   where
423     orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
424     orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
425
426 addVersionInfo (Just old_iface@(ModIface { mi_mod_vers  = old_mod_vers, 
427                                            mi_exp_vers  = old_exp_vers, 
428                                            mi_rule_vers = old_rule_vers, 
429                                            mi_decls     = old_decls,
430                                            mi_ver_fn    = old_decl_vers,
431                                            mi_fix_fn    = old_fixities }))
432                new_iface@(ModIface { mi_fix_fn = new_fixities })
433                new_decls
434
435   | no_change_at_all = (old_iface,   True,  ptext SLIT("Interface file unchanged"), pp_orphs)
436   | otherwise        = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
437                                                   nest 2 pp_diffs], pp_orphs)
438   where
439     final_iface = new_iface { mi_mod_vers  = bump_unless no_output_change old_mod_vers,
440                               mi_exp_vers  = bump_unless no_export_change old_exp_vers,
441                               mi_rule_vers = bump_unless no_rule_change   old_rule_vers,
442                               mi_orphan    = not (null new_orph_rules && null new_orph_insts),
443                               mi_decls     = decls_w_vers,
444                               mi_ver_fn    = mkIfaceVerCache decls_w_vers }
445
446     decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
447
448     -------------------
449     (old_non_orph_insts, old_orph_insts) = mkOrphMap ifInstOrph (mi_insts old_iface)
450     (new_non_orph_insts, new_orph_insts) = mkOrphMap ifInstOrph (mi_insts new_iface)
451     same_insts occ = eqMaybeBy  (eqListBy eqIfInst) 
452                                 (lookupOccEnv old_non_orph_insts occ)
453                                 (lookupOccEnv new_non_orph_insts occ)
454   
455     (old_non_orph_rules, old_orph_rules) = mkOrphMap ifRuleOrph (mi_rules old_iface)
456     (new_non_orph_rules, new_orph_rules) = mkOrphMap ifRuleOrph (mi_rules new_iface)
457     same_rules occ = eqMaybeBy  (eqListBy eqIfRule)
458                                 (lookupOccEnv old_non_orph_rules occ)
459                                 (lookupOccEnv new_non_orph_rules occ)
460     -------------------
461     -- Computing what changed
462     no_output_change = no_decl_change   && no_rule_change && 
463                        no_export_change && no_deprec_change
464     no_export_change = mi_exports new_iface == mi_exports old_iface     -- Kept sorted
465     no_decl_change   = isEmptyOccSet changed_occs
466     no_rule_change   = not (changedWrt changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
467                          || changedWrt changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts))
468     no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
469
470         -- If the usages havn't changed either, we don't need to write the interface file
471     no_other_changes = mi_usages new_iface == mi_usages old_iface && 
472                        mi_deps new_iface == mi_deps old_iface
473     no_change_at_all = no_output_change && no_other_changes
474  
475     pp_diffs = vcat [pp_change no_export_change "Export list" 
476                         (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
477                      pp_change no_rule_change "Rules"
478                         (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
479                      pp_change no_deprec_change "Deprecations" empty,
480                      pp_change no_other_changes  "Usages" empty,
481                      pp_decl_diffs]
482     pp_change True  what info = empty
483     pp_change False what info = text what <+> ptext SLIT("changed") <+> info
484
485     -------------------
486     old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
487     same_fixity n = bool (old_fixities n == new_fixities n)
488
489     -------------------
490     -- Adding version info
491     new_version     = bumpVersion old_mod_vers
492     add_vers decl | occ `elemOccSet` changed_occs = new_version
493                   | otherwise = expectJust "add_vers" (old_decl_vers occ)
494                                 -- If it's unchanged, there jolly well 
495                   where         -- should be an old version number
496                     occ = ifName decl
497
498     -------------------
499     changed_occs :: OccSet
500     changed_occs = computeChangedOccs eq_info
501
502     eq_info :: [(OccName, IfaceEq)]
503     eq_info = map check_eq new_decls
504     check_eq new_decl | Just old_decl <- lookupOccEnv old_decl_env occ 
505                       = (occ, new_decl `eqIfDecl` old_decl &&&
506                               eq_indirects new_decl)
507                       | otherwise {- No corresponding old decl -}      
508                       = (occ, NotEqual) 
509                       where
510                         occ = ifName new_decl
511
512     eq_indirects :: IfaceDecl -> IfaceEq
513                 -- When seeing if two decls are the same, remember to
514                 -- check whether any relevant fixity or rules have changed
515     eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
516     eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
517         = same_insts cls_occ &&& 
518           eq_ind_occs [op | IfaceClassOp op _ _ <- sigs] 
519     eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
520         = same_insts tc_occ &&& same_fixity tc_occ &&&  -- The TyCon can have a fixity too
521           eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
522     eq_indirects other = Equal  -- Synonyms and foreign declarations
523
524     eq_ind_occ :: OccName -> IfaceEq    -- For class ops and Ids; check fixity and rules
525     eq_ind_occ occ = same_fixity occ &&& same_rules occ
526     eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal 
527    
528     -------------------
529     -- Diffs
530     pp_decl_diffs :: SDoc       -- Nothing => no changes
531     pp_decl_diffs 
532         | isEmptyOccSet changed_occs = empty
533         | otherwise 
534         = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
535                 ptext SLIT("Version change for these decls:"),
536                 nest 2 (vcat (map show_change new_decls))]
537
538     eq_env = mkOccEnv eq_info
539     show_change new_decl
540         | not (occ `elemOccSet` changed_occs) = empty
541         | otherwise
542         = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version, 
543                 nest 2 why]
544         where
545           occ = ifName new_decl
546           why = case lookupOccEnv eq_env occ of
547                     Just (EqBut occs) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:"),
548                                               nest 2 (braces (fsep (map ppr (occSetElts 
549                                                 (occs `intersectOccSet` changed_occs)))))]
550                     Just NotEqual  
551                         | Just old_decl <- lookupOccEnv old_decl_env occ 
552                         -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
553                          ptext SLIT("New:") <+> ppr new_decl]
554                         | otherwise 
555                         -> ppr occ <+> ptext SLIT("only in new interface")
556                     other -> pprPanic "MkIface.show_change" (ppr occ)
557         
558     pp_orphs = pprOrphans new_orph_insts new_orph_rules
559
560 pprOrphans insts rules
561   | null insts && null rules = Nothing
562   | otherwise
563   = Just $ vcat [
564         if null insts then empty else
565              hang (ptext SLIT("Warning: orphan instances:"))
566                 2 (vcat (map ppr insts)),
567         if null rules then empty else
568              hang (ptext SLIT("Warning: orphan rules:"))
569                 2 (vcat (map ppr rules))
570     ]
571
572 computeChangedOccs :: [(OccName, IfaceEq)] -> OccSet
573 computeChangedOccs eq_info
574   = foldl add_changes emptyOccSet (stronglyConnComp edges)
575   where
576     edges :: [((OccName,IfaceEq), Unique, [Unique])]
577     edges = [ (node, getUnique occ, map getUnique occs)
578             | node@(occ, iface_eq) <- eq_info
579             , let occs = case iface_eq of
580                            EqBut occ_set -> occSetElts occ_set
581                            other -> [] ]
582
583     -- Changes in declarations
584     add_changes :: OccSet -> SCC (OccName, IfaceEq) -> OccSet
585     add_changes so_far (AcyclicSCC (occ, iface_eq)) 
586         | changedWrt so_far iface_eq                            -- This one has changed
587         = extendOccSet so_far occ
588     add_changes so_far (CyclicSCC pairs)
589         | changedWrt so_far (foldr1 (&&&) (map snd pairs))      -- One of this group has changed
590         = extendOccSetList so_far (map fst pairs)
591     add_changes so_far other = so_far
592
593 changedWrt :: OccSet -> IfaceEq -> Bool
594 changedWrt so_far Equal        = False
595 changedWrt so_far NotEqual     = True
596 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
597
598 ----------------------
599 -- mkOrphMap partitions instance decls or rules into
600 --      (a) an OccEnv for ones that are not orphans, 
601 --          mapping the local OccName to a list of its decls
602 --      (b) a list of orphan decls
603 mkOrphMap :: (decl -> Maybe OccName)    -- (Just occ) for a non-orphan decl, keyed by occ
604                                         -- Nothing for an orphan decl
605           -> [decl]                     -- Sorted into canonical order
606           -> (OccEnv [decl],            -- Non-orphan decls associated with their key;
607                                         --      each sublist in canonical order
608               [decl])                   -- Orphan decls; in canonical order
609 mkOrphMap get_key decls
610   = foldl go (emptyOccEnv, []) decls
611   where
612     go (non_orphs, orphs) d
613         | Just occ <- get_key d
614         = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
615         | otherwise = (non_orphs, d:orphs)
616
617 anyNothing :: (a -> Maybe b) -> [a] -> Bool
618 anyNothing p []     = False
619 anyNothing p (x:xs) = isNothing (p x) || anyNothing p xs
620
621 ----------------------
622 mkIfaceDeprec :: Deprecations -> IfaceDeprecs
623 mkIfaceDeprec NoDeprecs        = NoDeprecs
624 mkIfaceDeprec (DeprecAll t)    = DeprecAll t
625 mkIfaceDeprec (DeprecSome env) = DeprecSome (sortLe (<=) (nameEnvElts env))
626
627 ----------------------
628 bump_unless :: Bool -> Version -> Version
629 bump_unless True  v = v -- True <=> no change
630 bump_unless False v = bumpVersion v
631 \end{code}
632
633
634 %*********************************************************
635 %*                                                      *
636 \subsection{Keeping track of what we've slurped, and version numbers}
637 %*                                                      *
638 %*********************************************************
639
640
641 \begin{code}
642 mkUsageInfo :: HscEnv 
643             -> HomeModules
644             -> ModuleEnv (Module, Maybe Bool, SrcSpan)
645             -> [(Module, IsBootInterface)]
646             -> NameSet -> IO [Usage]
647 mkUsageInfo hsc_env hmods dir_imp_mods dep_mods used_names
648   = do  { eps <- hscEPS hsc_env
649         ; let usages = mk_usage_info (eps_PIT eps) hsc_env hmods
650                                      dir_imp_mods dep_mods used_names
651         ; usages `seqList`  return usages }
652          -- seq the list of Usages returned: occasionally these
653          -- don't get evaluated for a while and we can end up hanging on to
654          -- the entire collection of Ifaces.
655
656 mk_usage_info pit hsc_env hmods dir_imp_mods dep_mods proto_used_names
657   = mapCatMaybes mkUsage dep_mods
658         -- ToDo: do we need to sort into canonical order?
659   where
660     dflags = hsc_dflags hsc_env
661     hpt = hsc_HPT hsc_env
662
663     used_names = mkNameSet $                    -- Eliminate duplicates
664                  [ nameParent n                 -- Just record usage on the 'main' names
665                  | n <- nameSetToList proto_used_names
666                  , not (isWiredInName n)        -- Don't record usages for wired-in names
667                  , isExternalName n             -- Ignore internal names
668                  ]
669
670     -- ent_map groups together all the things imported and used
671     -- from a particular module in this package
672     ent_map :: ModuleEnv [OccName]
673     ent_map  = foldNameSet add_mv emptyModuleEnv used_names
674     add_mv name mv_map = extendModuleEnv_C add_item mv_map mod [occ]
675                    where
676                      occ = nameOccName name
677                      mod = nameModule name
678                      add_item occs _ = occ:occs
679     
680     import_all mod = case lookupModuleEnv dir_imp_mods mod of
681                         Just (_,imp_all,_) -> isNothing imp_all
682                         Nothing            -> False
683     
684     -- We want to create a Usage for a home module if 
685     --  a) we used something from; has something in used_names
686     --  b) we imported all of it, even if we used nothing from it
687     --          (need to recompile if its export list changes: export_vers)
688     --  c) is a home-package orphan module (need to recompile if its
689     --          instance decls change: rules_vers)
690     mkUsage :: (Module, Bool) -> Maybe Usage
691     mkUsage (mod_name, _)
692       |  isNothing maybe_iface  -- We can't depend on it if we didn't
693       || not (isHomeModule hmods mod)   -- even open the interface!
694       || (null used_occs
695           && not all_imported
696           && not orphan_mod)
697       = Nothing                 -- Record no usage info
698     
699       | otherwise       
700       = Just (Usage { usg_name     = mod,
701                       usg_mod      = mod_vers,
702                       usg_exports  = export_vers,
703                       usg_entities = ent_vers,
704                       usg_rules    = rules_vers })
705       where
706         maybe_iface  = lookupIfaceByModule hpt pit mod_name
707                 -- In one-shot mode, the interfaces for home-package 
708                 -- modules accumulate in the PIT not HPT.  Sigh.
709
710         Just iface   = maybe_iface
711         mod          = mi_module    iface
712         orphan_mod   = mi_orphan    iface
713         version_env  = mi_ver_fn    iface
714         mod_vers     = mi_mod_vers  iface
715         rules_vers   = mi_rule_vers iface
716         all_imported = import_all mod 
717         export_vers | all_imported = Just (mi_exp_vers iface)
718                     | otherwise    = Nothing
719     
720         -- The sort is to put them into canonical order
721         used_occs = lookupModuleEnv ent_map mod `orElse` []
722         ent_vers :: [(OccName,Version)]
723         ent_vers = [ (occ, version_env occ `orElse` initialVersion) 
724                    | occ <- sortLe (<=) used_occs]
725 \end{code}
726
727 \begin{code}
728 mkIfaceExports :: NameSet -> [(Module, [GenAvailInfo OccName])]
729   -- Group by module and sort by occurrence
730   -- This keeps the list in canonical order
731 mkIfaceExports exports 
732   = [ (mkSysModuleFS fs, eltsFM avails)
733     | (fs, avails) <- fmToList groupFM
734     ]
735   where
736     groupFM :: FiniteMap FastString (FiniteMap FastString (GenAvailInfo OccName))
737         -- Deliberately use the FastString so we
738         -- get a canonical ordering
739     groupFM = foldl add emptyFM (nameSetToList exports)
740
741     add env name = addToFM_C add_avail env mod_fs 
742                              (unitFM avail_fs avail)
743       where
744         occ    = nameOccName name
745         mod_fs = moduleFS (nameModule name)
746         avail | Just p <- nameParent_maybe name = AvailTC (nameOccName p) [occ]
747               | isTcOcc occ                     = AvailTC occ [occ]
748               | otherwise                       = Avail occ
749         avail_fs = occNameFS (availName avail)      
750         add_avail avail_fm _ = addToFM_C add_item avail_fm avail_fs avail
751
752         add_item (AvailTC p occs) _ = AvailTC p (List.insert occ occs)
753         add_item (Avail n)        _ = pprPanic "MkIface.addAvail" (ppr n <+> ppr name)
754 \end{code}
755
756
757 %************************************************************************
758 %*                                                                      *
759         Load the old interface file for this module (unless
760         we have it aleady), and check whether it is up to date
761         
762 %*                                                                      *
763 %************************************************************************
764
765 \begin{code}
766 checkOldIface :: HscEnv
767               -> ModSummary
768               -> Bool                   -- Source unchanged
769               -> Maybe ModIface         -- Old interface from compilation manager, if any
770               -> IO (RecompileRequired, Maybe ModIface)
771
772 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
773   = do  { showPass (hsc_dflags hsc_env) 
774                    ("Checking old interface for " ++ moduleUserString (ms_mod mod_summary)) ;
775
776         ; initIfaceCheck hsc_env $
777           check_old_iface mod_summary source_unchanged maybe_iface
778      }
779
780 check_old_iface mod_summary source_unchanged maybe_iface
781  =      -- CHECK WHETHER THE SOURCE HAS CHANGED
782     ifM (not source_unchanged)
783         (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
784                                                 `thenM_`
785
786      -- If the source has changed and we're in interactive mode, avoid reading
787      -- an interface; just return the one we might have been supplied with.
788     getGhciMode                                 `thenM` \ ghci_mode ->
789     if (ghci_mode == Interactive || ghci_mode == JustTypecheck) 
790         && not source_unchanged then
791          returnM (outOfDate, maybe_iface)
792     else
793
794     case maybe_iface of {
795        Just old_iface -> -- Use the one we already have
796                          checkVersions source_unchanged old_iface       `thenM` \ recomp ->
797                          returnM (recomp, Just old_iface)
798
799     ;  Nothing ->
800
801         -- Try and read the old interface for the current module
802         -- from the .hi file left from the last time we compiled it
803     let
804         iface_path = msHiFilePath mod_summary
805     in
806     readIface (ms_mod mod_summary) iface_path False     `thenM` \ read_result ->
807     case read_result of {
808        Failed err ->    -- Old interface file not found, or garbled; give up
809                    traceIf (text "FYI: cannot read old interface file:"
810                                  $$ nest 4 err)         `thenM_`
811                    returnM (outOfDate, Nothing)
812
813     ;  Succeeded iface ->       
814
815         -- We have got the old iface; check its versions
816     checkVersions source_unchanged iface        `thenM` \ recomp ->
817     returnM (recomp, Just iface)
818     }}
819 \end{code}
820
821 @recompileRequired@ is called from the HscMain.   It checks whether
822 a recompilation is required.  It needs access to the persistent state,
823 finder, etc, because it may have to load lots of interface files to
824 check their versions.
825
826 \begin{code}
827 type RecompileRequired = Bool
828 upToDate  = False       -- Recompile not required
829 outOfDate = True        -- Recompile required
830
831 checkVersions :: Bool           -- True <=> source unchanged
832               -> ModIface       -- Old interface
833               -> IfG RecompileRequired
834 checkVersions source_unchanged iface
835   | not source_unchanged
836   = returnM outOfDate
837   | otherwise
838   = do  { traceHiDiffs (text "Considering whether compilation is required for" <+> 
839                         ppr (mi_module iface) <> colon)
840
841         -- Source code unchanged and no errors yet... carry on 
842
843         -- First put the dependent-module info, read from the old interface, into the envt, 
844         -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
845         -- 
846         -- It's just temporary because either the usage check will succeed 
847         -- (in which case we are done with this module) or it'll fail (in which
848         -- case we'll compile the module from scratch anyhow).
849         --      
850         -- We do this regardless of compilation mode
851         ; updateEps_ $ \eps  -> eps { eps_is_boot = mod_deps }
852
853         ; checkList [checkModUsage u | u <- mi_usages iface]
854     }
855   where
856         -- This is a bit of a hack really
857     mod_deps :: ModuleEnv (Module, IsBootInterface)
858     mod_deps = mkModDeps (dep_mods (mi_deps iface))
859
860 checkModUsage :: Usage -> IfG RecompileRequired
861 -- Given the usage information extracted from the old
862 -- M.hi file for the module being compiled, figure out
863 -- whether M needs to be recompiled.
864
865 checkModUsage (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
866                        usg_rules = old_rule_vers,
867                        usg_exports = maybe_old_export_vers, 
868                        usg_entities = old_decl_vers })
869   =     -- Load the imported interface is possible
870     let
871         doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
872     in
873     traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
874
875     loadInterface doc_str mod_name ImportBySystem       `thenM` \ mb_iface ->
876         -- Load the interface, but don't complain on failure;
877         -- Instead, get an Either back which we can test
878
879     case mb_iface of {
880         Failed exn ->  (out_of_date (sep [ptext SLIT("Can't find version number for module"), 
881                                        ppr mod_name]));
882                 -- Couldn't find or parse a module mentioned in the
883                 -- old interface file.  Don't complain -- it might just be that
884                 -- the current module doesn't need that import and it's been deleted
885
886         Succeeded iface -> 
887     let
888         new_mod_vers    = mi_mod_vers  iface
889         new_decl_vers   = mi_ver_fn    iface
890         new_export_vers = mi_exp_vers  iface
891         new_rule_vers   = mi_rule_vers iface
892     in
893         -- CHECK MODULE
894     checkModuleVersion old_mod_vers new_mod_vers        `thenM` \ recompile ->
895     if not recompile then
896         returnM upToDate
897     else
898                                  
899         -- CHECK EXPORT LIST
900     if checkExportList maybe_old_export_vers new_export_vers then
901         out_of_date_vers (ptext SLIT("  Export list changed"))
902                          (fromJust maybe_old_export_vers) 
903                          new_export_vers
904     else
905
906         -- CHECK RULES
907     if old_rule_vers /= new_rule_vers then
908         out_of_date_vers (ptext SLIT("  Rules changed")) 
909                          old_rule_vers new_rule_vers
910     else
911
912         -- CHECK ITEMS ONE BY ONE
913     checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]   `thenM` \ recompile ->
914     if recompile then
915         returnM outOfDate       -- This one failed, so just bail out now
916     else
917         up_to_date (ptext SLIT("  Great!  The bits I use are up to date"))
918     }
919
920 ------------------------
921 checkModuleVersion old_mod_vers new_mod_vers
922   | new_mod_vers == old_mod_vers
923   = up_to_date (ptext SLIT("Module version unchanged"))
924
925   | otherwise
926   = out_of_date_vers (ptext SLIT("  Module version has changed"))
927                      old_mod_vers new_mod_vers
928
929 ------------------------
930 checkExportList Nothing  new_vers = upToDate
931 checkExportList (Just v) new_vers = v /= new_vers
932
933 ------------------------
934 checkEntityUsage new_vers (name,old_vers)
935   = case new_vers name of
936
937         Nothing       ->        -- We used it before, but it ain't there now
938                           out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
939
940         Just new_vers   -- It's there, but is it up to date?
941           | new_vers == old_vers -> traceHiDiffs (text "  Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
942                                     returnM upToDate
943           | otherwise            -> out_of_date_vers (ptext SLIT("  Out of date:") <+> ppr name)
944                                                      old_vers new_vers
945
946 up_to_date  msg = traceHiDiffs msg `thenM_` returnM upToDate
947 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
948 out_of_date_vers msg old_vers new_vers 
949   = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
950
951 ----------------------
952 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
953 -- This helper is used in two places
954 checkList []             = returnM upToDate
955 checkList (check:checks) = check        `thenM` \ recompile ->
956                            if recompile then 
957                                 returnM outOfDate
958                            else
959                                 checkList checks
960 \end{code}
961
962 %************************************************************************
963 %*                                                                      *
964                 Printing interfaces
965 %*                                                                      *
966 %************************************************************************
967
968 \begin{code}
969 showIface :: FilePath -> IO ()
970 -- Read binary interface, and print it out
971 showIface filename = do
972    -- skip the version check; we don't want to worry about profiled vs.
973    -- non-profiled interfaces, for example.
974    writeIORef v_IgnoreHiWay True
975    iface <- Binary.getBinFileWithDict filename
976    printDump (pprModIface iface)
977  where
978 \end{code}
979
980
981 \begin{code}
982 pprModIface :: ModIface -> SDoc
983 -- Show a ModIface
984 pprModIface iface
985  = vcat [ ptext SLIT("interface")
986                 <+> ppr_package (mi_package iface)
987                 <+> ppr (mi_module iface) <+> pp_boot 
988                 <+> ppr (mi_mod_vers iface) <+> pp_sub_vers
989                 <+> (if mi_orphan iface then ptext SLIT("[orphan module]") else empty)
990                 <+> int opt_HiVersion
991                 <+> ptext SLIT("where")
992         , vcat (map pprExport (mi_exports iface))
993         , pprDeps (mi_deps iface)
994         , vcat (map pprUsage (mi_usages iface))
995         , pprFixities (mi_fixities iface)
996         , vcat (map pprIfaceDecl (mi_decls iface))
997         , vcat (map ppr (mi_insts iface))
998         , vcat (map ppr (mi_rules iface))
999         , pprDeprecs (mi_deprecs iface)
1000         ]
1001   where
1002     pp_boot | mi_boot iface = ptext SLIT("[boot]")
1003             | otherwise     = empty
1004     ppr_package HomePackage = empty
1005     ppr_package (ExtPackage id) = doubleQuotes (ppr id)
1006
1007     exp_vers  = mi_exp_vers iface
1008     rule_vers = mi_rule_vers iface
1009
1010     pp_sub_vers | exp_vers == initialVersion && rule_vers == initialVersion = empty
1011                 | otherwise = brackets (ppr exp_vers <+> ppr rule_vers)
1012 \end{code}
1013
1014 When printing export lists, we print like this:
1015         Avail   f               f
1016         AvailTC C [C, x, y]     C(x,y)
1017         AvailTC C [x, y]        C!(x,y)         -- Exporting x, y but not C
1018
1019 \begin{code}
1020 pprExport :: IfaceExport -> SDoc
1021 pprExport (mod, items)
1022  = hsep [ ptext SLIT("export"), ppr mod, hsep (map pp_avail items) ]
1023   where
1024     pp_avail :: GenAvailInfo OccName -> SDoc
1025     pp_avail (Avail occ)    = ppr occ
1026     pp_avail (AvailTC _ []) = empty
1027     pp_avail (AvailTC n (n':ns)) 
1028         | n==n'     = ppr n <> pp_export ns
1029         | otherwise = ppr n <> char '|' <> pp_export (n':ns)
1030     
1031     pp_export []    = empty
1032     pp_export names = braces (hsep (map ppr names))
1033
1034 pprUsage :: Usage -> SDoc
1035 pprUsage usage
1036   = hsep [ptext SLIT("import"), ppr (usg_name usage), 
1037           int (usg_mod usage), 
1038           pp_export_version (usg_exports usage),
1039           int (usg_rules usage),
1040           pp_versions (usg_entities usage) ]
1041   where
1042     pp_versions nvs = hsep [ ppr n <+> int v | (n,v) <- nvs ]
1043     pp_export_version Nothing  = empty
1044     pp_export_version (Just v) = int v
1045
1046 pprDeps :: Dependencies -> SDoc
1047 pprDeps (Deps { dep_mods = mods, dep_pkgs = pkgs, dep_orphs = orphs})
1048   = vcat [ptext SLIT("module dependencies:") <+> fsep (map ppr_mod mods),
1049           ptext SLIT("package dependencies:") <+> fsep (map ppr pkgs), 
1050           ptext SLIT("orphans:") <+> fsep (map ppr orphs)
1051         ]
1052   where
1053     ppr_mod (mod_name, boot) = ppr mod_name <+> ppr_boot boot
1054     ppr_boot True  = text "[boot]"
1055     ppr_boot False = empty
1056
1057 pprIfaceDecl :: (Version, IfaceDecl) -> SDoc
1058 pprIfaceDecl (ver, decl)
1059   = ppr_vers ver <+> ppr decl
1060   where
1061         -- Print the version for the decl
1062     ppr_vers v | v == initialVersion = empty
1063                | otherwise           = int v
1064
1065 pprFixities :: [(OccName, Fixity)] -> SDoc
1066 pprFixities []    = empty
1067 pprFixities fixes = ptext SLIT("fixities") <+> pprWithCommas pprFix fixes
1068                   where
1069                     pprFix (occ,fix) = ppr fix <+> ppr occ 
1070
1071 pprDeprecs NoDeprecs        = empty
1072 pprDeprecs (DeprecAll txt)  = ptext SLIT("Deprecate all") <+> doubleQuotes (ftext txt)
1073 pprDeprecs (DeprecSome prs) = ptext SLIT("Deprecate") <+> vcat (map pprDeprec prs)
1074                             where
1075                               pprDeprec (name, txt) = ppr name <+> doubleQuotes (ftext txt)
1076 \end{code}