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