FIX #1617: reloading didn't change the :browse output as it should
[ghc-hetmet.git] / compiler / iface / MkIface.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 %
5
6 \begin{code}
7 {-# OPTIONS -w #-}
8 -- The above warning supression flag is a temporary kludge.
9 -- While working on this module you are encouraged to remove it and fix
10 -- any warnings in the module. See
11 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
12 -- for details
13
14 module MkIface ( 
15         mkUsedNames,
16         mkDependencies,
17         mkIface,        -- Build a ModIface from a ModGuts, 
18                         -- including computing version information
19
20         mkIfaceTc,
21
22         writeIfaceFile, -- Write the interface file
23
24         checkOldIface,  -- See if recompilation is required, by
25                         -- comparing version information
26
27         tyThingToIfaceDecl -- Converting things to their Iface equivalents
28  ) where
29 \end{code}
30
31         -----------------------------------------------
32                 MkIface.lhs deals with versioning
33         -----------------------------------------------
34
35 Here's the version-related info in an interface file
36
37   module Foo 8          -- module-version 
38              3          -- export-list-version
39              2          -- rule-version
40     Usages:     -- Version info for what this compilation of Foo imported
41         Baz 3           -- Module version
42             [4]         -- The export-list version if Foo depended on it
43             (g,2)       -- Function and its version
44             (T,1)       -- Type and its version
45
46     <version> f :: Int -> Int {- Unfolding: \x -> Wib.t[2] x -}
47                 -- The [2] says that f's unfolding 
48                 -- mentions verison 2 of Wib.t
49         
50         -----------------------------------------------
51                         Basic idea
52         -----------------------------------------------
53
54 Basic idea: 
55   * In the mi_usages information in an interface, we record the 
56     version number of each free variable of the module
57
58   * In mkIface, we compute the version number of each exported thing A.f
59     by comparing its A.f's info with its new info, and bumping its 
60     version number if it differs.  If A.f mentions B.g, and B.g's version
61     number has changed, then we count A.f as having changed too.
62
63   * In checkOldIface we compare the mi_usages for the module with
64     the actual version info for all each thing recorded in mi_usages
65
66
67 Fixities
68 ~~~~~~~~
69 We count A.f as changing if its fixity changes
70
71 Rules
72 ~~~~~
73 If a rule changes, we want to recompile any module that might be
74 affected by that rule.  For non-orphan rules, this is relatively easy.
75 If module M defines f, and a rule for f, just arrange that the version
76 number for M.f changes if any of the rules for M.f change.  Any module
77 that does not depend on M.f can't be affected by the rule-change
78 either.
79
80 Orphan rules (ones whose 'head function' is not defined in M) are
81 harder.  Here's what we do.
82
83   * We have a per-module orphan-rule version number which changes if 
84     any orphan rule changes. (It's unaffected by non-orphan rules.)
85
86   * We record usage info for any orphan module 'below' this one,
87     giving the orphan-rule version number.  We recompile if this 
88     changes. 
89
90 The net effect is that if an orphan rule changes, we recompile every
91 module above it.  That's very conservative, but it's devilishly hard
92 to know what it might affect, so we just have to be conservative.
93
94 Instance decls
95 ~~~~~~~~~~~~~~
96 In an iface file we have
97      module A where
98         instance Eq a => Eq [a]  =  dfun29
99         dfun29 :: ... 
100
101 We have a version number for dfun29, covering its unfolding
102 etc. Suppose we are compiling a module M that imports A only
103 indirectly.  If typechecking M uses this instance decl, we record the
104 dependency on A.dfun29 as if it were a free variable of the module
105 (via the tcg_inst_usages accumulator).  That means that A will appear
106 in M's usage list.  If the shape of the instance declaration changes,
107 then so will dfun29's version, triggering a recompilation.
108
109 Adding an instance declaration, or changing an instance decl that is
110 not currently used, is more tricky.  (This really only makes a
111 difference when we have overlapping instance decls, because then the
112 new instance decl might kick in to override the old one.)  We handle
113 this in a very similar way that we handle rules above.
114
115   * For non-orphan instance decls, identify one locally-defined tycon/class
116     mentioned in the decl.  Treat the instance decl as part of the defn of that
117     tycon/class, so that if the shape of the instance decl changes, so does the
118     tycon/class; that in turn will force recompilation of anything that uses
119     that tycon/class.
120
121   * For orphan instance decls, act the same way as for orphan rules.
122     Indeed, we use the same global orphan-rule version number.
123
124 mkUsageInfo
125 ~~~~~~~~~~~
126 mkUsageInfo figures out what the ``usage information'' for this
127 moudule is; that is, what it must record in its interface file as the
128 things it uses.  
129
130 We produce a line for every module B below the module, A, currently being
131 compiled:
132         import B <n> ;
133 to record the fact that A does import B indirectly.  This is used to decide
134 to look to look for B.hi rather than B.hi-boot when compiling a module that
135 imports A.  This line says that A imports B, but uses nothing in it.
136 So we'll get an early bale-out when compiling A if B's version changes.
137
138 The usage information records:
139
140 \begin{itemize}
141 \item   (a) anything reachable from its body code
142 \item   (b) any module exported with a @module Foo@
143 \item   (c) anything reachable from an exported item
144 \end{itemize}
145
146 Why (b)?  Because if @Foo@ changes then this module's export list
147 will change, so we must recompile this module at least as far as
148 making a new interface file --- but in practice that means complete
149 recompilation.
150
151 Why (c)?  Consider this:
152 \begin{verbatim}
153         module A( f, g ) where  |       module B( f ) where
154           import B( f )         |         f = h 3
155           g = ...               |         h = ...
156 \end{verbatim}
157
158 Here, @B.f@ isn't used in A.  Should we nevertheless record @B.f@ in
159 @A@'s usages?  Our idea is that we aren't going to touch A.hi if it is
160 *identical* to what it was before.  If anything about @B.f@ changes
161 than anyone who imports @A@ should be recompiled in case they use
162 @B.f@ (they'll get an early exit if they don't).  So, if anything
163 about @B.f@ changes we'd better make sure that something in A.hi
164 changes, and the convenient way to do that is to record the version
165 number @B.f@ in A.hi in the usage list.  If B.f changes that'll force a
166 complete recompiation of A, which is overkill but it's the only way to 
167 write a new, slightly different, A.hi.
168
169 But the example is tricker.  Even if @B.f@ doesn't change at all,
170 @B.h@ may do so, and this change may not be reflected in @f@'s version
171 number.  But with -O, a module that imports A must be recompiled if
172 @B.h@ changes!  So A must record a dependency on @B.h@.  So we treat
173 the occurrence of @B.f@ in the export list *just as if* it were in the
174 code of A, and thereby haul in all the stuff reachable from it.
175
176         *** Conclusion: if A mentions B.f in its export list,
177             behave just as if A mentioned B.f in its source code,
178             and slurp in B.f and all its transitive closure ***
179
180 [NB: If B was compiled with -O, but A isn't, we should really *still*
181 haul in all the unfoldings for B, in case the module that imports A *is*
182 compiled with -O.  I think this is the case.]
183
184
185 \begin{code}
186 #include "HsVersions.h"
187
188 import IfaceSyn
189 import IfaceType
190 import LoadIface
191 import Id
192 import IdInfo
193 import NewDemand
194 import CoreSyn
195 import CoreFVs
196 import Class
197 import TyCon
198 import DataCon
199 import Type
200 import TcType
201 import InstEnv
202 import FamInstEnv
203 import TcRnMonad
204 import HscTypes
205 import Finder
206 import DynFlags
207 import VarEnv
208 import Var
209 import Name
210 import NameEnv
211 import NameSet
212 import OccName
213 import Module
214 import BinIface
215 import Unique
216 import ErrUtils
217 import Digraph
218 import SrcLoc
219 import PackageConfig    hiding ( Version )
220 import Outputable
221 import BasicTypes       hiding ( SuccessFlag(..) )
222 import UniqFM
223 import Util             hiding ( eqListBy )
224 import FiniteMap
225 import FastString
226 import Maybes
227 import ListSetOps
228
229 import Control.Monad
230 import Data.List
231 import Data.IORef
232 \end{code}
233
234
235
236 %************************************************************************
237 %*                                                                      *
238 \subsection{Completing an interface}
239 %*                                                                      *
240 %************************************************************************
241
242 \begin{code}
243 mkIface :: HscEnv
244         -> Maybe ModIface       -- The old interface, if we have it
245         -> ModDetails           -- The trimmed, tidied interface
246         -> ModGuts              -- Usages, deprecations, etc
247         -> IO (ModIface,        -- The new one, complete with decls and versions
248                Bool)            -- True <=> there was an old Iface, and the new one
249                                 --          is identical, so no need to write it
250
251 mkIface hsc_env maybe_old_iface mod_details
252          ModGuts{     mg_module    = this_mod,
253                       mg_boot      = is_boot,
254                       mg_used_names = used_names,
255                       mg_deps      = deps,
256                       mg_dir_imps  = dir_imp_mods,
257                       mg_rdr_env   = rdr_env,
258                       mg_fix_env   = fix_env,
259                       mg_deprecs   = deprecs,
260                       mg_hpc_info  = hpc_info }
261         = mkIface_ hsc_env maybe_old_iface
262                    this_mod is_boot used_names deps rdr_env 
263                    fix_env deprecs hpc_info dir_imp_mods mod_details
264         
265 -- | make an interface from the results of typechecking only.  Useful
266 -- for non-optimising compilation, or where we aren't generating any
267 -- object code at all ('HscNothing').
268 mkIfaceTc :: HscEnv
269           -> Maybe ModIface     -- The old interface, if we have it
270           -> ModDetails         -- gotten from mkBootModDetails, probably
271           -> TcGblEnv           -- Usages, deprecations, etc
272           -> IO (ModIface,
273                  Bool)
274 mkIfaceTc hsc_env maybe_old_iface mod_details
275   tc_result@TcGblEnv{ tcg_mod = this_mod,
276                       tcg_src = hsc_src,
277                       tcg_imports = imports,
278                       tcg_rdr_env = rdr_env,
279                       tcg_fix_env = fix_env,
280                       tcg_deprecs = deprecs,
281                       tcg_hpc = other_hpc_info
282                     }
283   = do
284           used_names <- mkUsedNames tc_result
285           deps <- mkDependencies tc_result
286           let hpc_info = emptyHpcInfo other_hpc_info
287           mkIface_ hsc_env maybe_old_iface
288                    this_mod (isHsBoot hsc_src) used_names deps rdr_env 
289                    fix_env deprecs hpc_info (imp_mods imports) mod_details
290         
291
292 mkUsedNames :: TcGblEnv -> IO NameSet
293 mkUsedNames 
294           TcGblEnv{ tcg_inst_uses = dfun_uses_var,
295                     tcg_dus = dus
296                   }
297  = do
298         dfun_uses <- readIORef dfun_uses_var            -- What dfuns are used
299         return (allUses dus `unionNameSets` dfun_uses)
300         
301 mkDependencies :: TcGblEnv -> IO Dependencies
302 mkDependencies
303           TcGblEnv{ tcg_mod = mod,
304                     tcg_imports = imports,
305                     tcg_th_used = th_var
306                   }
307  = do 
308       th_used   <- readIORef th_var                        -- Whether TH is used
309       let
310         dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
311                 -- M.hi-boot can be in the imp_dep_mods, but we must remove
312                 -- it before recording the modules on which this one depends!
313                 -- (We want to retain M.hi-boot in imp_dep_mods so that 
314                 --  loadHiBootInterface can see if M's direct imports depend 
315                 --  on M.hi-boot, and hence that we should do the hi-boot consistency 
316                 --  check.)
317
318         dir_imp_mods = imp_mods imports
319
320                 -- Modules don't compare lexicographically usually, 
321                 -- but we want them to do so here.
322         le_mod :: Module -> Module -> Bool         
323         le_mod m1 m2 = moduleNameFS (moduleName m1) 
324                            <= moduleNameFS (moduleName m2)
325
326         le_dep_mod :: (ModuleName, IsBootInterface)
327                     -> (ModuleName, IsBootInterface) -> Bool         
328         le_dep_mod (m1,_) (m2,_) = moduleNameFS m1 <= moduleNameFS m2
329
330         
331         pkgs | th_used   = insertList thPackageId (imp_dep_pkgs imports)
332              | otherwise = imp_dep_pkgs imports
333
334       return Deps { dep_mods   = sortLe le_dep_mod dep_mods,
335                     dep_pkgs   = sortLe (<=)   pkgs,        
336                     dep_orphs  = sortLe le_mod (imp_orphs  imports),
337                     dep_finsts = sortLe le_mod (imp_finsts imports) }
338                 -- sort to get into canonical order
339
340
341 mkIface_ hsc_env maybe_old_iface 
342          this_mod is_boot used_names deps rdr_env fix_env src_deprecs hpc_info
343          dir_imp_mods
344          ModDetails{  md_insts     = insts, 
345                       md_fam_insts = fam_insts,
346                       md_rules     = rules,
347                       md_vect_info = vect_info,
348                       md_types     = type_env,
349                       md_exports   = exports }
350 -- NB:  notice that mkIface does not look at the bindings
351 --      only at the TypeEnv.  The previous Tidy phase has
352 --      put exactly the info into the TypeEnv that we want
353 --      to expose in the interface
354
355   = do  {eps <- hscEPS hsc_env
356
357         ; usages <- mkUsageInfo hsc_env dir_imp_mods (dep_mods deps) used_names
358
359         ; let   { entities = typeEnvElts type_env ;
360                   decls  = [ tyThingToIfaceDecl entity
361                            | entity <- entities,
362                              let name = getName entity,
363                              not (isImplicitTyThing entity),
364                                 -- No implicit Ids and class tycons in the interface file
365                              not (isWiredInName name),
366                                 -- Nor wired-in things; the compiler knows about them anyhow
367                              nameIsLocalOrFrom this_mod name  ]
368                                 -- Sigh: see Note [Root-main Id] in TcRnDriver
369
370                 ; fixities    = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
371                 ; deprecs     = src_deprecs
372                 ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
373                 ; iface_insts = map instanceToIfaceInst insts
374                 ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
375                 ; iface_vect_info = flattenVectInfo vect_info
376
377                 ; intermediate_iface = ModIface { 
378                         mi_module   = this_mod,
379                         mi_boot     = is_boot,
380                         mi_deps     = deps,
381                         mi_usages   = usages,
382                         mi_exports  = mkIfaceExports exports,
383         
384                         -- Sort these lexicographically, so that
385                         -- the result is stable across compilations
386                         mi_insts    = sortLe le_inst iface_insts,
387                         mi_fam_insts= sortLe le_fam_inst iface_fam_insts,
388                         mi_rules    = sortLe le_rule iface_rules,
389
390                         mi_vect_info = iface_vect_info,
391
392                         mi_fixities = fixities,
393                         mi_deprecs  = deprecs,
394                         mi_globals  = Just rdr_env,
395
396                         -- Left out deliberately: filled in by addVersionInfo
397                         mi_mod_vers  = initialVersion,
398                         mi_exp_vers  = initialVersion,
399                         mi_rule_vers = initialVersion,
400                         mi_orphan    = False,   -- Always set by addVersionInfo, but
401                                                 -- it's a strict field, so we can't omit it.
402                         mi_finsts    = False,   -- Ditto
403                         mi_decls     = deliberatelyOmitted "decls",
404                         mi_ver_fn    = deliberatelyOmitted "ver_fn",
405                         mi_hpc       = isHpcUsed hpc_info,
406
407                         -- And build the cached values
408                         mi_dep_fn = mkIfaceDepCache deprecs,
409                         mi_fix_fn = mkIfaceFixCache fixities }
410
411                 -- Add version information
412               ; ext_ver_fn = mkParentVerFun hsc_env eps
413                 ; (new_iface, no_change_at_all, pp_diffs, pp_orphs) 
414                         = {-# SCC "versioninfo" #-}
415                          addVersionInfo ext_ver_fn maybe_old_iface
416                                          intermediate_iface decls
417                 }
418
419                 -- Debug printing
420         ; when (isJust pp_orphs && dopt Opt_WarnOrphans dflags) 
421                (printDump (expectJust "mkIface" pp_orphs))
422         ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
423         ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE" 
424                         (pprModIface new_iface)
425
426                 -- bug #1617: on reload we weren't updating the PrintUnqualified
427                 -- correctly.  This stems from the fact that the interface had
428                 -- not changed, so addVersionInfo returns the old ModIface
429                 -- with the old GlobalRdrEnv (mi_globals).
430         ; let final_iface = new_iface{ mi_globals = Just rdr_env }
431
432         ; return (final_iface, no_change_at_all) }
433   where
434      r1 `le_rule`     r2 = ifRuleName      r1    <=    ifRuleName      r2
435      i1 `le_inst`     i2 = ifDFun          i1 `le_occ` ifDFun          i2  
436      i1 `le_fam_inst` i2 = ifFamInstTcName i1 `le_occ` ifFamInstTcName i2
437
438      le_occ :: Name -> Name -> Bool
439         -- Compare lexicographically by OccName, *not* by unique, because 
440         -- the latter is not stable across compilations
441      le_occ n1 n2 = nameOccName n1 <= nameOccName n2
442
443      dflags = hsc_dflags hsc_env
444      deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
445      ifFamInstTcName = ifaceTyConName . ifFamInstTyCon
446
447      flattenVectInfo (VectInfo { vectInfoVar   = vVar
448                                , vectInfoTyCon = vTyCon
449                                }) = 
450        IfaceVectInfo { 
451          ifaceVectInfoVar        = [ Var.varName v 
452                                    | (v, _) <- varEnvElts vVar],
453          ifaceVectInfoTyCon      = [ tyConName t 
454                                    | (t, t_v) <- nameEnvElts vTyCon
455                                    , t /= t_v],
456          ifaceVectInfoTyConReuse = [ tyConName t
457                                    | (t, t_v) <- nameEnvElts vTyCon
458                                    , t == t_v]
459        } 
460
461 -----------------------------
462 writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
463 writeIfaceFile dflags location new_iface
464     = do createDirectoryHierarchy (directoryOf hi_file_path)
465          writeBinIface dflags hi_file_path new_iface
466     where hi_file_path = ml_hi_file location
467
468
469 -- -----------------------------------------------------------------------------
470 -- Look up parents and versions of Names
471
472 -- This is like a global version of the mi_ver_fn field in each ModIface.
473 -- Given a Name, it finds the ModIface, and then uses mi_ver_fn to get
474 -- the parent and version info.
475
476 mkParentVerFun
477         :: HscEnv                       -- needed to look up versions
478         -> ExternalPackageState         -- ditto
479         -> (Name -> (OccName,Version))
480 mkParentVerFun hsc_env eps
481   = \name -> 
482       let 
483         mod = nameModule name
484         occ = nameOccName name
485         iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse` 
486                    pprPanic "lookupVers2" (ppr mod <+> ppr occ)
487       in  
488         mi_ver_fn iface occ `orElse` 
489                  pprPanic "lookupVers1" (ppr mod <+> ppr occ)
490   where
491       hpt = hsc_HPT hsc_env
492       pit = eps_PIT eps
493
494 -----------------------------------------------------------------------------
495 -- Compute version numbers for local decls
496
497 addVersionInfo
498         :: (Name -> (OccName,Version))  -- lookup parents and versions of names
499         -> Maybe ModIface  -- The old interface, read from M.hi
500         -> ModIface        -- The new interface (lacking decls)
501         -> [IfaceDecl]     -- The new decls
502         -> (ModIface,   -- Updated interface
503             Bool,          -- True <=> no changes at all; no need to write Iface
504             SDoc,          -- Differences
505             Maybe SDoc) -- Warnings about orphans
506
507 addVersionInfo ver_fn Nothing new_iface new_decls
508 -- No old interface, so definitely write a new one!
509   = (new_iface { mi_orphan = not (null orph_insts && null orph_rules)
510                , mi_finsts = not . null $ mi_fam_insts new_iface
511                , mi_decls  = [(initialVersion, decl) | decl <- new_decls]
512                , mi_ver_fn = mkIfaceVerCache (zip (repeat initialVersion) 
513                                                   new_decls)
514                },
515      False, 
516      ptext SLIT("No old interface file"),
517      pprOrphans orph_insts orph_rules)
518   where
519     orph_insts = filter (isNothing . ifInstOrph) (mi_insts new_iface)
520     orph_rules = filter (isNothing . ifRuleOrph) (mi_rules new_iface)
521
522 addVersionInfo ver_fn (Just old_iface@(ModIface { 
523                                            mi_mod_vers  = old_mod_vers, 
524                                            mi_exp_vers  = old_exp_vers, 
525                                            mi_rule_vers = old_rule_vers, 
526                                            mi_decls     = old_decls,
527                                            mi_ver_fn    = old_decl_vers,
528                                            mi_fix_fn    = old_fixities }))
529                new_iface@(ModIface { mi_fix_fn = new_fixities })
530                new_decls
531  | no_change_at_all
532  = (old_iface,  True,   ptext SLIT("Interface file unchanged"), pp_orphs)
533  | otherwise
534  = (final_iface, False, vcat [ptext SLIT("Interface file has changed"),
535                               nest 2 pp_diffs], pp_orphs)
536  where
537     final_iface = new_iface { 
538                 mi_mod_vers  = bump_unless no_output_change old_mod_vers,
539                 mi_exp_vers  = bump_unless no_export_change old_exp_vers,
540                 mi_rule_vers = bump_unless no_rule_change   old_rule_vers,
541                 mi_orphan    = not (null new_orph_rules && null new_orph_insts),
542                 mi_finsts    = not . null $ mi_fam_insts new_iface,
543                 mi_decls     = decls_w_vers,
544                 mi_ver_fn    = mkIfaceVerCache decls_w_vers }
545
546     decls_w_vers = [(add_vers decl, decl) | decl <- new_decls]
547
548     -------------------
549     (old_non_orph_insts, old_orph_insts) = 
550         mkOrphMap ifInstOrph (mi_insts old_iface)
551     (new_non_orph_insts, new_orph_insts) = 
552         mkOrphMap ifInstOrph (mi_insts new_iface)
553     old_fam_insts = mi_fam_insts old_iface
554     new_fam_insts = mi_fam_insts new_iface
555     same_insts occ = eqMaybeBy  (eqListBy eqIfInst) 
556                                 (lookupOccEnv old_non_orph_insts occ)
557                                 (lookupOccEnv new_non_orph_insts occ)
558   
559     (old_non_orph_rules, old_orph_rules) = 
560         mkOrphMap ifRuleOrph (mi_rules old_iface)
561     (new_non_orph_rules, new_orph_rules) = 
562         mkOrphMap ifRuleOrph (mi_rules new_iface)
563     same_rules occ = eqMaybeBy  (eqListBy eqIfRule)
564                                 (lookupOccEnv old_non_orph_rules occ)
565                                 (lookupOccEnv new_non_orph_rules occ)
566     -------------------
567     -- Computing what changed
568     no_output_change = no_decl_change   && no_rule_change && 
569                        no_export_change && no_deprec_change
570     no_export_change = mi_exports new_iface == mi_exports old_iface
571                                 -- Kept sorted
572     no_decl_change   = isEmptyOccSet changed_occs
573     no_rule_change   = not (changedWrtNames changed_occs (eqListBy eqIfRule old_orph_rules new_orph_rules)
574                          || changedWrtNames changed_occs (eqListBy eqIfInst old_orph_insts new_orph_insts)
575                          || changedWrtNames changed_occs (eqListBy eqIfFamInst old_fam_insts new_fam_insts))
576     no_deprec_change = mi_deprecs new_iface == mi_deprecs old_iface
577
578         -- If the usages havn't changed either, we don't need to write the interface file
579     no_other_changes = mi_usages new_iface == mi_usages old_iface && 
580                        mi_deps new_iface == mi_deps old_iface &&
581                        mi_hpc new_iface == mi_hpc old_iface
582     no_change_at_all = no_output_change && no_other_changes
583  
584     pp_diffs = vcat [pp_change no_export_change "Export list" 
585                         (ppr old_exp_vers <+> arrow <+> ppr (mi_exp_vers final_iface)),
586                      pp_change no_rule_change "Rules"
587                         (ppr old_rule_vers <+> arrow <+> ppr (mi_rule_vers final_iface)),
588                      pp_change no_deprec_change "Deprecations" empty,
589                      pp_change no_other_changes  "Usages" empty,
590                      pp_decl_diffs]
591     pp_change True  what info = empty
592     pp_change False what info = text what <+> ptext SLIT("changed") <+> info
593
594     -------------------
595     old_decl_env = mkOccEnv [(ifName decl, decl) | (_,decl) <- old_decls]
596     same_fixity n = bool (old_fixities n == new_fixities n)
597
598     -------------------
599     -- Adding version info
600     new_version = bumpVersion old_mod_vers
601                         -- Start from the old module version, not from
602                         -- zero so that if you remove f, and then add
603                         -- it again, you don't thereby reduce f's
604                         -- version number
605
606     add_vers decl | occ `elemOccSet` changed_occs = new_version
607                   | otherwise = snd (expectJust "add_vers" (old_decl_vers occ))
608                                 -- If it's unchanged, there jolly well 
609                   where         -- should be an old version number
610                     occ = ifName decl
611
612     -------------------
613     -- Deciding which declarations have changed
614             
615     -- For each local decl, the IfaceEq gives the list of things that
616     -- must be unchanged for the declaration as a whole to be unchanged.
617     eq_info :: [(OccName, IfaceEq)]
618     eq_info = map check_eq new_decls
619     check_eq new_decl
620          | Just old_decl <- lookupOccEnv old_decl_env occ 
621          = (occ, new_decl `eqIfDecl` old_decl &&& eq_indirects new_decl)
622          | otherwise {- No corresponding old decl -}      
623          = (occ, NotEqual)      
624         where
625           occ = ifName new_decl
626
627     eq_indirects :: IfaceDecl -> IfaceEq
628                 -- When seeing if two decls are the same, remember to
629                 -- check whether any relevant fixity or rules have changed
630     eq_indirects (IfaceId {ifName = occ}) = eq_ind_occ occ
631     eq_indirects (IfaceClass {ifName = cls_occ, ifSigs = sigs})
632         = same_insts cls_occ &&& 
633           eq_ind_occs [op | IfaceClassOp op _ _ <- sigs] 
634     eq_indirects (IfaceData {ifName = tc_occ, ifCons = cons})
635         = same_insts tc_occ &&& same_fixity tc_occ &&&  -- The TyCon can have a fixity too
636           eq_ind_occs (map ifConOcc (visibleIfConDecls cons))
637     eq_indirects other = Equal  -- Synonyms and foreign declarations
638
639     eq_ind_occ :: OccName -> IfaceEq    -- For class ops and Ids; check fixity and rules
640     eq_ind_occ occ = same_fixity occ &&& same_rules occ
641     eq_ind_occs = foldr ((&&&) . eq_ind_occ) Equal 
642      
643     -- The Occs of declarations that changed.
644     changed_occs :: OccSet
645     changed_occs = computeChangedOccs ver_fn (mi_module new_iface)
646                          (mi_usages old_iface) eq_info
647
648     -------------------
649     -- Diffs
650     pp_decl_diffs :: SDoc       -- Nothing => no changes
651     pp_decl_diffs 
652         | isEmptyOccSet changed_occs = empty
653         | otherwise 
654         = vcat [ptext SLIT("Changed occs:") <+> ppr (occSetElts changed_occs),
655                 ptext SLIT("Version change for these decls:"),
656                 nest 2 (vcat (map show_change new_decls))]
657
658     eq_env = mkOccEnv eq_info
659     show_change new_decl
660         | not (occ `elemOccSet` changed_occs) = empty
661         | otherwise
662         = vcat [ppr occ <+> ppr (old_decl_vers occ) <+> arrow <+> ppr new_version, 
663                 nest 2 why]
664         where
665           occ = ifName new_decl
666           why = case lookupOccEnv eq_env occ of
667                     Just (EqBut names) -> sep [ppr occ <> colon, ptext SLIT("Free vars (only) changed:") <> ppr names,
668                                               nest 2 (braces (fsep (map ppr (occSetElts 
669                                                 (occs `intersectOccSet` changed_occs)))))]
670                            where occs = mkOccSet (map nameOccName (nameSetToList names))
671                     Just NotEqual  
672                         | Just old_decl <- lookupOccEnv old_decl_env occ 
673                         -> vcat [ptext SLIT("Old:") <+> ppr old_decl,
674                          ptext SLIT("New:") <+> ppr new_decl]
675                         | otherwise 
676                         -> ppr occ <+> ptext SLIT("only in new interface")
677                     other -> pprPanic "MkIface.show_change" (ppr occ)
678         
679     pp_orphs = pprOrphans new_orph_insts new_orph_rules
680
681
682 pprOrphans insts rules
683   | null insts && null rules = Nothing
684   | otherwise
685   = Just $ vcat [
686         if null insts then empty else
687              hang (ptext SLIT("Warning: orphan instances:"))
688                 2 (vcat (map ppr insts)),
689         if null rules then empty else
690              hang (ptext SLIT("Warning: orphan rules:"))
691                 2 (vcat (map ppr rules))
692     ]
693
694 computeChangedOccs
695         :: (Name -> (OccName,Version))     -- get parents and versions
696         -> Module                       -- This module
697         -> [Usage]                      -- Usages from old iface
698         -> [(OccName, IfaceEq)]         -- decl names, equality conditions
699         -> OccSet                       -- set of things that have changed
700 computeChangedOccs ver_fn this_module old_usages eq_info
701   = foldl add_changes emptyOccSet (stronglyConnComp edges)
702   where
703
704     -- return True if an external name has changed
705     name_changed :: Name -> Bool
706     name_changed nm
707         | Just ents <- lookupUFM usg_modmap (moduleName mod) 
708         = case lookupUFM ents parent_occ of
709                 Nothing -> pprPanic "computeChangedOccs" (ppr nm)
710                 Just v  -> v < new_version
711         | otherwise = False -- must be in another package
712       where
713          mod = nameModule nm
714          (parent_occ, new_version) = ver_fn nm
715
716     -- Turn the usages from the old ModIface into a mapping
717     usg_modmap = listToUFM [ (usg_mod usg, listToUFM (usg_entities usg))
718                            | usg <- old_usages ]
719
720     get_local_eq_info :: GenIfaceEq NameSet -> GenIfaceEq OccSet
721     get_local_eq_info Equal = Equal
722     get_local_eq_info NotEqual = NotEqual
723     get_local_eq_info (EqBut ns) = foldNameSet f Equal ns
724         where f name eq | nameModule name == this_module =         
725                           EqBut (unitOccSet (nameOccName name)) `and_occifeq` eq
726                         | name_changed name = NotEqual
727                         | otherwise = eq
728
729     local_eq_infos = mapSnd get_local_eq_info eq_info
730
731     edges :: [((OccName, OccIfaceEq), Unique, [Unique])]
732     edges = [ (node, getUnique occ, map getUnique occs)
733             | node@(occ, iface_eq) <- local_eq_infos
734             , let occs = case iface_eq of
735                            EqBut occ_set -> occSetElts occ_set
736                            other -> [] ]
737
738     -- Changes in declarations
739     add_changes :: OccSet -> SCC (OccName, OccIfaceEq) -> OccSet
740     add_changes so_far (AcyclicSCC (occ, iface_eq)) 
741         | changedWrt so_far iface_eq -- This one has changed
742         = extendOccSet so_far occ
743     add_changes so_far (CyclicSCC pairs)
744         | changedWrt so_far (foldr1 and_occifeq iface_eqs)
745                 -- One of this group has changed
746         = extendOccSetList so_far occs
747         where (occs, iface_eqs) = unzip pairs
748     add_changes so_far other = so_far
749
750 type OccIfaceEq = GenIfaceEq OccSet
751
752 changedWrt :: OccSet -> OccIfaceEq -> Bool
753 changedWrt so_far Equal        = False
754 changedWrt so_far NotEqual     = True
755 changedWrt so_far (EqBut kids) = so_far `intersectsOccSet` kids
756
757 changedWrtNames :: OccSet -> IfaceEq -> Bool
758 changedWrtNames so_far Equal        = False
759 changedWrtNames so_far NotEqual     = True
760 changedWrtNames so_far (EqBut kids) = 
761   so_far `intersectsOccSet` mkOccSet (map nameOccName (nameSetToList kids))
762
763 and_occifeq :: OccIfaceEq -> OccIfaceEq -> OccIfaceEq
764 Equal       `and_occifeq` x         = x
765 NotEqual    `and_occifeq` x         = NotEqual
766 EqBut nms   `and_occifeq` Equal       = EqBut nms
767 EqBut nms   `and_occifeq` NotEqual    = NotEqual
768 EqBut nms1  `and_occifeq` EqBut nms2  = EqBut (nms1 `unionOccSets` nms2)
769
770 ----------------------
771 -- mkOrphMap partitions instance decls or rules into
772 --      (a) an OccEnv for ones that are not orphans, 
773 --          mapping the local OccName to a list of its decls
774 --      (b) a list of orphan decls
775 mkOrphMap :: (decl -> Maybe OccName)    -- (Just occ) for a non-orphan decl, keyed by occ
776                                         -- Nothing for an orphan decl
777           -> [decl]                     -- Sorted into canonical order
778           -> (OccEnv [decl],            -- Non-orphan decls associated with their key;
779                                         --      each sublist in canonical order
780               [decl])                   -- Orphan decls; in canonical order
781 mkOrphMap get_key decls
782   = foldl go (emptyOccEnv, []) decls
783   where
784     go (non_orphs, orphs) d
785         | Just occ <- get_key d
786         = (extendOccEnv_C (\ ds _ -> d:ds) non_orphs occ [d], orphs)
787         | otherwise = (non_orphs, d:orphs)
788
789 ----------------------
790 bump_unless :: Bool -> Version -> Version
791 bump_unless True  v = v -- True <=> no change
792 bump_unless False v = bumpVersion v
793 \end{code}
794
795
796 %*********************************************************
797 %*                                                      *
798 \subsection{Keeping track of what we've slurped, and version numbers}
799 %*                                                      *
800 %*********************************************************
801
802
803 \begin{code}
804 mkUsageInfo :: HscEnv 
805             -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
806             -> [(ModuleName, IsBootInterface)]
807             -> NameSet -> IO [Usage]
808 mkUsageInfo hsc_env dir_imp_mods dep_mods used_names
809   = do  { eps <- hscEPS hsc_env
810         ; let usages = mk_usage_info (eps_PIT eps) hsc_env 
811                                      dir_imp_mods dep_mods used_names
812         ; usages `seqList`  return usages }
813          -- seq the list of Usages returned: occasionally these
814          -- don't get evaluated for a while and we can end up hanging on to
815          -- the entire collection of Ifaces.
816
817 mk_usage_info :: PackageIfaceTable
818               -> HscEnv
819               -> ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)])
820               -> [(ModuleName, IsBootInterface)]
821               -> NameSet
822               -> [Usage]
823 mk_usage_info pit hsc_env dir_imp_mods dep_mods used_names
824   = mapCatMaybes mkUsage dep_mods
825         -- ToDo: do we need to sort into canonical order?
826   where
827     hpt = hsc_HPT hsc_env
828     dflags = hsc_dflags hsc_env
829
830     -- ent_map groups together all the things imported and used
831     -- from a particular module in this package
832     ent_map :: ModuleEnv [OccName]
833     ent_map  = foldNameSet add_mv emptyModuleEnv used_names
834     add_mv name mv_map
835         | isWiredInName name = mv_map  -- ignore wired-in names
836         | otherwise
837         = case nameModule_maybe name of
838              Nothing  -> mv_map         -- ignore internal names
839              Just mod -> extendModuleEnv_C add_item mv_map mod [occ]
840                    where
841                      occ = nameOccName name
842                      add_item occs _ = occ:occs
843     
844     depend_on_exports mod = case lookupModuleEnv dir_imp_mods mod of
845                                 Just (_, xs) -> any (\(_, no_imp, _) -> not no_imp) xs
846                                 Nothing          -> True
847     
848     -- We want to create a Usage for a home module if 
849     --  a) we used something from; has something in used_names
850     --  b) we imported all of it, even if we used nothing from it
851     --          (need to recompile if its export list changes: export_vers)
852     --  c) is a home-package orphan or family-instance module (need to
853     --          recompile if its instance decls change: rules_vers)
854     mkUsage :: (ModuleName, IsBootInterface) -> Maybe Usage
855     mkUsage (mod_name, _)
856       |  isNothing maybe_iface          -- We can't depend on it if we didn't
857       || (null used_occs                -- load its interface.
858           && isNothing export_vers
859           && not orphan_mod
860           && not finsts_mod)
861       = Nothing                 -- Record no usage info
862     
863       | otherwise       
864       = Just (Usage { usg_name     = mod_name,
865                       usg_mod      = mod_vers,
866                       usg_exports  = export_vers,
867                       usg_entities = fmToList ent_vers,
868                       usg_rules    = rules_vers })
869       where
870         maybe_iface  = lookupIfaceByModule dflags hpt pit mod
871                 -- In one-shot mode, the interfaces for home-package 
872                 -- modules accumulate in the PIT not HPT.  Sigh.
873
874         mod = mkModule (thisPackage dflags) mod_name
875
876         Just iface   = maybe_iface
877         orphan_mod   = mi_orphan    iface
878         finsts_mod   = mi_finsts    iface
879         version_env  = mi_ver_fn    iface
880         mod_vers     = mi_mod_vers  iface
881         rules_vers   = mi_rule_vers iface
882         export_vers | depend_on_exports mod = Just (mi_exp_vers iface)
883                     | otherwise             = Nothing
884     
885         used_occs = lookupModuleEnv ent_map mod `orElse` []
886
887         -- Making a FiniteMap here ensures that (a) we remove duplicates
888         -- when we have usages on several subordinates of a single parent,
889         -- and (b) that the usages emerge in a canonical order, which
890         -- is why we use FiniteMap rather than OccEnv: FiniteMap works
891         -- using Ord on the OccNames, which is a lexicographic ordering.
892         ent_vers :: FiniteMap OccName Version
893         ent_vers = listToFM (map lookup_occ used_occs)
894         
895         lookup_occ occ = 
896             case version_env occ of
897                 Nothing -> pprTrace "hmm, strange" (ppr mod <+> ppr occ) $
898                            (occ, initialVersion) -- does this ever happen?
899                 Just (parent, version) -> (parent, version)
900 \end{code}
901
902 \begin{code}
903 mkIfaceExports :: [AvailInfo]
904                -> [(Module, [GenAvailInfo OccName])]
905   -- Group by module and sort by occurrence
906   -- This keeps the list in canonical order
907 mkIfaceExports exports
908   = [ (mod, eltsFM avails)
909     | (mod, avails) <- fmToList groupFM
910     ]
911   where
912         -- Group by the module where the exported entities are defined
913         -- (which may not be the same for all Names in an Avail)
914         -- Deliberately use FiniteMap rather than UniqFM so we
915         -- get a canonical ordering
916     groupFM :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
917     groupFM = foldl add emptyModuleEnv exports
918
919     add_one :: ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
920             -> Module -> GenAvailInfo OccName
921             -> ModuleEnv (FiniteMap FastString (GenAvailInfo OccName))
922     add_one env mod avail 
923       =  extendModuleEnv_C plusFM env mod 
924                 (unitFM (occNameFS (availName avail)) avail)
925
926         -- NB: we should not get T(X) and T(Y) in the export list
927         --     else the plusFM will simply discard one!  They
928         --     should have been combined by now.
929     add env (Avail n)
930       = add_one env (nameModule n) (Avail (nameOccName n))
931
932     add env (AvailTC tc ns)
933       = foldl add_for_mod env mods
934       where
935         tc_occ = nameOccName tc
936         mods   = nub (map nameModule ns)
937                 -- Usually just one, but see Note [Original module]
938
939         add_for_mod env mod
940             = add_one env mod (AvailTC tc_occ (sort names_from_mod))
941               -- NB. sort the children, we need a canonical order
942             where
943               names_from_mod = [nameOccName n | n <- ns, nameModule n == mod]
944 \end{code}
945
946 Note [Orignal module]
947 ~~~~~~~~~~~~~~~~~~~~~
948 Consider this:
949         module X where { data family T }
950         module Y( T(..) ) where { import X; data instance T Int = MkT Int }
951 The exported Avail from Y will look like
952         X.T{X.T, Y.MkT}
953 That is, in Y, 
954   - only MkT is brought into scope by the data instance;
955   - but the parent (used for grouping and naming in T(..) exports) is X.T
956   - and in this case we export X.T too
957
958 In the result of MkIfaceExports, the names are grouped by defining module,
959 so we may need to split up a single Avail into multiple ones.
960
961
962 %************************************************************************
963 %*                                                                      *
964         Load the old interface file for this module (unless
965         we have it aleady), and check whether it is up to date
966         
967 %*                                                                      *
968 %************************************************************************
969
970 \begin{code}
971 checkOldIface :: HscEnv
972               -> ModSummary
973               -> Bool                   -- Source unchanged
974               -> Maybe ModIface         -- Old interface from compilation manager, if any
975               -> IO (RecompileRequired, Maybe ModIface)
976
977 checkOldIface hsc_env mod_summary source_unchanged maybe_iface
978   = do  { showPass (hsc_dflags hsc_env) 
979                    ("Checking old interface for " ++ 
980                         showSDoc (ppr (ms_mod mod_summary))) ;
981
982         ; initIfaceCheck hsc_env $
983           check_old_iface hsc_env mod_summary source_unchanged maybe_iface
984      }
985
986 check_old_iface hsc_env mod_summary source_unchanged maybe_iface
987  =  do  -- CHECK WHETHER THE SOURCE HAS CHANGED
988     { ifM (not source_unchanged)
989            (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
990
991      -- If the source has changed and we're in interactive mode, avoid reading
992      -- an interface; just return the one we might have been supplied with.
993     ; let dflags = hsc_dflags hsc_env
994     ; if not (isObjectTarget (hscTarget dflags)) && not source_unchanged then
995          return (outOfDate, maybe_iface)
996       else
997       case maybe_iface of {
998         Just old_iface -> do -- Use the one we already have
999           { traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
1000           ; recomp <- checkVersions hsc_env source_unchanged mod_summary old_iface
1001           ; return (recomp, Just old_iface) }
1002
1003       ; Nothing -> do
1004
1005         -- Try and read the old interface for the current module
1006         -- from the .hi file left from the last time we compiled it
1007     { let iface_path = msHiFilePath mod_summary
1008     ; read_result <- readIface (ms_mod mod_summary) iface_path False
1009     ; case read_result of {
1010          Failed err -> do       -- Old interface file not found, or garbled; give up
1011                 { traceIf (text "FYI: cannot read old interface file:"
1012                                  $$ nest 4 err)
1013                 ; return (outOfDate, Nothing) }
1014
1015       ;  Succeeded iface -> do
1016
1017         -- We have got the old iface; check its versions
1018     { traceIf (text "Read the interface file" <+> text iface_path)
1019     ; recomp <- checkVersions hsc_env source_unchanged mod_summary iface
1020     ; returnM (recomp, Just iface)
1021     }}}}}
1022
1023 \end{code}
1024
1025 @recompileRequired@ is called from the HscMain.   It checks whether
1026 a recompilation is required.  It needs access to the persistent state,
1027 finder, etc, because it may have to load lots of interface files to
1028 check their versions.
1029
1030 \begin{code}
1031 type RecompileRequired = Bool
1032 upToDate  = False       -- Recompile not required
1033 outOfDate = True        -- Recompile required
1034
1035 checkVersions :: HscEnv
1036               -> Bool           -- True <=> source unchanged
1037               -> ModSummary
1038               -> ModIface       -- Old interface
1039               -> IfG RecompileRequired
1040 checkVersions hsc_env source_unchanged mod_summary iface
1041   | not source_unchanged
1042   = returnM outOfDate
1043   | otherwise
1044   = do  { traceHiDiffs (text "Considering whether compilation is required for" <+> 
1045                         ppr (mi_module iface) <> colon)
1046
1047         ; recomp <- checkDependencies hsc_env mod_summary iface
1048         ; if recomp then return outOfDate else do {
1049
1050         -- Source code unchanged and no errors yet... carry on 
1051
1052         -- First put the dependent-module info, read from the old interface, into the envt, 
1053         -- so that when we look for interfaces we look for the right one (.hi or .hi-boot)
1054         -- 
1055         -- It's just temporary because either the usage check will succeed 
1056         -- (in which case we are done with this module) or it'll fail (in which
1057         -- case we'll compile the module from scratch anyhow).
1058         --      
1059         -- We do this regardless of compilation mode, although in --make mode
1060         -- all the dependent modules should be in the HPT already, so it's
1061         -- quite redundant
1062           updateEps_ $ \eps  -> eps { eps_is_boot = mod_deps }
1063
1064         ; let this_pkg = thisPackage (hsc_dflags hsc_env)
1065         ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
1066     }}
1067   where
1068         -- This is a bit of a hack really
1069     mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
1070     mod_deps = mkModDeps (dep_mods (mi_deps iface))
1071
1072
1073 -- If the direct imports of this module are resolved to targets that
1074 -- are not among the dependencies of the previous interface file,
1075 -- then we definitely need to recompile.  This catches cases like
1076 --   - an exposed package has been upgraded
1077 --   - we are compiling with different package flags
1078 --   - a home module that was shadowing a package module has been removed
1079 --   - a new home module has been added that shadows a package module
1080 -- See bug #1372.
1081 --
1082 -- Returns True if recompilation is required.
1083 checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
1084 checkDependencies hsc_env summary iface
1085  = orM (map dep_missing (ms_imps summary ++ ms_srcimps summary))
1086   where
1087    prev_dep_mods = dep_mods (mi_deps iface)
1088    prev_dep_pkgs = dep_pkgs (mi_deps iface)
1089
1090    this_pkg = thisPackage (hsc_dflags hsc_env)
1091
1092    orM = foldr f (return False)
1093     where f m rest = do b <- m; if b then return True else rest
1094
1095    dep_missing (L _ mod) = do
1096      find_res <- ioToIOEnv $ findImportedModule hsc_env mod Nothing
1097      case find_res of
1098         Found _ mod
1099           | pkg == this_pkg
1100            -> if moduleName mod `notElem` map fst prev_dep_mods
1101                  then do traceHiDiffs $
1102                            text "imported module " <> quotes (ppr mod) <>
1103                            text " not among previous dependencies"
1104                          return outOfDate
1105                  else
1106                          return upToDate
1107           | otherwise
1108            -> if pkg `notElem` prev_dep_pkgs
1109                  then do traceHiDiffs $
1110                            text "imported module " <> quotes (ppr mod) <>
1111                            text " is from package " <> quotes (ppr pkg) <>
1112                            text ", which is not among previous dependencies"
1113                          return outOfDate
1114                  else
1115                          return upToDate
1116            where pkg = modulePackageId mod
1117         _otherwise  -> return outOfDate
1118
1119 checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
1120 -- Given the usage information extracted from the old
1121 -- M.hi file for the module being compiled, figure out
1122 -- whether M needs to be recompiled.
1123
1124 checkModUsage this_pkg (Usage { usg_name = mod_name, usg_mod = old_mod_vers,
1125                                 usg_rules = old_rule_vers,
1126                                 usg_exports = maybe_old_export_vers, 
1127                                 usg_entities = old_decl_vers })
1128   =     -- Load the imported interface is possible
1129     let
1130         doc_str = sep [ptext SLIT("need version info for"), ppr mod_name]
1131     in
1132     traceHiDiffs (text "Checking usages for module" <+> ppr mod_name) `thenM_`
1133
1134     let
1135         mod = mkModule this_pkg mod_name
1136     in
1137     loadInterface doc_str mod ImportBySystem            `thenM` \ mb_iface ->
1138         -- Load the interface, but don't complain on failure;
1139         -- Instead, get an Either back which we can test
1140
1141     case mb_iface of {
1142         Failed exn ->  (out_of_date (sep [ptext SLIT("Can't find version number for module"), 
1143                                        ppr mod_name]));
1144                 -- Couldn't find or parse a module mentioned in the
1145                 -- old interface file.  Don't complain -- it might just be that
1146                 -- the current module doesn't need that import and it's been deleted
1147
1148         Succeeded iface -> 
1149     let
1150         new_mod_vers    = mi_mod_vers  iface
1151         new_decl_vers   = mi_ver_fn    iface
1152         new_export_vers = mi_exp_vers  iface
1153         new_rule_vers   = mi_rule_vers iface
1154     in
1155         -- CHECK MODULE
1156     checkModuleVersion old_mod_vers new_mod_vers        `thenM` \ recompile ->
1157     if not recompile then
1158         returnM upToDate
1159     else
1160                                  
1161         -- CHECK EXPORT LIST
1162     if checkExportList maybe_old_export_vers new_export_vers then
1163         out_of_date_vers (ptext SLIT("  Export list changed"))
1164                          (expectJust "checkModUsage" maybe_old_export_vers) 
1165                          new_export_vers
1166     else
1167
1168         -- CHECK RULES
1169     if old_rule_vers /= new_rule_vers then
1170         out_of_date_vers (ptext SLIT("  Rules changed")) 
1171                          old_rule_vers new_rule_vers
1172     else
1173
1174         -- CHECK ITEMS ONE BY ONE
1175     checkList [checkEntityUsage new_decl_vers u | u <- old_decl_vers]   `thenM` \ recompile ->
1176     if recompile then
1177         returnM outOfDate       -- This one failed, so just bail out now
1178     else
1179         up_to_date (ptext SLIT("  Great!  The bits I use are up to date"))
1180     }
1181
1182 ------------------------
1183 checkModuleVersion old_mod_vers new_mod_vers
1184   | new_mod_vers == old_mod_vers
1185   = up_to_date (ptext SLIT("Module version unchanged"))
1186
1187   | otherwise
1188   = out_of_date_vers (ptext SLIT("  Module version has changed"))
1189                      old_mod_vers new_mod_vers
1190
1191 ------------------------
1192 checkExportList Nothing  new_vers = upToDate
1193 checkExportList (Just v) new_vers = v /= new_vers
1194
1195 ------------------------
1196 checkEntityUsage new_vers (name,old_vers)
1197   = case new_vers name of
1198
1199         Nothing       ->        -- We used it before, but it ain't there now
1200                           out_of_date (sep [ptext SLIT("No longer exported:"), ppr name])
1201
1202         Just (_, new_vers)      -- It's there, but is it up to date?
1203           | new_vers == old_vers -> traceHiDiffs (text "  Up to date" <+> ppr name <+> parens (ppr new_vers)) `thenM_`
1204                                     returnM upToDate
1205           | otherwise            -> out_of_date_vers (ptext SLIT("  Out of date:") <+> ppr name)
1206                                                      old_vers new_vers
1207
1208 up_to_date  msg = traceHiDiffs msg `thenM_` returnM upToDate
1209 out_of_date msg = traceHiDiffs msg `thenM_` returnM outOfDate
1210 out_of_date_vers msg old_vers new_vers 
1211   = out_of_date (hsep [msg, ppr old_vers, ptext SLIT("->"), ppr new_vers])
1212
1213 ----------------------
1214 checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
1215 -- This helper is used in two places
1216 checkList []             = returnM upToDate
1217 checkList (check:checks) = check        `thenM` \ recompile ->
1218                            if recompile then 
1219                                 returnM outOfDate
1220                            else
1221                                 checkList checks
1222 \end{code}
1223
1224 %************************************************************************
1225 %*                                                                      *
1226                 Converting things to their Iface equivalents
1227 %*                                                                      *
1228 %************************************************************************
1229
1230 \begin{code}
1231 tyThingToIfaceDecl :: TyThing -> IfaceDecl
1232 -- Assumption: the thing is already tidied, so that locally-bound names
1233 --             (lambdas, for-alls) already have non-clashing OccNames
1234 -- Reason: Iface stuff uses OccNames, and the conversion here does
1235 --         not do tidying on the way
1236 tyThingToIfaceDecl (AnId id)
1237   = IfaceId { ifName   = getOccName id,
1238               ifType   = toIfaceType (idType id),
1239               ifIdInfo = info }
1240   where
1241     info = case toIfaceIdInfo (idInfo id) of
1242                 []    -> NoInfo
1243                 items -> HasInfo items
1244
1245 tyThingToIfaceDecl (AClass clas)
1246   = IfaceClass { ifCtxt   = toIfaceContext sc_theta,
1247                  ifName   = getOccName clas,
1248                  ifTyVars = toIfaceTvBndrs clas_tyvars,
1249                  ifFDs    = map toIfaceFD clas_fds,
1250                  ifATs    = map (tyThingToIfaceDecl . ATyCon) clas_ats,
1251                  ifSigs   = map toIfaceClassOp op_stuff,
1252                  ifRec    = boolToRecFlag (isRecursiveTyCon tycon) }
1253   where
1254     (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff) 
1255       = classExtraBigSig clas
1256     tycon = classTyCon clas
1257
1258     toIfaceClassOp (sel_id, def_meth)
1259         = ASSERT(sel_tyvars == clas_tyvars)
1260           IfaceClassOp (getOccName sel_id) def_meth (toIfaceType op_ty)
1261         where
1262                 -- Be careful when splitting the type, because of things
1263                 -- like         class Foo a where
1264                 --                op :: (?x :: String) => a -> a
1265                 -- and          class Baz a where
1266                 --                op :: (Ord a) => a -> a
1267           (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
1268           op_ty                = funResultTy rho_ty
1269
1270     toIfaceFD (tvs1, tvs2) = (map getFS tvs1, map getFS tvs2)
1271
1272 tyThingToIfaceDecl (ATyCon tycon)
1273   | isSynTyCon tycon
1274   = IfaceSyn {  ifName    = getOccName tycon,
1275                 ifTyVars  = toIfaceTvBndrs tyvars,
1276                 ifOpenSyn = syn_isOpen,
1277                 ifSynRhs  = toIfaceType syn_tyki,
1278                 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)
1279              }
1280
1281   | isAlgTyCon tycon
1282   = IfaceData { ifName    = getOccName tycon,
1283                 ifTyVars  = toIfaceTvBndrs tyvars,
1284                 ifCtxt    = toIfaceContext (tyConStupidTheta tycon),
1285                 ifCons    = ifaceConDecls (algTyConRhs tycon),
1286                 ifRec     = boolToRecFlag (isRecursiveTyCon tycon),
1287                 ifGadtSyntax = isGadtSyntaxTyCon tycon,
1288                 ifGeneric = tyConHasGenerics tycon,
1289                 ifFamInst = famInstToIface (tyConFamInst_maybe tycon)}
1290
1291   | isForeignTyCon tycon
1292   = IfaceForeign { ifName    = getOccName tycon,
1293                    ifExtName = tyConExtName tycon }
1294
1295   | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
1296   where
1297     tyvars = tyConTyVars tycon
1298     (syn_isOpen, syn_tyki) = case synTyConRhs tycon of
1299                                OpenSynTyCon ki _ -> (True , ki)
1300                                SynonymTyCon ty   -> (False, ty)
1301
1302     ifaceConDecls (NewTyCon { data_con = con })     = 
1303       IfNewTyCon  (ifaceConDecl con)
1304     ifaceConDecls (DataTyCon { data_cons = cons })  = 
1305       IfDataTyCon (map ifaceConDecl cons)
1306     ifaceConDecls OpenTyCon {}                      = IfOpenDataTyCon
1307     ifaceConDecls AbstractTyCon                     = IfAbstractTyCon
1308         -- The last case happens when a TyCon has been trimmed during tidying
1309         -- Furthermore, tyThingToIfaceDecl is also used
1310         -- in TcRnDriver for GHCi, when browsing a module, in which case the
1311         -- AbstractTyCon case is perfectly sensible.
1312
1313     ifaceConDecl data_con 
1314         = IfCon   { ifConOcc     = getOccName (dataConName data_con),
1315                     ifConInfix   = dataConIsInfix data_con,
1316                     ifConUnivTvs = toIfaceTvBndrs (dataConUnivTyVars data_con),
1317                     ifConExTvs   = toIfaceTvBndrs (dataConExTyVars data_con),
1318                     ifConEqSpec  = to_eq_spec (dataConEqSpec data_con),
1319                     ifConCtxt    = toIfaceContext (dataConEqTheta data_con ++ dataConDictTheta data_con),
1320                     ifConArgTys  = map toIfaceType (dataConOrigArgTys data_con),
1321                     ifConFields  = map getOccName 
1322                                        (dataConFieldLabels data_con),
1323                     ifConStricts = dataConStrictMarks data_con }
1324
1325     to_eq_spec spec = [(getOccName tv, toIfaceType ty) | (tv,ty) <- spec]
1326
1327     famInstToIface Nothing                    = Nothing
1328     famInstToIface (Just (famTyCon, instTys)) = 
1329       Just (toIfaceTyCon famTyCon, map toIfaceType instTys)
1330
1331 tyThingToIfaceDecl (ADataCon dc)
1332  = pprPanic "toIfaceDecl" (ppr dc)      -- Should be trimmed out earlier
1333
1334
1335 getFS x = occNameFS (getOccName x)
1336
1337 --------------------------
1338 instanceToIfaceInst :: Instance -> IfaceInst
1339 instanceToIfaceInst ispec@(Instance { is_dfun = dfun_id, is_flag = oflag,
1340                                       is_cls = cls_name, is_tcs = mb_tcs })
1341   = ASSERT( cls_name == className cls )
1342     IfaceInst { ifDFun    = dfun_name,
1343                 ifOFlag   = oflag,
1344                 ifInstCls = cls_name,
1345                 ifInstTys = map do_rough mb_tcs,
1346                 ifInstOrph = orph }
1347   where
1348     do_rough Nothing  = Nothing
1349     do_rough (Just n) = Just (toIfaceTyCon_name n)
1350
1351     dfun_name = idName dfun_id
1352     mod       = nameModule dfun_name
1353     is_local name = nameIsLocalOrFrom mod name
1354
1355         -- Compute orphanhood.  See Note [Orphans] in IfaceSyn
1356     (_, _, cls, tys) = tcSplitDFunTy (idType dfun_id)
1357                 -- Slightly awkward: we need the Class to get the fundeps
1358     (tvs, fds) = classTvsFds cls
1359     arg_names = [filterNameSet is_local (tyClsNamesOfType ty) | ty <- tys]
1360     orph | is_local cls_name = Just (nameOccName cls_name)
1361          | all isJust mb_ns  = head mb_ns
1362          | otherwise         = Nothing
1363     
1364     mb_ns :: [Maybe OccName]    -- One for each fundep; a locally-defined name
1365                                 -- that is not in the "determined" arguments
1366     mb_ns | null fds   = [choose_one arg_names]
1367           | otherwise  = map do_one fds
1368     do_one (ltvs,rtvs) = choose_one [ns | (tv,ns) <- tvs `zip` arg_names
1369                                         , not (tv `elem` rtvs)]
1370
1371     choose_one :: [NameSet] -> Maybe OccName
1372     choose_one nss = case nameSetToList (unionManyNameSets nss) of
1373                         []     -> Nothing
1374                         (n:ns) -> Just (nameOccName n)
1375
1376 --------------------------
1377 famInstToIfaceFamInst :: FamInst -> IfaceFamInst
1378 famInstToIfaceFamInst fi@(FamInst { fi_tycon = tycon,
1379                                             fi_fam = fam, fi_tcs = mb_tcs })
1380   = IfaceFamInst { ifFamInstTyCon  = toIfaceTyCon tycon
1381                  , ifFamInstFam    = fam
1382                  , ifFamInstTys    = map do_rough mb_tcs }
1383   where
1384     do_rough Nothing  = Nothing
1385     do_rough (Just n) = Just (toIfaceTyCon_name n)
1386
1387 --------------------------
1388 toIfaceLetBndr id  = IfLetBndr (occNameFS (getOccName id))
1389                                (toIfaceType (idType id)) 
1390                                prag_info
1391   where
1392         -- Stripped-down version of tcIfaceIdInfo
1393         -- Change this if you want to export more IdInfo for
1394         -- non-top-level Ids.  Don't forget to change
1395         -- CoreTidy.tidyLetBndr too!
1396         --
1397         -- See Note [IdInfo on nested let-bindings] in IfaceSyn
1398     id_info = idInfo id
1399     inline_prag = inlinePragInfo id_info
1400     prag_info | isAlwaysActive inline_prag = NoInfo
1401               | otherwise                  = HasInfo [HsInline inline_prag]
1402
1403 --------------------------
1404 toIfaceIdInfo :: IdInfo -> [IfaceInfoItem]
1405 toIfaceIdInfo id_info
1406   = catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo, 
1407                inline_hsinfo, wrkr_hsinfo,  unfold_hsinfo] 
1408   where
1409     ------------  Arity  --------------
1410     arity_info = arityInfo id_info
1411     arity_hsinfo | arity_info == 0 = Nothing
1412                  | otherwise       = Just (HsArity arity_info)
1413
1414     ------------ Caf Info --------------
1415     caf_info   = cafInfo id_info
1416     caf_hsinfo = case caf_info of
1417                    NoCafRefs -> Just HsNoCafRefs
1418                    _other    -> Nothing
1419
1420     ------------  Strictness  --------------
1421         -- No point in explicitly exporting TopSig
1422     strict_hsinfo = case newStrictnessInfo id_info of
1423                         Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
1424                         _other                        -> Nothing
1425
1426     ------------  Worker  --------------
1427     work_info   = workerInfo id_info
1428     has_worker  = workerExists work_info
1429     wrkr_hsinfo = case work_info of
1430                     HasWorker work_id wrap_arity -> 
1431                         Just (HsWorker ((idName work_id)) wrap_arity)
1432                     NoWorker -> Nothing
1433
1434     ------------  Unfolding  --------------
1435     -- The unfolding is redundant if there is a worker
1436     unfold_info  = unfoldingInfo id_info
1437     rhs          = unfoldingTemplate unfold_info
1438     no_unfolding = neverUnfold unfold_info
1439                         -- The CoreTidy phase retains unfolding info iff
1440                         -- we want to expose the unfolding, taking into account
1441                         -- unconditional NOINLINE, etc.  See TidyPgm.addExternal
1442     unfold_hsinfo | no_unfolding = Nothing                      
1443                   | has_worker   = Nothing      -- Unfolding is implicit
1444                   | otherwise    = Just (HsUnfold (toIfaceExpr rhs))
1445                                         
1446     ------------  Inline prag  --------------
1447     inline_prag = inlinePragInfo id_info
1448     inline_hsinfo | isAlwaysActive inline_prag     = Nothing
1449                   | no_unfolding && not has_worker = Nothing
1450                         -- If the iface file give no unfolding info, we 
1451                         -- don't need to say when inlining is OK!
1452                   | otherwise                      = Just (HsInline inline_prag)
1453
1454 --------------------------
1455 coreRuleToIfaceRule :: Module -> CoreRule -> IfaceRule
1456 coreRuleToIfaceRule mod (BuiltinRule { ru_fn = fn})
1457   = pprTrace "toHsRule: builtin" (ppr fn) $
1458     bogusIfaceRule fn
1459
1460 coreRuleToIfaceRule mod (Rule { ru_name = name, ru_fn = fn, 
1461                                 ru_act = act, ru_bndrs = bndrs,
1462                                 ru_args = args, ru_rhs = rhs })
1463   = IfaceRule { ifRuleName  = name, ifActivation = act, 
1464                 ifRuleBndrs = map toIfaceBndr bndrs,
1465                 ifRuleHead  = fn, 
1466                 ifRuleArgs  = map do_arg args,
1467                 ifRuleRhs   = toIfaceExpr rhs,
1468                 ifRuleOrph  = orph }
1469   where
1470         -- For type args we must remove synonyms from the outermost
1471         -- level.  Reason: so that when we read it back in we'll
1472         -- construct the same ru_rough field as we have right now;
1473         -- see tcIfaceRule
1474     do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
1475     do_arg arg       = toIfaceExpr arg
1476
1477         -- Compute orphanhood.  See Note [Orphans] in IfaceSyn
1478         -- A rule is an orphan only if none of the variables
1479         -- mentioned on its left-hand side are locally defined
1480     lhs_names = fn : nameSetToList (exprsFreeNames args)
1481                 -- No need to delete bndrs, because
1482                 -- exprsFreeNames finds only External names
1483
1484     orph = case filter (nameIsLocalOrFrom mod) lhs_names of
1485                         (n:ns) -> Just (nameOccName n)
1486                         []     -> Nothing
1487
1488 bogusIfaceRule :: Name -> IfaceRule
1489 bogusIfaceRule id_name
1490   = IfaceRule { ifRuleName = FSLIT("bogus"), ifActivation = NeverActive,  
1491         ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [], 
1492         ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing }
1493
1494 ---------------------
1495 toIfaceExpr :: CoreExpr -> IfaceExpr
1496 toIfaceExpr (Var v)       = toIfaceVar v
1497 toIfaceExpr (Lit l)       = IfaceLit l
1498 toIfaceExpr (Type ty)     = IfaceType (toIfaceType ty)
1499 toIfaceExpr (Lam x b)     = IfaceLam (toIfaceBndr x) (toIfaceExpr b)
1500 toIfaceExpr (App f a)     = toIfaceApp f [a]
1501 toIfaceExpr (Case s x ty as) = IfaceCase (toIfaceExpr s) (getFS x) (toIfaceType ty) (map toIfaceAlt as)
1502 toIfaceExpr (Let b e)     = IfaceLet (toIfaceBind b) (toIfaceExpr e)
1503 toIfaceExpr (Cast e co)   = IfaceCast (toIfaceExpr e) (toIfaceType co)
1504 toIfaceExpr (Note n e)    = IfaceNote (toIfaceNote n) (toIfaceExpr e)
1505
1506 ---------------------
1507 toIfaceNote (SCC cc)      = IfaceSCC cc
1508 toIfaceNote InlineMe      = IfaceInlineMe
1509 toIfaceNote (CoreNote s)  = IfaceCoreNote s
1510
1511 ---------------------
1512 toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
1513 toIfaceBind (Rec prs)    = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
1514
1515 ---------------------
1516 toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
1517
1518 ---------------------
1519 toIfaceCon (DataAlt dc) | isTupleTyCon tc = IfaceTupleAlt (tupleTyConBoxity tc)
1520                         | otherwise       = IfaceDataAlt (getName dc)
1521                         where
1522                           tc = dataConTyCon dc
1523            
1524 toIfaceCon (LitAlt l) = IfaceLitAlt l
1525 toIfaceCon DEFAULT    = IfaceDefault
1526
1527 ---------------------
1528 toIfaceApp (App f a) as = toIfaceApp f (a:as)
1529 toIfaceApp (Var v) as
1530   = case isDataConWorkId_maybe v of
1531         -- We convert the *worker* for tuples into IfaceTuples
1532         Just dc |  isTupleTyCon tc && saturated 
1533                 -> IfaceTuple (tupleTyConBoxity tc) tup_args
1534           where
1535             val_args  = dropWhile isTypeArg as
1536             saturated = val_args `lengthIs` idArity v
1537             tup_args  = map toIfaceExpr val_args
1538             tc        = dataConTyCon dc
1539
1540         other -> mkIfaceApps (toIfaceVar v) as
1541
1542 toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
1543
1544 mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
1545
1546 ---------------------
1547 toIfaceVar :: Id -> IfaceExpr
1548 toIfaceVar v 
1549   | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
1550           -- Foreign calls have special syntax
1551   | isExternalName name             = IfaceExt name
1552   | Just (TickBox m ix) <- isTickBoxOp_maybe v
1553                                     = IfaceTick m ix
1554   | otherwise                       = IfaceLcl (getFS name)
1555   where
1556     name = idName v
1557 \end{code}