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