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