MkIface.lhs 73.3 KB
Newer Older
1
%
2
% (c) The University of Glasgow 2006-2008
3
4
5
6
% (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
%

\begin{code}
dterei's avatar
dterei committed
7
8
9
-- | Module for constructing @ModIface@ values (interface files),
-- writing them to disk and comparing two versions to see if
-- recompilation is required.
10
module MkIface ( 
Simon Marlow's avatar
Simon Marlow committed
11
12
        mkUsedNames,
        mkDependencies,
13
14
        mkIface,        -- Build a ModIface from a ModGuts, 
                        -- including computing version information
15

Simon Marlow's avatar
Simon Marlow committed
16
17
        mkIfaceTc,

18
        writeIfaceFile, -- Write the interface file
19

20
21
        checkOldIface,  -- See if recompilation is required, by
                        -- comparing version information
22
23

        tyThingToIfaceDecl -- Converting things to their Iface equivalents
24
25
26
 ) where
\end{code}

27
28
29
  -----------------------------------------------
          Recompilation checking
  -----------------------------------------------
30

31
32
A complete description of how recompilation checking works can be
found in the wiki commentary:
33

34
 http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
35

36
37
Please read the above page for a top-down description of how this all
works.  Notes below cover specific issues related to the implementation.
38
39

Basic idea: 
40

41
  * In the mi_usages information in an interface, we record the 
42
    fingerprint of each free variable of the module
43

44
45
46
47
48
  * In mkIface, we compute the fingerprint of each exported thing A.f.
    For each external thing that A.f refers to, we include the fingerprint
    of the external reference when computing the fingerprint of A.f.  So
    if anything that A.f depends on changes, then A.f's fingerprint will
    change.
GregWeber's avatar
GregWeber committed
49
50
    Also record any dependent files added with addDependentFile.
    In the future record any #include usages.
51
52

  * In checkOldIface we compare the mi_usages for the module with
53
    the actual fingerprint for all each thing recorded in mi_usages
54
55
56
57

\begin{code}
#include "HsVersions.h"

Simon Marlow's avatar
Simon Marlow committed
58
59
import IfaceSyn
import LoadIface
60
61
import FlagChecker

Simon Marlow's avatar
Simon Marlow committed
62
63
import Id
import IdInfo
64
import Demand
65
import Annotations
66
import CoreSyn
67
import CoreFVs
Simon Marlow's avatar
Simon Marlow committed
68
import Class
69
import Kind
Simon Marlow's avatar
Simon Marlow committed
70
71
72
73
74
75
import TyCon
import DataCon
import Type
import TcType
import InstEnv
import FamInstEnv
76
import TcRnMonad
77
import HsSyn
Simon Marlow's avatar
Simon Marlow committed
78
import HscTypes
79
import Finder
Simon Marlow's avatar
Simon Marlow committed
80
import DynFlags
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
81
import VarEnv
82
import VarSet
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
83
import Var
Simon Marlow's avatar
Simon Marlow committed
84
import Name
85
import Avail
Ian Lynagh's avatar
Ian Lynagh committed
86
import RdrName
87
88
import NameEnv
import NameSet
Simon Marlow's avatar
Simon Marlow committed
89
import Module
Simon Marlow's avatar
Simon Marlow committed
90
91
92
93
import BinIface
import ErrUtils
import Digraph
import SrcLoc
94
95
import Outputable
import BasicTypes       hiding ( SuccessFlag(..) )
96
import UniqFM
97
import Unique
98
import Util             hiding ( eqListBy )
99
import FastString
Simon Marlow's avatar
Simon Marlow committed
100
import Maybes
Simon Marlow's avatar
Simon Marlow committed
101
import ListSetOps
102
103
import Binary
import Fingerprint
104
import Bag
105

Simon Marlow's avatar
Simon Marlow committed
106
107
import Control.Monad
import Data.List
108
109
import Data.Map (Map)
import qualified Data.Map as Map
Simon Marlow's avatar
Simon Marlow committed
110
import Data.IORef
Ian Lynagh's avatar
Ian Lynagh committed
111
import System.FilePath
GregWeber's avatar
GregWeber committed
112
import System.Directory (getModificationTime)
113
114
115
116
117
\end{code}



%************************************************************************
118
%*                                                                      *
119
\subsection{Completing an interface}
120
%*                                                                      *
121
122
123
124
%************************************************************************

\begin{code}
mkIface :: HscEnv
125
126
127
128
        -> Maybe Fingerprint    -- The old fingerprint, if we have it
        -> ModDetails           -- The trimmed, tidied interface
        -> ModGuts              -- Usages, deprecations, etc
        -> IO (Messages,
Thomas Schilling's avatar
Thomas Schilling committed
129
               Maybe (ModIface, -- The new one
130
                      Bool))    -- True <=> there was an old Iface, and the
131
132
                                --          new one is identical, so no need
                                --          to write it
133

134
mkIface hsc_env maybe_old_fingerprint mod_details
135
136
137
         ModGuts{     mg_module     = this_mod,
                      mg_boot       = is_boot,
                      mg_used_names = used_names,
138
                      mg_used_th    = used_th,
139
140
141
142
143
144
                      mg_deps       = deps,
                      mg_dir_imps   = dir_imp_mods,
                      mg_rdr_env    = rdr_env,
                      mg_fix_env    = fix_env,
                      mg_warns      = warns,
                      mg_hpc_info   = hpc_info,
GregWeber's avatar
GregWeber committed
145
146
147
                      mg_trust_pkg  = self_trust,
                      mg_dependent_files = dependent_files
                    }
148
        = mkIface_ hsc_env maybe_old_fingerprint
149
                   this_mod is_boot used_names used_th deps rdr_env fix_env
GregWeber's avatar
GregWeber committed
150
                   warns hpc_info dir_imp_mods self_trust dependent_files mod_details
Thomas Schilling's avatar
Thomas Schilling committed
151

Simon Marlow's avatar
Simon Marlow committed
152
153
154
155
-- | make an interface from the results of typechecking only.  Useful
-- for non-optimising compilation, or where we aren't generating any
-- object code at all ('HscNothing').
mkIfaceTc :: HscEnv
dterei's avatar
dterei committed
156
157
158
159
          -> Maybe Fingerprint  -- The old fingerprint, if we have it
          -> ModDetails         -- gotten from mkBootModDetails, probably
          -> TcGblEnv           -- Usages, deprecations, etc
          -> IO (Messages, Maybe (ModIface, Bool))
160
mkIfaceTc hsc_env maybe_old_fingerprint mod_details
Simon Marlow's avatar
Simon Marlow committed
161
162
163
164
165
  tc_result@TcGblEnv{ tcg_mod = this_mod,
                      tcg_src = hsc_src,
                      tcg_imports = imports,
                      tcg_rdr_env = rdr_env,
                      tcg_fix_env = fix_env,
Ian Lynagh's avatar
Ian Lynagh committed
166
                      tcg_warns = warns,
167
                      tcg_hpc = other_hpc_info,
GregWeber's avatar
GregWeber committed
168
169
                      tcg_th_splice_used = tc_splice_used,
                      tcg_dependent_files = dependent_files
Simon Marlow's avatar
Simon Marlow committed
170
171
                    }
  = do
172
          let used_names = mkUsedNames tc_result
Simon Marlow's avatar
Simon Marlow committed
173
174
          deps <- mkDependencies tc_result
          let hpc_info = emptyHpcInfo other_hpc_info
175
          used_th <- readIORef tc_splice_used
GregWeber's avatar
GregWeber committed
176
          dep_files <- (readIORef dependent_files)
177
          mkIface_ hsc_env maybe_old_fingerprint
178
                   this_mod (isHsBoot hsc_src) used_names used_th deps rdr_env
179
                   fix_env warns hpc_info (imp_mods imports)
GregWeber's avatar
GregWeber committed
180
                   (imp_trust_own_pkg imports) dep_files mod_details
Simon Marlow's avatar
Simon Marlow committed
181
182
        

183
184
mkUsedNames :: TcGblEnv -> NameSet
mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
Simon Marlow's avatar
Simon Marlow committed
185
        
186
187
-- | Extract information from the rename and typecheck phases to produce
-- a dependencies information for the module being compiled.
Simon Marlow's avatar
Simon Marlow committed
188
189
190
191
192
193
194
mkDependencies :: TcGblEnv -> IO Dependencies
mkDependencies
          TcGblEnv{ tcg_mod = mod,
                    tcg_imports = imports,
                    tcg_th_used = th_var
                  }
 = do 
dterei's avatar
dterei committed
195
196
197
      -- Template Haskell used?
      th_used <- readIORef th_var
      let dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
Simon Marlow's avatar
Simon Marlow committed
198
199
200
201
202
203
204
                -- M.hi-boot can be in the imp_dep_mods, but we must remove
                -- it before recording the modules on which this one depends!
                -- (We want to retain M.hi-boot in imp_dep_mods so that 
                --  loadHiBootInterface can see if M's direct imports depend 
                --  on M.hi-boot, and hence that we should do the hi-boot consistency 
                --  check.)

205
206
          pkgs | th_used   = insertList thPackageId (imp_dep_pkgs imports)
               | otherwise = imp_dep_pkgs imports
Simon Marlow's avatar
Simon Marlow committed
207

208
209
210
211
212
          -- Set the packages required to be Safe according to Safe Haskell.
          -- See Note [RnNames . Tracking Trust Transitively]
          sorted_pkgs = sortBy stablePackageIdCmp pkgs
          trust_pkgs  = imp_trust_pkgs imports
          dep_pkgs'   = map (\x -> (x, x `elem` trust_pkgs)) sorted_pkgs
213

214
      return Deps { dep_mods   = sortBy (stableModuleNameCmp `on` fst) dep_mods,
215
                    dep_pkgs   = dep_pkgs',
216
217
                    dep_orphs  = sortBy stableModuleCmp (imp_orphs  imports),
                    dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
218
219
                    -- sort to get into canonical order
                    -- NB. remember to use lexicographic ordering
Simon Marlow's avatar
Simon Marlow committed
220

221
mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> IsBootInterface
222
         -> NameSet -> Bool -> Dependencies -> GlobalRdrEnv
Ian Lynagh's avatar
Ian Lynagh committed
223
         -> NameEnv FixItem -> Warnings -> HpcInfo
224
         -> ImportedMods -> Bool
GregWeber's avatar
GregWeber committed
225
         -> [FilePath]
Ian Lynagh's avatar
Ian Lynagh committed
226
         -> ModDetails
227
         -> IO (Messages, Maybe (ModIface, Bool))
228
mkIface_ hsc_env maybe_old_fingerprint 
229
         this_mod is_boot used_names used_th deps rdr_env fix_env src_warns
GregWeber's avatar
GregWeber committed
230
         hpc_info dir_imp_mods pkg_trust_req dependent_files
dterei's avatar
dterei committed
231
232
233
234
         ModDetails{  md_insts     = insts, 
                      md_fam_insts = fam_insts,
                      md_rules     = rules,
                      md_anns      = anns,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
235
                      md_vect_info = vect_info,
dterei's avatar
dterei committed
236
237
238
239
240
241
242
243
                      md_types     = type_env,
                      md_exports   = exports }
-- NB:  notice that mkIface does not look at the bindings
--      only at the TypeEnv.  The previous Tidy phase has
--      put exactly the info into the TypeEnv that we want
--      to expose in the interface

  = do  { usages  <- mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
244
        ; safeInf <- hscGetSafeInf hsc_env
Simon Marlow's avatar
Simon Marlow committed
245

dterei's avatar
dterei committed
246
        ; let   { entities = typeEnvElts type_env ;
247
                  decls  = [ tyThingToIfaceDecl entity
dterei's avatar
dterei committed
248
249
                           | entity <- entities,
                             let name = getName entity,
250
                             not (isImplicitTyThing entity),
dterei's avatar
dterei committed
251
252
253
254
255
256
257
258
259
260
261
                                -- No implicit Ids and class tycons in the interface file
                             not (isWiredInName name),
                                -- Nor wired-in things; the compiler knows about them anyhow
                             nameIsLocalOrFrom this_mod name  ]
                                -- Sigh: see Note [Root-main Id] in TcRnDriver

                ; fixities    = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
                ; warns       = src_warns
                ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
                ; iface_insts = map instanceToIfaceInst insts
                ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
262
                ; iface_vect_info = flattenVectInfo vect_info
dterei's avatar
dterei committed
263
264
                -- Check if we are in Safe Inference mode but we failed to pass
                -- the muster
265
266
267
268
                ; safeMode    = if safeInferOn dflags  && not safeInf
                                    then Sf_None
                                    else safeHaskell dflags
                ; trust_info  = setSafeMode safeMode
269

dterei's avatar
dterei committed
270
271
272
273
274
275
276
277
278
279
280
281
                ; intermediate_iface = ModIface { 
                        mi_module      = this_mod,
                        mi_boot        = is_boot,
                        mi_deps        = deps,
                        mi_usages      = usages,
                        mi_exports     = mkIfaceExports exports,
        
                        -- Sort these lexicographically, so that
                        -- the result is stable across compilations
                        mi_insts       = sortLe le_inst iface_insts,
                        mi_fam_insts   = sortLe le_fam_inst iface_fam_insts,
                        mi_rules       = sortLe le_rule iface_rules,
282

dterei's avatar
dterei committed
283
                        mi_vect_info   = iface_vect_info,
chak@cse.unsw.edu.au.'s avatar
chak@cse.unsw.edu.au. committed
284

dterei's avatar
dterei committed
285
286
287
288
                        mi_fixities    = fixities,
                        mi_warns       = warns,
                        mi_anns        = mkIfaceAnnotations anns,
                        mi_globals     = Just rdr_env,
289

290
                        -- Left out deliberately: filled in by addFingerprints
dterei's avatar
dterei committed
291
292
                        mi_iface_hash  = fingerprint0,
                        mi_mod_hash    = fingerprint0,
293
                        mi_flag_hash   = fingerprint0,
dterei's avatar
dterei committed
294
                        mi_exp_hash    = fingerprint0,
dterei's avatar
dterei committed
295
                        mi_used_th     = used_th,
296
                        mi_orphan_hash = fingerprint0,
297
                        mi_orphan      = False, -- Always set by addFingerprints, but
dterei's avatar
dterei committed
298
                                                -- it's a strict field, so we can't omit it.
dterei's avatar
dterei committed
299
                        mi_finsts      = False, -- Ditto
dterei's avatar
dterei committed
300
301
302
303
304
                        mi_decls       = deliberatelyOmitted "decls",
                        mi_hash_fn     = deliberatelyOmitted "hash_fn",
                        mi_hpc         = isHpcUsed hpc_info,
                        mi_trust       = trust_info,
                        mi_trust_pkg   = pkg_trust_req,
305

dterei's avatar
dterei committed
306
307
308
309
                        -- And build the cached values
                        mi_warn_fn     = mkIfaceWarnCache warns,
                        mi_fix_fn      = mkIfaceFixCache fixities }
                }
310

311
        ; (new_iface, no_change_at_all) 
dterei's avatar
dterei committed
312
313
                <- {-# SCC "versioninfo" #-}
                         addFingerprints hsc_env maybe_old_fingerprint
314
                                         intermediate_iface decls
315

dterei's avatar
dterei committed
316
317
                -- Warn about orphans
        ; let warn_orphs      = wopt Opt_WarnOrphans dflags
318
              warn_auto_orphs = wopt Opt_WarnAutoOrphans dflags
319
              orph_warnings   --- Laziness means no work done unless -fwarn-orphans
dterei's avatar
dterei committed
320
321
322
323
324
325
326
327
328
329
                | warn_orphs || warn_auto_orphs = rule_warns `unionBags` inst_warns
                | otherwise                     = emptyBag
              errs_and_warns = (orph_warnings, emptyBag)
              unqual = mkPrintUnqualified dflags rdr_env
              inst_warns = listToBag [ instOrphWarn unqual d 
                                     | (d,i) <- insts `zip` iface_insts
                                     , isNothing (ifInstOrph i) ]
              rule_warns = listToBag [ ruleOrphWarn unqual this_mod r 
                                     | r <- iface_rules
                                     , isNothing (ifRuleOrph r)
330
331
                                     , if ifRuleAuto r then warn_auto_orphs
                                                       else warn_orphs ]
332

dterei's avatar
dterei committed
333
        ; if errorsFound dflags errs_and_warns
Thomas Schilling's avatar
Thomas Schilling committed
334
335
            then return ( errs_and_warns, Nothing )
            else do {
336

dterei's avatar
dterei committed
337
338
339
                -- Debug printing
        ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE" 
                        (pprModIface new_iface)
340

341
342
                -- bug #1617: on reload we weren't updating the PrintUnqualified
                -- correctly.  This stems from the fact that the interface had
343
                -- not changed, so addFingerprints returns the old ModIface
344
345
346
                -- with the old GlobalRdrEnv (mi_globals).
        ; let final_iface = new_iface{ mi_globals = Just rdr_env }

dterei's avatar
dterei committed
347
        ; return (errs_and_warns, Just (final_iface, no_change_at_all)) }}
348
  where
349
350
351
352
353
     r1 `le_rule`     r2 = ifRuleName      r1    <=    ifRuleName      r2
     i1 `le_inst`     i2 = ifDFun          i1 `le_occ` ifDFun          i2  
     i1 `le_fam_inst` i2 = ifFamInstTcName i1 `le_occ` ifFamInstTcName i2

     le_occ :: Name -> Name -> Bool
dterei's avatar
dterei committed
354
355
        -- Compare lexicographically by OccName, *not* by unique, because 
        -- the latter is not stable across compilations
356
     le_occ n1 n2 = nameOccName n1 <= nameOccName n2
357

358
     dflags = hsc_dflags hsc_env
359
360

     deliberatelyOmitted :: String -> a
361
     deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
362

363
     ifFamInstTcName = ifaceTyConName . ifFamInstTyCon
364

365
366
367
368
     flattenVectInfo (VectInfo { vectInfoVar          = vVar
                               , vectInfoTyCon        = vTyCon
                               , vectInfoScalarVars   = vScalarVars
                               , vectInfoScalarTyCons = vScalarTyCons
369
                               }) = 
370
371
372
373
374
375
       IfaceVectInfo
       { ifaceVectInfoVar          = [Var.varName v | (v, _  ) <- varEnvElts  vVar]
       , ifaceVectInfoTyCon        = [tyConName t   | (t, t_v) <- nameEnvElts vTyCon, t /= t_v]
       , ifaceVectInfoTyConReuse   = [tyConName t   | (t, t_v) <- nameEnvElts vTyCon, t == t_v]
       , ifaceVectInfoScalarVars   = [Var.varName v | v <- varSetElems vScalarVars]
       , ifaceVectInfoScalarTyCons = nameSetToList vScalarTyCons
376
       } 
377

378
-----------------------------
379
380
writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
writeIfaceFile dflags location new_iface
Ian Lynagh's avatar
Ian Lynagh committed
381
    = do createDirectoryHierarchy (takeDirectory hi_file_path)
382
         writeBinIface dflags hi_file_path new_iface
383
    where hi_file_path = ml_hi_file location
384
385


386
387
-- -----------------------------------------------------------------------------
-- Look up parents and versions of Names
388

389
390
-- This is like a global version of the mi_hash_fn field in each ModIface.
-- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get
391
-- the parent and version info.
392

393
mkHashFun
394
395
        :: HscEnv                       -- needed to look up versions
        -> ExternalPackageState         -- ditto
396
397
        -> (Name -> Fingerprint)
mkHashFun hsc_env eps
398
399
  = \name -> 
      let 
400
        mod = ASSERT2( isExternalName name, ppr name ) nameModule name
401
402
403
404
        occ = nameOccName name
        iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse` 
                   pprPanic "lookupVers2" (ppr mod <+> ppr occ)
      in  
405
406
        snd (mi_hash_fn iface occ `orElse` 
                  pprPanic "lookupVers1" (ppr mod <+> ppr occ))
407
  where
408
409
      hpt = hsc_HPT hsc_env
      pit = eps_PIT eps
410

411
412
413
414
415
416
-- ---------------------------------------------------------------------------
-- Compute fingerprints for the interface

addFingerprints
        :: HscEnv
        -> Maybe Fingerprint -- the old fingerprint, if any
dterei's avatar
dterei committed
417
        -> ModIface          -- The new interface (lacking decls)
418
419
        -> [IfaceDecl]       -- The new decls
        -> IO (ModIface,     -- Updated interface
dterei's avatar
dterei committed
420
               Bool)         -- True <=> no changes at all; 
421
422
423
424
425
426
                             -- no need to write Iface

addFingerprints hsc_env mb_old_fingerprint iface0 new_decls
 = do
   eps <- hscEPS hsc_env
   let
427
        -- The ABI of a declaration represents everything that is made
428
429
430
431
432
433
434
435
        -- visible about the declaration that a client can depend on.
        -- see IfaceDeclABI below.
       declABI :: IfaceDecl -> IfaceDeclABI 
       declABI decl = (this_mod, decl, extras)
        where extras = declExtras fix_fn non_orph_rules non_orph_insts decl

       edges :: [(IfaceDeclABI, Unique, [Unique])]
       edges = [ (abi, getUnique (ifName decl), out)
dterei's avatar
dterei committed
436
               | decl <- new_decls
437
               , let abi = declABI decl
dterei's avatar
dterei committed
438
               , let out = localOccs $ freeNamesDeclABI abi
439
440
               ]

simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
441
       name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n
442
       localOccs = map (getUnique . getParent . getOccName) 
443
                        . filter ((== this_mod) . name_module)
444
445
446
447
448
449
450
451
452
453
454
455
456
                        . nameSetToList
          where getParent occ = lookupOccEnv parent_map occ `orElse` occ

        -- maps OccNames to their parents in the current module.
        -- e.g. a reference to a constructor must be turned into a reference
        -- to the TyCon for the purposes of calculating dependencies.
       parent_map :: OccEnv OccName
       parent_map = foldr extend emptyOccEnv new_decls
          where extend d env = 
                  extendOccEnvList env [ (b,n) | b <- ifaceDeclSubBndrs d ]
                  where n = ifName d

        -- strongly-connected groups of declarations, in dependency order
457
       groups = stronglyConnCompFromEdgedVertices edges
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

       global_hash_fn = mkHashFun hsc_env eps

        -- how to output Names when generating the data to fingerprint.
        -- Here we want to output the fingerprint for each top-level
        -- Name, whether it comes from the current module or another
        -- module.  In this way, the fingerprint for a declaration will
        -- change if the fingerprint for anything it refers to (transitively)
        -- changes.
       mk_put_name :: (OccEnv (OccName,Fingerprint))
                   -> BinHandle -> Name -> IO  ()
       mk_put_name local_env bh name
          | isWiredInName name  =  putNameLiterally bh name 
           -- wired-in names don't have fingerprints
          | otherwise
473
          = ASSERT2( isExternalName name, ppr name )
dterei's avatar
dterei committed
474
            let hash | nameModule name /= this_mod =  global_hash_fn name
475
476
477
478
                     | otherwise = 
                        snd (lookupOccEnv local_env (getOccName name)
                           `orElse` pprPanic "urk! lookup local fingerprint" 
                                       (ppr name)) -- (undefined,fingerprint0))
479
480
481
482
483
484
485
                -- This panic indicates that we got the dependency
                -- analysis wrong, because we needed a fingerprint for
                -- an entity that wasn't in the environment.  To debug
                -- it, turn the panic into a trace, uncomment the
                -- pprTraces below, run the compile again, and inspect
                -- the output and the generated .hi file with
                -- --show-iface.
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
            in 
            put_ bh hash

        -- take a strongly-connected group of declarations and compute
        -- its fingerprint.

       fingerprint_group :: (OccEnv (OccName,Fingerprint), 
                             [(Fingerprint,IfaceDecl)])
                         -> SCC IfaceDeclABI
                         -> IO (OccEnv (OccName,Fingerprint), 
                                [(Fingerprint,IfaceDecl)])

       fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi)
          = do let hash_fn = mk_put_name local_env
                   decl = abiDecl abi
               -- pprTrace "fingerprinting" (ppr (ifName decl) ) $ do
502
               hash <- computeFingerprint hash_fn abi
503
504
505
506
507
508
509
510
511
512
513
               return (extend_hash_env (hash,decl) local_env,
                       (hash,decl) : decls_w_hashes)

       fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis)
          = do let decls = map abiDecl abis
                   local_env' = foldr extend_hash_env local_env 
                                   (zip (repeat fingerprint0) decls)
                   hash_fn = mk_put_name local_env'
               -- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do
               let stable_abis = sortBy cmp_abiNames abis
                -- put the cycle in a canonical order
514
               hash <- computeFingerprint hash_fn stable_abis
515
516
517
518
519
520
521
522
               let pairs = zip (repeat hash) decls
               return (foldr extend_hash_env local_env pairs,
                       pairs ++ decls_w_hashes)

       extend_hash_env :: (Fingerprint,IfaceDecl)
                       -> OccEnv (OccName,Fingerprint)
                       -> OccEnv (OccName,Fingerprint)
       extend_hash_env (hash,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
523
        where
524
525
526
527
528
529
530
531
532
          decl_name = ifName d
          item = (decl_name, hash)
          env1 = extendOccEnv env0 decl_name item
          add_imp bndr env = extendOccEnv env bndr item
            
   --
   (local_env, decls_w_hashes) <- 
       foldM fingerprint_group (emptyOccEnv, []) groups

533
534
535
536
537
   -- when calculating fingerprints, we always need to use canonical
   -- ordering for lists of things.  In particular, the mi_deps has various
   -- lists of modules and suchlike, so put these all in canonical order:
   let sorted_deps = sortDependencies (mi_deps iface0)

538
   -- the export hash of a module depends on the orphan hashes of the
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
539
   -- orphan modules below us in the dependency tree.  This is the way
540
541
542
543
   -- that changes in orphans get propagated all the way up the
   -- dependency tree.  We only care about orphan modules in the current
   -- package, because changes to orphans outside this package will be
   -- tracked by the usage on the ABI hash of package modules that we import.
544
545
   let orph_mods = filter ((== this_pkg) . modulePackageId)
                   $ dep_orphs sorted_deps
546
547
   dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods

548
   orphan_hash <- computeFingerprint (mk_put_name local_env)
549
                      (map ifDFun orph_insts, orph_rules, fam_insts)
550
551
552

   -- the export list hash doesn't depend on the fingerprints of
   -- the Names it mentions, only the Names themselves, hence putNameLiterally.
553
   export_hash <- computeFingerprint putNameLiterally
554
555
556
                      (mi_exports iface0,
                       orphan_hash,
                       dep_orphan_hashes,
557
                       dep_pkgs (mi_deps iface0),
558
559
                        -- dep_pkgs: see "Package Version Changes" on
                        -- wiki/Commentary/Compiler/RecompilationAvoidance
560
                       mi_trust iface0)
561
                        -- Make sure change of Safe Haskell mode causes recomp.
562
563

   -- put the declarations in a canonical order, sorted by OccName
564
   let sorted_decls = Map.elems $ Map.fromList $
565
                          [(ifName d, e) | e@(_, d) <- decls_w_hashes]
566
567
568
569
570
571
   
   -- the flag hash depends on:
   --   - (some of) dflags
   -- it returns two hashes, one that shouldn't change
   -- the abi hash and one that should
   flag_hash <- fingerprintDynFlags dflags putNameLiterally
572
573
574
575
576
577

   -- the ABI hash depends on:
   --   - decls
   --   - export list
   --   - orphans
   --   - deprecations
578
   --   - vect info
579
   --   - flag abi hash
580
   mod_hash <- computeFingerprint putNameLiterally
581
582
583
                      (map fst sorted_decls,
                       export_hash,
                       orphan_hash,
584
585
                       mi_warns iface0,
                       mi_vect_info iface0)
586
587

   -- The interface hash depends on:
588
589
590
591
   --   - the ABI hash, plus
   --   - usages
   --   - deps
   --   - hpc
592
   iface_hash <- computeFingerprint putNameLiterally
593
594
                      (mod_hash, 
                       mi_usages iface0,
595
                       sorted_deps,
596
597
598
599
600
601
602
603
604
605
                       mi_hpc iface0)

   let
    no_change_at_all = Just iface_hash == mb_old_fingerprint

    final_iface = iface0 {
                mi_mod_hash    = mod_hash,
                mi_iface_hash  = iface_hash,
                mi_exp_hash    = export_hash,
                mi_orphan_hash = orphan_hash,
606
                mi_flag_hash   = flag_hash,
607
608
                mi_orphan      = not (null orph_rules && null orph_insts
                                      && null (ifaceVectInfoVar (mi_vect_info iface0))),
609
610
611
612
                mi_finsts      = not . null $ mi_fam_insts iface0,
                mi_decls       = sorted_decls,
                mi_hash_fn     = lookupOccEnv local_env }
   --
613
   return (final_iface, no_change_at_all)
614

615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
  where
    this_mod = mi_module iface0
    dflags = hsc_dflags hsc_env
    this_pkg = thisPackage dflags
    (non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0)
    (non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0)
        -- ToDo: shouldn't we be splitting fam_insts into orphans and
        -- non-orphans?
    fam_insts = mi_fam_insts iface0
    fix_fn = mi_fix_fn iface0


getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint]
getOrphanHashes hsc_env mods = do
  eps <- hscEPS hsc_env
  let 
    hpt        = hsc_HPT hsc_env
    pit        = eps_PIT eps
    dflags     = hsc_dflags hsc_env
    get_orph_hash mod = 
          case lookupIfaceByModule dflags hpt pit mod of
            Nothing    -> pprPanic "moduleOrphanHash" (ppr mod)
            Just iface -> mi_orphan_hash iface
  --
  return (map get_orph_hash mods)


642
643
644
sortDependencies :: Dependencies -> Dependencies
sortDependencies d
 = Deps { dep_mods   = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d),
645
          dep_pkgs   = sortBy (stablePackageIdCmp `on` fst) (dep_pkgs d),
646
647
          dep_orphs  = sortBy stableModuleCmp (dep_orphs d),
          dep_finsts = sortBy stableModuleCmp (dep_finsts d) }
648
649
650
651
\end{code}


%************************************************************************
dterei's avatar
dterei committed
652
653
654
%*                                                                      *
          The ABI of an IfaceDecl                                                                               
%*                                                                      *
655
656
657
658
659
660
661
662
663
%************************************************************************

Note [The ABI of an IfaceDecl]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The ABI of a declaration consists of:

   (a) the full name of the identifier (inc. module and package,
       because these are used to construct the symbol name by which
       the identifier is known externally).
664

665
666
667
668
669
670
671
672
673
674
675
   (b) the declaration itself, as exposed to clients.  That is, the
       definition of an Id is included in the fingerprint only if
       it is made available as as unfolding in the interface.

   (c) the fixity of the identifier
   (d) for Ids: rules
   (e) for classes: instances, fixity & rules for methods
   (f) for datatypes: instances, fixity & rules for constrs

Items (c)-(f) are not stored in the IfaceDecl, but instead appear
elsewhere in the interface file.  But they are *fingerprinted* with
676
677
the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras,
and fingerprinting that as part of the declaration.
678
679

\begin{code}
680
681
type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras)

682
683
data IfaceDeclExtras 
  = IfaceIdExtras    Fixity [IfaceRule]
684
685

  | IfaceDataExtras  
dterei's avatar
dterei committed
686
687
688
689
       Fixity                   -- Fixity of the tycon itself
       [IfaceInstABI]           -- Local instances of this tycon
                                -- See Note [Orphans] in IfaceSyn
       [(Fixity,[IfaceRule])]   -- For each construcotr, fixity and RULES
690
691

  | IfaceClassExtras 
dterei's avatar
dterei committed
692
693
694
695
696
       Fixity                   -- Fixity of the class itself
       [IfaceInstABI]           -- Local instances of this class *or*
                                --   of its associated data types
                                -- See Note [Orphans] in IfaceSyn
       [(Fixity,[IfaceRule])]   -- For each class method, fixity and RULES
697

698
  | IfaceSynExtras   Fixity
699

700
701
  | IfaceOtherDeclExtras

702
703
704
705
706
707
708
709
710
711
712
713
714
715
abiDecl :: IfaceDeclABI -> IfaceDecl
abiDecl (_, decl, _) = decl

cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering
cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare` 
                         ifName (abiDecl abi2)

freeNamesDeclABI :: IfaceDeclABI -> NameSet
freeNamesDeclABI (_mod, decl, extras) =
  freeNamesIfDecl decl `unionNameSets` freeNamesDeclExtras extras

freeNamesDeclExtras :: IfaceDeclExtras -> NameSet
freeNamesDeclExtras (IfaceIdExtras    _ rules)
  = unionManyNameSets (map freeNamesIfRule rules)
716
717
718
719
freeNamesDeclExtras (IfaceDataExtras  _ insts subs)
  = unionManyNameSets (mkNameSet insts : map freeNamesSub subs)
freeNamesDeclExtras (IfaceClassExtras _ insts subs)
  = unionManyNameSets (mkNameSet insts : map freeNamesSub subs)
720
721
freeNamesDeclExtras (IfaceSynExtras _)
  = emptyNameSet
722
723
724
725
726
727
freeNamesDeclExtras IfaceOtherDeclExtras
  = emptyNameSet

freeNamesSub :: (Fixity,[IfaceRule]) -> NameSet
freeNamesSub (_,rules) = unionManyNameSets (map freeNamesIfRule rules)

728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
instance Outputable IfaceDeclExtras where
  ppr IfaceOtherDeclExtras       = empty
  ppr (IfaceIdExtras  fix rules) = ppr_id_extras fix rules
  ppr (IfaceSynExtras fix)       = ppr fix
  ppr (IfaceDataExtras fix insts stuff)  = vcat [ppr fix, ppr_insts insts,
                                                 ppr_id_extras_s stuff]
  ppr (IfaceClassExtras fix insts stuff) = vcat [ppr fix, ppr_insts insts,
                                                 ppr_id_extras_s stuff]

ppr_insts :: [IfaceInstABI] -> SDoc
ppr_insts _ = ptext (sLit "<insts>")

ppr_id_extras_s :: [(Fixity, [IfaceRule])] -> SDoc
ppr_id_extras_s stuff = vcat [ppr_id_extras f r | (f,r)<- stuff]

ppr_id_extras :: Fixity -> [IfaceRule] -> SDoc
ppr_id_extras fix rules = ppr fix $$ vcat (map ppr rules)

746
-- This instance is used only to compute fingerprints
747
748
749
750
751
752
instance Binary IfaceDeclExtras where
  get _bh = panic "no get for IfaceDeclExtras"
  put_ bh (IfaceIdExtras fix rules) = do
   putByte bh 1; put_ bh fix; put_ bh rules
  put_ bh (IfaceDataExtras fix insts cons) = do
   putByte bh 2; put_ bh fix; put_ bh insts; put_ bh cons
753
754
755
756
  put_ bh (IfaceClassExtras fix insts methods) = do
   putByte bh 3; put_ bh fix; put_ bh insts; put_ bh methods
  put_ bh (IfaceSynExtras fix) = do
   putByte bh 4; put_ bh fix
757
  put_ bh IfaceOtherDeclExtras = do
758
   putByte bh 5
759
760
761
762
763
764
765
766
767
768
769
770
771

declExtras :: (OccName -> Fixity)
           -> OccEnv [IfaceRule]
           -> OccEnv [IfaceInst]
           -> IfaceDecl
           -> IfaceDeclExtras

declExtras fix_fn rule_env inst_env decl
  = case decl of
      IfaceId{} -> IfaceIdExtras (fix_fn n) 
                        (lookupOccEnvL rule_env n)
      IfaceData{ifCons=cons} -> 
                     IfaceDataExtras (fix_fn n)
772
                        (map ifDFun $ lookupOccEnvL inst_env n)
773
                        (map (id_extras . ifConOcc) (visibleIfConDecls cons))
774
      IfaceClass{ifSigs=sigs, ifATs=ats} -> 
775
                     IfaceClassExtras (fix_fn n)
776
                        (map ifDFun $ (concatMap at_extras ats)
777
                                    ++ lookupOccEnvL inst_env n)
dterei's avatar
dterei committed
778
779
                           -- Include instances of the associated types
                           -- as well as instances of the class (Trac #5147)
780
                        [id_extras op | IfaceClassOp op _ _ <- sigs]
781
      IfaceSyn{} -> IfaceSynExtras (fix_fn n)
782
783
784
785
      _other -> IfaceOtherDeclExtras
  where
        n = ifName decl
        id_extras occ = (fix_fn occ, lookupOccEnvL rule_env occ)
786
        at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (ifName decl)
787

788
--
789
790
-- When hashing an instance, we hash only the DFunId, because that
-- depends on all the information about the instance.
791
--
792
type IfaceInstABI = IfExtName
793
794
795
796
797
798
799

lookupOccEnvL :: OccEnv [v] -> OccName -> [v]
lookupOccEnvL env k = lookupOccEnv env k `orElse` []

-- used when we want to fingerprint a structure without depending on the
-- fingerprints of external Names that it refers to.
putNameLiterally :: BinHandle -> Name -> IO ()
800
801
802
putNameLiterally bh name = ASSERT( isExternalName name ) 
  do { put_ bh $! nameModule name
     ; put_ bh $! nameOccName name }
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822

{-
-- for testing: use the md5sum command to generate fingerprints and
-- compare the results against our built-in version.
  fp' <- oldMD5 dflags bh
  if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp')
               else return fp

oldMD5 dflags bh = do
  tmp <- newTempName dflags "bin"
  writeBinMem bh tmp
  tmp2 <- newTempName dflags "md5"
  let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2
  r <- system cmd
  case r of
    ExitFailure _ -> ghcError (PhaseFailed cmd r)
    ExitSuccess -> do
        hash_str <- readFile tmp2
        return $! readHexFingerprint hash_str
-}
823

824
825
826
827
828
829
830
831
832
833
instOrphWarn :: PrintUnqualified -> Instance -> WarnMsg
instOrphWarn unqual inst
  = mkWarnMsg (getSrcSpan inst) unqual $
    hang (ptext (sLit "Warning: orphan instance:")) 2 (pprInstanceHdr inst)

ruleOrphWarn :: PrintUnqualified -> Module -> IfaceRule -> WarnMsg
ruleOrphWarn unqual mod rule
  = mkWarnMsg silly_loc unqual $
    ptext (sLit "Orphan rule:") <+> ppr rule
  where
834
    silly_loc = srcLocSpan (mkSrcLoc (moduleNameFS (moduleName mod)) 1 1)
835
836
    -- We don't have a decent SrcSpan for a Rule, not even the CoreRule
    -- Could readily be fixed by adding a SrcSpan to CoreRule, if we wanted to
837
838

----------------------
839
-- mkOrphMap partitions instance decls or rules into
dterei's avatar
dterei committed
840
841
842
843
844
845
846
847
848
--      (a) an OccEnv for ones that are not orphans, 
--          mapping the local OccName to a list of its decls
--      (b) a list of orphan decls
mkOrphMap :: (decl -> Maybe OccName)    -- (Just occ) for a non-orphan decl, keyed by occ
                                        -- Nothing for an orphan decl
          -> [decl]                     -- Sorted into canonical order
          -> (OccEnv [decl],            -- Non-orphan decls associated with their key;
                                        --      each sublist in canonical order
              [decl])                   -- Orphan decls; in canonical order
849
mkOrphMap get_key decls
850
851
852
  = foldl go (emptyOccEnv, []) decls
  where
    go (non_orphs, orphs) d
dterei's avatar
dterei committed
853
854
855
        | Just occ <- get_key d
        = (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs)
        | otherwise = (non_orphs, d:orphs)
856
857
858
\end{code}


859
%************************************************************************
dterei's avatar
dterei committed
860
%*                                                                      *
861
       Keeping track of what we've slurped, and fingerprints
dterei's avatar
dterei committed
862
%*                                                                      *
863
%************************************************************************
864
865

\begin{code}
GregWeber's avatar
GregWeber committed
866
867
mkUsageInfo :: HscEnv -> Module -> ImportedMods -> NameSet -> [FilePath] -> IO [Usage]
mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
dterei's avatar
dterei committed
868
  = do  { eps <- hscEPS hsc_env
GregWeber's avatar
GregWeber committed
869
    ; mtimes <- mapM getModificationTime dependent_files
dterei's avatar
dterei committed
870
871
872
873
874
875
876
        ; let mod_usages = mk_mod_usage_info (eps_PIT eps) hsc_env this_mod
                                     dir_imp_mods used_names
        ; let usages = mod_usages ++ map to_file_usage (zip dependent_files mtimes)
        ; usages `seqList`  return usages }
         -- seq the list of Usages returned: occasionally these
         -- don't get evaluated for a while and we can end up hanging on to
         -- the entire collection of Ifaces.
GregWeber's avatar
GregWeber committed
877
878
   where
     to_file_usage (f, mtime) = UsageFile { usg_file_path = f, usg_mtime = mtime }
879

GregWeber's avatar
GregWeber committed
880
mk_mod_usage_info :: PackageIfaceTable
881
              -> HscEnv
882
883
              -> Module
              -> ImportedMods
884
885
              -> NameSet
              -> [Usage]
GregWeber's avatar
GregWeber committed
886
mk_mod_usage_info pit hsc_env this_mod direct_imports used_names
887
  = mapCatMaybes mkUsage usage_mods
888
  where
889
    hpt = hsc_HPT hsc_env
Simon Marlow's avatar
Simon Marlow committed
890
    dflags = hsc_dflags hsc_env
891
892
893
    this_pkg = thisPackage dflags

    used_mods    = moduleEnvKeys ent_map
894
    dir_imp_mods = moduleEnvKeys direct_imports
895
896
897
898
    all_mods     = used_mods ++ filter (`notElem` used_mods) dir_imp_mods
    usage_mods   = sortBy stableModuleCmp all_mods
                        -- canonical order is imported, to avoid interface-file
                        -- wobblage.
899

900
    -- ent_map groups together all the things imported and used
901
    -- from a particular module
902
903
    ent_map :: ModuleEnv [OccName]
    ent_map  = foldNameSet add_mv emptyModuleEnv used_names
904
905
     where
      add_mv name mv_map
906
907
908
        | isWiredInName name = mv_map  -- ignore wired-in names
        | otherwise
        = case nameModule_maybe name of
909
             Nothing  -> ASSERT2( isSystemName name, ppr name ) mv_map
dterei's avatar
dterei committed
910
                -- See Note [Internal used_names]
911

912
913
             Just mod -> -- This lambda function is really just a
                         -- specialised (++); originally came about to
914
                         -- avoid quadratic behaviour (trac #2680)
915
                         extendModuleEnvWith (\_ xs -> occ:xs) mv_map mod [occ]
dterei's avatar
dterei committed
916
                where occ = nameOccName name
917
918
    
    -- We want to create a Usage for a home module if 
dterei's avatar
dterei committed
919
920
921
    --  a) we used something from it; has something in used_names
    --  b) we imported it, even if we used nothing from it
    --     (need to recompile if its export list changes: export_fprint)
922
923
    mkUsage :: Module -> Maybe Usage
    mkUsage mod
dterei's avatar
dterei committed
924
925
      | isNothing maybe_iface           -- We can't depend on it if we didn't
                                        -- load its interface.
926
927
928
929
930
931
      || mod == this_mod                -- We don't care about usages of
                                        -- things in *this* module
      = Nothing

      | modulePackageId mod /= this_pkg
      = Just UsagePackageModule{ usg_mod      = mod,
932
933
                                 usg_mod_hash = mod_hash,
                                 usg_safe     = imp_safe }
934
935
936
        -- for package modules, we record the module hash only

      | (null used_occs
dterei's avatar
dterei committed
937
          && isNothing export_hash
938
          && not is_direct_import
dterei's avatar
dterei committed
939
940
          && not finsts_mod)
      = Nothing                 -- Record no usage info
941
942
943
        -- for directly-imported modules, we always want to record a usage
        -- on the orphan hash.  This is what triggers a recompilation if
        -- an orphan is added or removed somewhere below us in the future.
944
    
dterei's avatar
dterei committed
945
      | otherwise       
946
947
      = Just UsageHomeModule { 
                      usg_mod_name = moduleName mod,
948
949
950
951
                      usg_mod_hash = mod_hash,
                      usg_exports  = export_hash,
                      usg_entities = Map.toList ent_hashs,
                      usg_safe     = imp_safe }
952
      where
953
954
955
        maybe_iface  = lookupIfaceByModule dflags hpt pit mod
                -- In one-shot mode, the interfaces for home-package
                -- modules accumulate in the PIT not HPT.  Sigh.
Simon Marlow's avatar
Simon Marlow committed
956

957
        Just iface   = maybe_iface
dterei's avatar
dterei committed
958
        finsts_mod   = mi_finsts    iface
959
960
        hash_env     = mi_hash_fn   iface
        mod_hash     = mi_mod_hash  iface
dterei's avatar
dterei committed
961
        export_hash | depend_on_exports = Just (mi_exp_hash iface)
962
963
964
965
                    | otherwise         = Nothing

        (is_direct_import, imp_safe)
            = case lookupModuleEnv direct_imports mod of
966
967
                Just ((_,_,_,safe):_xs) -> (True, safe)
                Just _                  -> pprPanic "mkUsage: empty direct import" empty
968
                Nothing                 -> (False, safeImplicitImpsReq dflags)
969
                -- Nothing case is for implicit imports like 'System.IO' when 'putStrLn'
970
                -- is used in the source code. We require them to be safe in Safe Haskell
971
972
    
        used_occs = lookupModuleEnv ent_map mod `orElse` []
973

dterei's avatar
dterei committed
974
        -- Making a Map here ensures that (a) we remove duplicates
975
976
        -- when we have usages on several subordinates of a single parent,
        -- and (b) that the usages emerge in a canonical order, which
977
        -- is why we use Map rather than OccEnv: Map works
978
        -- using Ord on the OccNames, which is a lexicographic ordering.
dterei's avatar
dterei committed
979
        ent_hashs :: Map OccName Fingerprint
980
        ent_hashs = Map.fromList (map lookup_occ used_occs)
981
982
        
        lookup_occ occ = 
983
984
985
986
            case hash_env occ of
                Nothing -> pprPanic "mkUsage" (ppr mod <+> ppr occ <+> ppr used_names)
                Just r  -> r

dterei's avatar
dterei committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
        depend_on_exports = is_direct_import
        {- True
              Even if we used 'import M ()', we have to register a
              usage on the export list because we are sensitive to
              changes in orphan instances/rules.
           False
              In GHC 6.8.x we always returned true, and in
              fact it recorded a dependency on *all* the
              modules underneath in the dependency tree.  This
              happens to make orphans work right, but is too
              expensive: it'll read too many interface files.
              The 'isNothing maybe_iface' check above saved us
              from generating many of these usages (at least in
              one-shot mode), but that's even more bogus!
        -}
1002
1003
\end{code}

1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
\begin{code}
mkIfaceAnnotations :: [Annotation] -> [IfaceAnnotation]
mkIfaceAnnotations = map mkIfaceAnnotation

mkIfaceAnnotation :: Annotation -> IfaceAnnotation
mkIfaceAnnotation (Annotation { ann_target = target, ann_value = serialized }) = IfaceAnnotation { 
        ifAnnotatedTarget = fmap nameOccName target,
        ifAnnotatedValue = serialized
    }
\end{code}

1015
\begin{code}
1016
mkIfaceExports :: [AvailInfo] -> [IfaceExport]  -- Sort to make canonical
1017
mkIfaceExports exports
1018
  = sortBy stableAvailCmp (map sort_subs exports)
1019
  where
1020
1021
1022
1023
1024
1025
1026
    sort_subs :: AvailInfo -> AvailInfo
    sort_subs (Avail n) = Avail n
    sort_subs (AvailTC n []) = AvailTC n []
    sort_subs (AvailTC n (m:ms)) 
       | n==m      = AvailTC n (m:sortBy stableNameCmp ms)
       | otherwise = AvailTC n (sortBy stableNameCmp (m:ms))
       -- Maintain the AvailTC Invariant
1027
1028
\end{code}

1029
1030
1031
Note [Orignal module]
~~~~~~~~~~~~~~~~~~~~~
Consider this:
dterei's avatar
dterei committed
1032
1033
        module X where { data family T }
        module Y( T(..) ) where { import X; data instance T Int = MkT Int }
1034
The exported Avail from Y will look like
dterei's avatar
dterei committed
1035
        X.T{X.T, Y.MkT}
1036
1037
1038
1039
1040
1041
1042
1043
That is, in Y, 
  - only MkT is brought into scope by the data instance;
  - but the parent (used for grouping and naming in T(..) exports) is X.T
  - and in this case we export X.T too

In the result of MkIfaceExports, the names are grouped by defining module,
so we may need to split up a single Avail into multiple ones.

1044
1045
1046
Note [Internal used_names]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Most of the used_names are External Names, but we can have Internal
1047
1048
Names too: see Note [Binders in Template Haskell] in Convert, and
Trac #5362 for an example.  Such Names are always
1049
1050
1051
1052
  - Such Names are always for locally-defined things, for which we
    don't gather usage info, so we can just ignore them in ent_map
  - They are always System Names, hence the assert, just as a double check.

1053

1054
%************************************************************************
dterei's avatar
dterei committed
1055
1056
%*                                                                      *
        Load the old interface file for this module (unless
1057
        we have it already), and check whether it is up to date
dterei's avatar
dterei committed
1058
1059
        
%*                                                                      *
1060
1061
1062
%************************************************************************

\begin{code}
1063
1064
1065
1066
1067
1068
-- | Top level function to check if the version of an old interface file
-- is equivalent to the current source file the user asked us to compile.
-- If the same, we can avoid recompilation. We return a tuple where the
-- first element is a bool saying if we should recompile the object file
-- and the second is maybe the interface file, where Nothng means to
-- rebuild the interface file not use the exisitng one.
1069
checkOldIface :: HscEnv
dterei's avatar
dterei committed
1070
              -> ModSummary
1071
              -> SourceModified
dterei's avatar
dterei committed
1072
1073
              -> Maybe ModIface         -- Old interface from compilation manager, if any
              -> IO (RecompileRequired, Maybe ModIface)
1074

1075
checkOldIface hsc_env mod_summary source_modified maybe_iface
1076
1077
1078
  = do  showPass (hsc_dflags hsc_env) $
            "Checking old interface for " ++ (showSDoc $ ppr $ ms_mod mod_summary)
        initIfaceCheck hsc_env $
1079
            check_old_iface hsc_env mod_summary source_modified maybe_iface
1080

1081
check_old_iface :: HscEnv -> ModSummary -> SourceModified -> Maybe ModIface
Ian Lynagh's avatar
Ian Lynagh committed
1082
                -> IfG (Bool, Maybe ModIface)
1083
1084
check_old_iface hsc_env mod_summary src_modified maybe_iface
  = let dflags = hsc_dflags hsc_env
1085
        getIface =
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
            case maybe_iface of
                Just _  -> do
                    traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
                    return maybe_iface
                Nothing -> loadIface

        loadIface = do
             let iface_path = msHiFilePath mod_summary
             read_result <- readIface (ms_mod mod_summary) iface_path False
             case read_result of
                 Failed err -> do
                     traceIf (text "FYI: cannont read old interface file:" $$ nest 4 err)
                     return Nothing
                 Succeeded iface -> do
                     traceIf (text "Read the interface file" <+> text iface_path)
                     return $ Just iface

        src_changed
            | dopt Opt_ForceRecomp (hsc_dflags hsc_env) = True
            | SourceModified <- src_modified = True
            | otherwise = False
1107
    in do
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
        when src_changed $
            traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off")

        case src_changed of
            -- If the source has changed and we're in interactive mode,
            -- avoid reading an interface; just return the one we might
            -- have been supplied with.
            True | not (isObjectTarget $ hscTarget dflags) ->
                return (outOfDate, maybe_iface)

            -- Try and read the old interface for the current module
            -- from the .hi file left from the last time we compiled it
            True -> do
1121
                maybe_iface' <- getIface
1122
                return (outOfDate, maybe_iface')
1123

1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
            False -> do
                maybe_iface' <- getIface
                case maybe_iface' of
                    -- We can't retrieve the iface
                    Nothing    -> return (outOfDate, Nothing)

                    -- We have got the old iface; check its versions
                    -- even in the SourceUnmodifiedAndStable case we
                    -- should check versions because some packages
                    -- might have changed or gone away.
                    Just iface -> checkVersions hsc_env mod_summary iface

-- | @recompileRequired@ is called from the HscMain.   It checks whether
-- a recompilation is required.  It needs access to the persistent state,
-- finder, etc, because it may have to load lots of interface files to
-- check their versions.
1140
type RecompileRequired = Bool
Ian Lynagh's avatar
Ian Lynagh committed
1141
upToDate, outOfDate :: Bool
1142
1143
upToDate  = False  -- Recompile not required
outOfDate = True   -- Recompile required
1144

1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
-- | Check if a module is still the same 'version'.
--
-- This function is called in the recompilation checker after we have
-- determined that the module M being checked hasn't had any changes
-- to its source file since we last compiled M. So at this point in general
-- two things may have changed that mean we should recompile M:
--   * The interface export by a dependency of M has changed.
--   * The compiler flags specified this time for M have changed
--     in a manner that is significant for recompilaiton.
-- We return not just if we should recompile the object file but also
-- if we should rebuild the interface file.
Simon Marlow's avatar
Simon Marlow committed
1156
checkVersions :: HscEnv
1157
              -> ModSummary
dterei's avatar
dterei committed
1158
1159
              -> ModIface       -- Old interface
              -> IfG (RecompileRequired, Maybe ModIface)
1160
checkVersions hsc_env mod_summary iface