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