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