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