PageRenderTime 29ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc-7.0.4/compiler/iface/MkIface.lhs

http://picorec.googlecode.com/
Haskell | 1655 lines | 1130 code | 231 blank | 294 comment | 50 complexity | d4f7b43d6dd0fe2dca9b4d83defbd824 MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. %
  2. % (c) The University of Glasgow 2006-2008
  3. % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
  4. %
  5. \begin{code}
  6. module MkIface (
  7. mkUsedNames,
  8. mkDependencies,
  9. mkIface, -- Build a ModIface from a ModGuts,
  10. -- including computing version information
  11. mkIfaceTc,
  12. writeIfaceFile, -- Write the interface file
  13. checkOldIface, -- See if recompilation is required, by
  14. -- comparing version information
  15. tyThingToIfaceDecl -- Converting things to their Iface equivalents
  16. ) where
  17. \end{code}
  18. -----------------------------------------------
  19. Recompilation checking
  20. -----------------------------------------------
  21. A complete description of how recompilation checking works can be
  22. found in the wiki commentary:
  23. http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
  24. Please read the above page for a top-down description of how this all
  25. works. Notes below cover specific issues related to the implementation.
  26. Basic idea:
  27. * In the mi_usages information in an interface, we record the
  28. fingerprint of each free variable of the module
  29. * In mkIface, we compute the fingerprint of each exported thing A.f.
  30. For each external thing that A.f refers to, we include the fingerprint
  31. of the external reference when computing the fingerprint of A.f. So
  32. if anything that A.f depends on changes, then A.f's fingerprint will
  33. change.
  34. * In checkOldIface we compare the mi_usages for the module with
  35. the actual fingerprint for all each thing recorded in mi_usages
  36. \begin{code}
  37. #include "HsVersions.h"
  38. import IfaceSyn
  39. import LoadIface
  40. import Id
  41. import IdInfo
  42. import Demand
  43. import Annotations
  44. import CoreSyn
  45. import CoreFVs
  46. import Class
  47. import TyCon
  48. import DataCon
  49. import Type
  50. import Coercion
  51. import TcType
  52. import InstEnv
  53. import FamInstEnv
  54. import TcRnMonad
  55. import HsSyn
  56. import HscTypes
  57. import Finder
  58. import DynFlags
  59. import VarEnv
  60. import Var
  61. import Name
  62. import RdrName
  63. import NameEnv
  64. import NameSet
  65. import Module
  66. import BinIface
  67. import ErrUtils
  68. import Digraph
  69. import SrcLoc
  70. import Outputable
  71. import BasicTypes hiding ( SuccessFlag(..) )
  72. import UniqFM
  73. import Unique
  74. import Util hiding ( eqListBy )
  75. import FastString
  76. import Maybes
  77. import ListSetOps
  78. import Binary
  79. import Fingerprint
  80. import Bag
  81. import Control.Monad
  82. import Data.List
  83. import Data.Map (Map)
  84. import qualified Data.Map as Map
  85. import Data.IORef
  86. import System.FilePath
  87. \end{code}
  88. %************************************************************************
  89. %* *
  90. \subsection{Completing an interface}
  91. %* *
  92. %************************************************************************
  93. \begin{code}
  94. mkIface :: HscEnv
  95. -> Maybe Fingerprint -- The old fingerprint, if we have it
  96. -> ModDetails -- The trimmed, tidied interface
  97. -> ModGuts -- Usages, deprecations, etc
  98. -> IO (Messages,
  99. Maybe (ModIface, -- The new one
  100. Bool)) -- True <=> there was an old Iface, and the
  101. -- new one is identical, so no need
  102. -- to write it
  103. mkIface hsc_env maybe_old_fingerprint mod_details
  104. ModGuts{ mg_module = this_mod,
  105. mg_boot = is_boot,
  106. mg_used_names = used_names,
  107. mg_deps = deps,
  108. mg_dir_imps = dir_imp_mods,
  109. mg_rdr_env = rdr_env,
  110. mg_fix_env = fix_env,
  111. mg_warns = warns,
  112. mg_hpc_info = hpc_info }
  113. = mkIface_ hsc_env maybe_old_fingerprint
  114. this_mod is_boot used_names deps rdr_env
  115. fix_env warns hpc_info dir_imp_mods mod_details
  116. -- | make an interface from the results of typechecking only. Useful
  117. -- for non-optimising compilation, or where we aren't generating any
  118. -- object code at all ('HscNothing').
  119. mkIfaceTc :: HscEnv
  120. -> Maybe Fingerprint -- The old fingerprint, if we have it
  121. -> ModDetails -- gotten from mkBootModDetails, probably
  122. -> TcGblEnv -- Usages, deprecations, etc
  123. -> IO (Messages, Maybe (ModIface, Bool))
  124. mkIfaceTc hsc_env maybe_old_fingerprint mod_details
  125. tc_result@TcGblEnv{ tcg_mod = this_mod,
  126. tcg_src = hsc_src,
  127. tcg_imports = imports,
  128. tcg_rdr_env = rdr_env,
  129. tcg_fix_env = fix_env,
  130. tcg_warns = warns,
  131. tcg_hpc = other_hpc_info
  132. }
  133. = do
  134. let used_names = mkUsedNames tc_result
  135. deps <- mkDependencies tc_result
  136. let hpc_info = emptyHpcInfo other_hpc_info
  137. mkIface_ hsc_env maybe_old_fingerprint
  138. this_mod (isHsBoot hsc_src) used_names deps rdr_env
  139. fix_env warns hpc_info (imp_mods imports) mod_details
  140. mkUsedNames :: TcGblEnv -> NameSet
  141. mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
  142. mkDependencies :: TcGblEnv -> IO Dependencies
  143. mkDependencies
  144. TcGblEnv{ tcg_mod = mod,
  145. tcg_imports = imports,
  146. tcg_th_used = th_var
  147. }
  148. = do
  149. th_used <- readIORef th_var -- Whether TH is used
  150. let
  151. dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
  152. -- M.hi-boot can be in the imp_dep_mods, but we must remove
  153. -- it before recording the modules on which this one depends!
  154. -- (We want to retain M.hi-boot in imp_dep_mods so that
  155. -- loadHiBootInterface can see if M's direct imports depend
  156. -- on M.hi-boot, and hence that we should do the hi-boot consistency
  157. -- check.)
  158. pkgs | th_used = insertList thPackageId (imp_dep_pkgs imports)
  159. | otherwise = imp_dep_pkgs imports
  160. return Deps { dep_mods = sortBy (stableModuleNameCmp `on` fst) dep_mods,
  161. dep_pkgs = sortBy stablePackageIdCmp pkgs,
  162. dep_orphs = sortBy stableModuleCmp (imp_orphs imports),
  163. dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
  164. -- sort to get into canonical order
  165. -- NB. remember to use lexicographic ordering
  166. mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> IsBootInterface
  167. -> NameSet -> Dependencies -> GlobalRdrEnv
  168. -> NameEnv FixItem -> Warnings -> HpcInfo
  169. -> ImportedMods
  170. -> ModDetails
  171. -> IO (Messages, Maybe (ModIface, Bool))
  172. mkIface_ hsc_env maybe_old_fingerprint
  173. this_mod is_boot used_names deps rdr_env fix_env src_warns hpc_info
  174. dir_imp_mods
  175. ModDetails{ md_insts = insts,
  176. md_fam_insts = fam_insts,
  177. md_rules = rules,
  178. md_anns = anns,
  179. md_vect_info = vect_info,
  180. md_types = type_env,
  181. md_exports = exports }
  182. -- NB: notice that mkIface does not look at the bindings
  183. -- only at the TypeEnv. The previous Tidy phase has
  184. -- put exactly the info into the TypeEnv that we want
  185. -- to expose in the interface
  186. = do { usages <- mkUsageInfo hsc_env this_mod dir_imp_mods used_names
  187. ; let { entities = typeEnvElts type_env ;
  188. decls = [ tyThingToIfaceDecl entity
  189. | entity <- entities,
  190. let name = getName entity,
  191. not (isImplicitTyThing entity),
  192. -- No implicit Ids and class tycons in the interface file
  193. not (isWiredInName name),
  194. -- Nor wired-in things; the compiler knows about them anyhow
  195. nameIsLocalOrFrom this_mod name ]
  196. -- Sigh: see Note [Root-main Id] in TcRnDriver
  197. ; fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
  198. ; warns = src_warns
  199. ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
  200. ; iface_insts = map instanceToIfaceInst insts
  201. ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
  202. ; iface_vect_info = flattenVectInfo vect_info
  203. ; intermediate_iface = ModIface {
  204. mi_module = this_mod,
  205. mi_boot = is_boot,
  206. mi_deps = deps,
  207. mi_usages = usages,
  208. mi_exports = mkIfaceExports exports,
  209. -- Sort these lexicographically, so that
  210. -- the result is stable across compilations
  211. mi_insts = sortLe le_inst iface_insts,
  212. mi_fam_insts= sortLe le_fam_inst iface_fam_insts,
  213. mi_rules = sortLe le_rule iface_rules,
  214. mi_vect_info = iface_vect_info,
  215. mi_fixities = fixities,
  216. mi_warns = warns,
  217. mi_anns = mkIfaceAnnotations anns,
  218. mi_globals = Just rdr_env,
  219. -- Left out deliberately: filled in by addVersionInfo
  220. mi_iface_hash = fingerprint0,
  221. mi_mod_hash = fingerprint0,
  222. mi_exp_hash = fingerprint0,
  223. mi_orphan_hash = fingerprint0,
  224. mi_orphan = False, -- Always set by addVersionInfo, but
  225. -- it's a strict field, so we can't omit it.
  226. mi_finsts = False, -- Ditto
  227. mi_decls = deliberatelyOmitted "decls",
  228. mi_hash_fn = deliberatelyOmitted "hash_fn",
  229. mi_hpc = isHpcUsed hpc_info,
  230. -- And build the cached values
  231. mi_warn_fn = mkIfaceWarnCache warns,
  232. mi_fix_fn = mkIfaceFixCache fixities }
  233. }
  234. ; (new_iface, no_change_at_all)
  235. <- {-# SCC "versioninfo" #-}
  236. addFingerprints hsc_env maybe_old_fingerprint
  237. intermediate_iface decls
  238. -- Warn about orphans
  239. ; let warn_orphs = dopt Opt_WarnOrphans dflags
  240. warn_auto_orphs = dopt Opt_WarnAutoOrphans dflags
  241. orph_warnings --- Laziness means no work done unless -fwarn-orphans
  242. | warn_orphs || warn_auto_orphs = rule_warns `unionBags` inst_warns
  243. | otherwise = emptyBag
  244. errs_and_warns = (orph_warnings, emptyBag)
  245. unqual = mkPrintUnqualified dflags rdr_env
  246. inst_warns = listToBag [ instOrphWarn unqual d
  247. | (d,i) <- insts `zip` iface_insts
  248. , isNothing (ifInstOrph i) ]
  249. rule_warns = listToBag [ ruleOrphWarn unqual this_mod r
  250. | r <- iface_rules
  251. , isNothing (ifRuleOrph r)
  252. , if ifRuleAuto r then warn_auto_orphs
  253. else warn_orphs ]
  254. ; if errorsFound dflags errs_and_warns
  255. then return ( errs_and_warns, Nothing )
  256. else do {
  257. -- XXX ; when (dopt Opt_D_dump_hi_diffs dflags) (printDump pp_diffs)
  258. -- Debug printing
  259. ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
  260. (pprModIface new_iface)
  261. -- bug #1617: on reload we weren't updating the PrintUnqualified
  262. -- correctly. This stems from the fact that the interface had
  263. -- not changed, so addVersionInfo returns the old ModIface
  264. -- with the old GlobalRdrEnv (mi_globals).
  265. ; let final_iface = new_iface{ mi_globals = Just rdr_env }
  266. ; return (errs_and_warns, Just (final_iface, no_change_at_all)) }}
  267. where
  268. r1 `le_rule` r2 = ifRuleName r1 <= ifRuleName r2
  269. i1 `le_inst` i2 = ifDFun i1 `le_occ` ifDFun i2
  270. i1 `le_fam_inst` i2 = ifFamInstTcName i1 `le_occ` ifFamInstTcName i2
  271. le_occ :: Name -> Name -> Bool
  272. -- Compare lexicographically by OccName, *not* by unique, because
  273. -- the latter is not stable across compilations
  274. le_occ n1 n2 = nameOccName n1 <= nameOccName n2
  275. dflags = hsc_dflags hsc_env
  276. deliberatelyOmitted :: String -> a
  277. deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
  278. ifFamInstTcName = ifaceTyConName . ifFamInstTyCon
  279. flattenVectInfo (VectInfo { vectInfoVar = vVar
  280. , vectInfoTyCon = vTyCon
  281. }) =
  282. IfaceVectInfo {
  283. ifaceVectInfoVar = [ Var.varName v
  284. | (v, _) <- varEnvElts vVar],
  285. ifaceVectInfoTyCon = [ tyConName t
  286. | (t, t_v) <- nameEnvElts vTyCon
  287. , t /= t_v],
  288. ifaceVectInfoTyConReuse = [ tyConName t
  289. | (t, t_v) <- nameEnvElts vTyCon
  290. , t == t_v]
  291. }
  292. -----------------------------
  293. writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
  294. writeIfaceFile dflags location new_iface
  295. = do createDirectoryHierarchy (takeDirectory hi_file_path)
  296. writeBinIface dflags hi_file_path new_iface
  297. where hi_file_path = ml_hi_file location
  298. -- -----------------------------------------------------------------------------
  299. -- Look up parents and versions of Names
  300. -- This is like a global version of the mi_hash_fn field in each ModIface.
  301. -- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get
  302. -- the parent and version info.
  303. mkHashFun
  304. :: HscEnv -- needed to look up versions
  305. -> ExternalPackageState -- ditto
  306. -> (Name -> Fingerprint)
  307. mkHashFun hsc_env eps
  308. = \name ->
  309. let
  310. mod = ASSERT2( isExternalName name, ppr name ) nameModule name
  311. occ = nameOccName name
  312. iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
  313. pprPanic "lookupVers2" (ppr mod <+> ppr occ)
  314. in
  315. snd (mi_hash_fn iface occ `orElse`
  316. pprPanic "lookupVers1" (ppr mod <+> ppr occ))
  317. where
  318. hpt = hsc_HPT hsc_env
  319. pit = eps_PIT eps
  320. -- ---------------------------------------------------------------------------
  321. -- Compute fingerprints for the interface
  322. addFingerprints
  323. :: HscEnv
  324. -> Maybe Fingerprint -- the old fingerprint, if any
  325. -> ModIface -- The new interface (lacking decls)
  326. -> [IfaceDecl] -- The new decls
  327. -> IO (ModIface, -- Updated interface
  328. Bool) -- True <=> no changes at all;
  329. -- no need to write Iface
  330. addFingerprints hsc_env mb_old_fingerprint iface0 new_decls
  331. = do
  332. eps <- hscEPS hsc_env
  333. let
  334. -- The ABI of a declaration represents everything that is made
  335. -- visible about the declaration that a client can depend on.
  336. -- see IfaceDeclABI below.
  337. declABI :: IfaceDecl -> IfaceDeclABI
  338. declABI decl = (this_mod, decl, extras)
  339. where extras = declExtras fix_fn non_orph_rules non_orph_insts decl
  340. edges :: [(IfaceDeclABI, Unique, [Unique])]
  341. edges = [ (abi, getUnique (ifName decl), out)
  342. | decl <- new_decls
  343. , let abi = declABI decl
  344. , let out = localOccs $ freeNamesDeclABI abi
  345. ]
  346. name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n
  347. localOccs = map (getUnique . getParent . getOccName)
  348. . filter ((== this_mod) . name_module)
  349. . nameSetToList
  350. where getParent occ = lookupOccEnv parent_map occ `orElse` occ
  351. -- maps OccNames to their parents in the current module.
  352. -- e.g. a reference to a constructor must be turned into a reference
  353. -- to the TyCon for the purposes of calculating dependencies.
  354. parent_map :: OccEnv OccName
  355. parent_map = foldr extend emptyOccEnv new_decls
  356. where extend d env =
  357. extendOccEnvList env [ (b,n) | b <- ifaceDeclSubBndrs d ]
  358. where n = ifName d
  359. -- strongly-connected groups of declarations, in dependency order
  360. groups = stronglyConnCompFromEdgedVertices edges
  361. global_hash_fn = mkHashFun hsc_env eps
  362. -- how to output Names when generating the data to fingerprint.
  363. -- Here we want to output the fingerprint for each top-level
  364. -- Name, whether it comes from the current module or another
  365. -- module. In this way, the fingerprint for a declaration will
  366. -- change if the fingerprint for anything it refers to (transitively)
  367. -- changes.
  368. mk_put_name :: (OccEnv (OccName,Fingerprint))
  369. -> BinHandle -> Name -> IO ()
  370. mk_put_name local_env bh name
  371. | isWiredInName name = putNameLiterally bh name
  372. -- wired-in names don't have fingerprints
  373. | otherwise
  374. = ASSERT2( isExternalName name, ppr name )
  375. let hash | nameModule name /= this_mod = global_hash_fn name
  376. | otherwise =
  377. snd (lookupOccEnv local_env (getOccName name)
  378. `orElse` pprPanic "urk! lookup local fingerprint"
  379. (ppr name)) -- (undefined,fingerprint0))
  380. -- This panic indicates that we got the dependency
  381. -- analysis wrong, because we needed a fingerprint for
  382. -- an entity that wasn't in the environment. To debug
  383. -- it, turn the panic into a trace, uncomment the
  384. -- pprTraces below, run the compile again, and inspect
  385. -- the output and the generated .hi file with
  386. -- --show-iface.
  387. in
  388. put_ bh hash
  389. -- take a strongly-connected group of declarations and compute
  390. -- its fingerprint.
  391. fingerprint_group :: (OccEnv (OccName,Fingerprint),
  392. [(Fingerprint,IfaceDecl)])
  393. -> SCC IfaceDeclABI
  394. -> IO (OccEnv (OccName,Fingerprint),
  395. [(Fingerprint,IfaceDecl)])
  396. fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi)
  397. = do let hash_fn = mk_put_name local_env
  398. decl = abiDecl abi
  399. -- pprTrace "fingerprinting" (ppr (ifName decl) ) $ do
  400. hash <- computeFingerprint dflags hash_fn abi
  401. return (extend_hash_env (hash,decl) local_env,
  402. (hash,decl) : decls_w_hashes)
  403. fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis)
  404. = do let decls = map abiDecl abis
  405. local_env' = foldr extend_hash_env local_env
  406. (zip (repeat fingerprint0) decls)
  407. hash_fn = mk_put_name local_env'
  408. -- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do
  409. let stable_abis = sortBy cmp_abiNames abis
  410. -- put the cycle in a canonical order
  411. hash <- computeFingerprint dflags hash_fn stable_abis
  412. let pairs = zip (repeat hash) decls
  413. return (foldr extend_hash_env local_env pairs,
  414. pairs ++ decls_w_hashes)
  415. extend_hash_env :: (Fingerprint,IfaceDecl)
  416. -> OccEnv (OccName,Fingerprint)
  417. -> OccEnv (OccName,Fingerprint)
  418. extend_hash_env (hash,d) env0 = foldr add_imp env1 (ifaceDeclSubBndrs d)
  419. where
  420. decl_name = ifName d
  421. item = (decl_name, hash)
  422. env1 = extendOccEnv env0 decl_name item
  423. add_imp bndr env = extendOccEnv env bndr item
  424. --
  425. (local_env, decls_w_hashes) <-
  426. foldM fingerprint_group (emptyOccEnv, []) groups
  427. -- when calculating fingerprints, we always need to use canonical
  428. -- ordering for lists of things. In particular, the mi_deps has various
  429. -- lists of modules and suchlike, so put these all in canonical order:
  430. let sorted_deps = sortDependencies (mi_deps iface0)
  431. -- the export hash of a module depends on the orphan hashes of the
  432. -- orphan modules below us in the dependency tree. This is the way
  433. -- that changes in orphans get propagated all the way up the
  434. -- dependency tree. We only care about orphan modules in the current
  435. -- package, because changes to orphans outside this package will be
  436. -- tracked by the usage on the ABI hash of package modules that we import.
  437. let orph_mods = filter ((== this_pkg) . modulePackageId)
  438. $ dep_orphs sorted_deps
  439. dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods
  440. orphan_hash <- computeFingerprint dflags (mk_put_name local_env)
  441. (map ifDFun orph_insts, orph_rules, fam_insts)
  442. -- the export list hash doesn't depend on the fingerprints of
  443. -- the Names it mentions, only the Names themselves, hence putNameLiterally.
  444. export_hash <- computeFingerprint dflags putNameLiterally
  445. (mi_exports iface0,
  446. orphan_hash,
  447. dep_orphan_hashes,
  448. dep_pkgs (mi_deps iface0))
  449. -- dep_pkgs: see "Package Version Changes" on
  450. -- wiki/Commentary/Compiler/RecompilationAvoidance
  451. -- put the declarations in a canonical order, sorted by OccName
  452. let sorted_decls = Map.elems $ Map.fromList $
  453. [(ifName d, e) | e@(_, d) <- decls_w_hashes]
  454. -- the ABI hash depends on:
  455. -- - decls
  456. -- - export list
  457. -- - orphans
  458. -- - deprecations
  459. -- - XXX vect info?
  460. mod_hash <- computeFingerprint dflags putNameLiterally
  461. (map fst sorted_decls,
  462. export_hash,
  463. orphan_hash,
  464. mi_warns iface0)
  465. -- The interface hash depends on:
  466. -- - the ABI hash, plus
  467. -- - usages
  468. -- - deps
  469. -- - hpc
  470. iface_hash <- computeFingerprint dflags putNameLiterally
  471. (mod_hash,
  472. mi_usages iface0,
  473. sorted_deps,
  474. mi_hpc iface0)
  475. let
  476. no_change_at_all = Just iface_hash == mb_old_fingerprint
  477. final_iface = iface0 {
  478. mi_mod_hash = mod_hash,
  479. mi_iface_hash = iface_hash,
  480. mi_exp_hash = export_hash,
  481. mi_orphan_hash = orphan_hash,
  482. mi_orphan = not (null orph_rules && null orph_insts),
  483. mi_finsts = not . null $ mi_fam_insts iface0,
  484. mi_decls = sorted_decls,
  485. mi_hash_fn = lookupOccEnv local_env }
  486. --
  487. return (final_iface, no_change_at_all)
  488. where
  489. this_mod = mi_module iface0
  490. dflags = hsc_dflags hsc_env
  491. this_pkg = thisPackage dflags
  492. (non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0)
  493. (non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0)
  494. -- ToDo: shouldn't we be splitting fam_insts into orphans and
  495. -- non-orphans?
  496. fam_insts = mi_fam_insts iface0
  497. fix_fn = mi_fix_fn iface0
  498. getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint]
  499. getOrphanHashes hsc_env mods = do
  500. eps <- hscEPS hsc_env
  501. let
  502. hpt = hsc_HPT hsc_env
  503. pit = eps_PIT eps
  504. dflags = hsc_dflags hsc_env
  505. get_orph_hash mod =
  506. case lookupIfaceByModule dflags hpt pit mod of
  507. Nothing -> pprPanic "moduleOrphanHash" (ppr mod)
  508. Just iface -> mi_orphan_hash iface
  509. --
  510. return (map get_orph_hash mods)
  511. sortDependencies :: Dependencies -> Dependencies
  512. sortDependencies d
  513. = Deps { dep_mods = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d),
  514. dep_pkgs = sortBy (compare `on` packageIdFS) (dep_pkgs d),
  515. dep_orphs = sortBy stableModuleCmp (dep_orphs d),
  516. dep_finsts = sortBy stableModuleCmp (dep_finsts d) }
  517. \end{code}
  518. %************************************************************************
  519. %* *
  520. The ABI of an IfaceDecl
  521. %* *
  522. %************************************************************************
  523. Note [The ABI of an IfaceDecl]
  524. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  525. The ABI of a declaration consists of:
  526. (a) the full name of the identifier (inc. module and package,
  527. because these are used to construct the symbol name by which
  528. the identifier is known externally).
  529. (b) the declaration itself, as exposed to clients. That is, the
  530. definition of an Id is included in the fingerprint only if
  531. it is made available as as unfolding in the interface.
  532. (c) the fixity of the identifier
  533. (d) for Ids: rules
  534. (e) for classes: instances, fixity & rules for methods
  535. (f) for datatypes: instances, fixity & rules for constrs
  536. Items (c)-(f) are not stored in the IfaceDecl, but instead appear
  537. elsewhere in the interface file. But they are *fingerprinted* with
  538. the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras,
  539. and fingerprinting that as part of the declaration.
  540. \begin{code}
  541. type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras)
  542. data IfaceDeclExtras
  543. = IfaceIdExtras Fixity [IfaceRule]
  544. | IfaceDataExtras Fixity [IfaceInstABI] [(Fixity,[IfaceRule])]
  545. | IfaceClassExtras Fixity [IfaceInstABI] [(Fixity,[IfaceRule])]
  546. | IfaceSynExtras Fixity
  547. | IfaceOtherDeclExtras
  548. abiDecl :: IfaceDeclABI -> IfaceDecl
  549. abiDecl (_, decl, _) = decl
  550. cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering
  551. cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare`
  552. ifName (abiDecl abi2)
  553. freeNamesDeclABI :: IfaceDeclABI -> NameSet
  554. freeNamesDeclABI (_mod, decl, extras) =
  555. freeNamesIfDecl decl `unionNameSets` freeNamesDeclExtras extras
  556. freeNamesDeclExtras :: IfaceDeclExtras -> NameSet
  557. freeNamesDeclExtras (IfaceIdExtras _ rules)
  558. = unionManyNameSets (map freeNamesIfRule rules)
  559. freeNamesDeclExtras (IfaceDataExtras _ insts subs)
  560. = unionManyNameSets (mkNameSet insts : map freeNamesSub subs)
  561. freeNamesDeclExtras (IfaceClassExtras _ insts subs)
  562. = unionManyNameSets (mkNameSet insts : map freeNamesSub subs)
  563. freeNamesDeclExtras (IfaceSynExtras _)
  564. = emptyNameSet
  565. freeNamesDeclExtras IfaceOtherDeclExtras
  566. = emptyNameSet
  567. freeNamesSub :: (Fixity,[IfaceRule]) -> NameSet
  568. freeNamesSub (_,rules) = unionManyNameSets (map freeNamesIfRule rules)
  569. instance Outputable IfaceDeclExtras where
  570. ppr IfaceOtherDeclExtras = empty
  571. ppr (IfaceIdExtras fix rules) = ppr_id_extras fix rules
  572. ppr (IfaceSynExtras fix) = ppr fix
  573. ppr (IfaceDataExtras fix insts stuff) = vcat [ppr fix, ppr_insts insts,
  574. ppr_id_extras_s stuff]
  575. ppr (IfaceClassExtras fix insts stuff) = vcat [ppr fix, ppr_insts insts,
  576. ppr_id_extras_s stuff]
  577. ppr_insts :: [IfaceInstABI] -> SDoc
  578. ppr_insts _ = ptext (sLit "<insts>")
  579. ppr_id_extras_s :: [(Fixity, [IfaceRule])] -> SDoc
  580. ppr_id_extras_s stuff = vcat [ppr_id_extras f r | (f,r)<- stuff]
  581. ppr_id_extras :: Fixity -> [IfaceRule] -> SDoc
  582. ppr_id_extras fix rules = ppr fix $$ vcat (map ppr rules)
  583. -- This instance is used only to compute fingerprints
  584. instance Binary IfaceDeclExtras where
  585. get _bh = panic "no get for IfaceDeclExtras"
  586. put_ bh (IfaceIdExtras fix rules) = do
  587. putByte bh 1; put_ bh fix; put_ bh rules
  588. put_ bh (IfaceDataExtras fix insts cons) = do
  589. putByte bh 2; put_ bh fix; put_ bh insts; put_ bh cons
  590. put_ bh (IfaceClassExtras fix insts methods) = do
  591. putByte bh 3; put_ bh fix; put_ bh insts; put_ bh methods
  592. put_ bh (IfaceSynExtras fix) = do
  593. putByte bh 4; put_ bh fix
  594. put_ bh IfaceOtherDeclExtras = do
  595. putByte bh 5
  596. declExtras :: (OccName -> Fixity)
  597. -> OccEnv [IfaceRule]
  598. -> OccEnv [IfaceInst]
  599. -> IfaceDecl
  600. -> IfaceDeclExtras
  601. declExtras fix_fn rule_env inst_env decl
  602. = case decl of
  603. IfaceId{} -> IfaceIdExtras (fix_fn n)
  604. (lookupOccEnvL rule_env n)
  605. IfaceData{ifCons=cons} ->
  606. IfaceDataExtras (fix_fn n)
  607. (map ifDFun $ lookupOccEnvL inst_env n)
  608. (map (id_extras . ifConOcc) (visibleIfConDecls cons))
  609. IfaceClass{ifSigs=sigs} ->
  610. IfaceClassExtras (fix_fn n)
  611. (map ifDFun $ lookupOccEnvL inst_env n)
  612. [id_extras op | IfaceClassOp op _ _ <- sigs]
  613. IfaceSyn{} -> IfaceSynExtras (fix_fn n)
  614. _other -> IfaceOtherDeclExtras
  615. where
  616. n = ifName decl
  617. id_extras occ = (fix_fn occ, lookupOccEnvL rule_env occ)
  618. --
  619. -- When hashing an instance, we hash only the DFunId, because that
  620. -- depends on all the information about the instance.
  621. --
  622. type IfaceInstABI = IfExtName
  623. lookupOccEnvL :: OccEnv [v] -> OccName -> [v]
  624. lookupOccEnvL env k = lookupOccEnv env k `orElse` []
  625. -- used when we want to fingerprint a structure without depending on the
  626. -- fingerprints of external Names that it refers to.
  627. putNameLiterally :: BinHandle -> Name -> IO ()
  628. putNameLiterally bh name = ASSERT( isExternalName name )
  629. do { put_ bh $! nameModule name
  630. ; put_ bh $! nameOccName name }
  631. computeFingerprint :: Binary a
  632. => DynFlags
  633. -> (BinHandle -> Name -> IO ())
  634. -> a
  635. -> IO Fingerprint
  636. computeFingerprint _dflags put_name a = do
  637. bh <- openBinMem (3*1024) -- just less than a block
  638. ud <- newWriteState put_name putFS
  639. bh <- return $ setUserData bh ud
  640. put_ bh a
  641. fingerprintBinMem bh
  642. {-
  643. -- for testing: use the md5sum command to generate fingerprints and
  644. -- compare the results against our built-in version.
  645. fp' <- oldMD5 dflags bh
  646. if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp')
  647. else return fp
  648. oldMD5 dflags bh = do
  649. tmp <- newTempName dflags "bin"
  650. writeBinMem bh tmp
  651. tmp2 <- newTempName dflags "md5"
  652. let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2
  653. r <- system cmd
  654. case r of
  655. ExitFailure _ -> ghcError (PhaseFailed cmd r)
  656. ExitSuccess -> do
  657. hash_str <- readFile tmp2
  658. return $! readHexFingerprint hash_str
  659. -}
  660. instOrphWarn :: PrintUnqualified -> Instance -> WarnMsg
  661. instOrphWarn unqual inst
  662. = mkWarnMsg (getSrcSpan inst) unqual $
  663. hang (ptext (sLit "Warning: orphan instance:")) 2 (pprInstanceHdr inst)
  664. ruleOrphWarn :: PrintUnqualified -> Module -> IfaceRule -> WarnMsg
  665. ruleOrphWarn unqual mod rule
  666. = mkWarnMsg silly_loc unqual $
  667. ptext (sLit "Orphan rule:") <+> ppr rule
  668. where
  669. silly_loc = srcLocSpan (mkSrcLoc (moduleNameFS (moduleName mod)) 1 1)
  670. -- We don't have a decent SrcSpan for a Rule, not even the CoreRule
  671. -- Could readily be fixed by adding a SrcSpan to CoreRule, if we wanted to
  672. ----------------------
  673. -- mkOrphMap partitions instance decls or rules into
  674. -- (a) an OccEnv for ones that are not orphans,
  675. -- mapping the local OccName to a list of its decls
  676. -- (b) a list of orphan decls
  677. mkOrphMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
  678. -- Nothing for an orphan decl
  679. -> [decl] -- Sorted into canonical order
  680. -> (OccEnv [decl], -- Non-orphan decls associated with their key;
  681. -- each sublist in canonical order
  682. [decl]) -- Orphan decls; in canonical order
  683. mkOrphMap get_key decls
  684. = foldl go (emptyOccEnv, []) decls
  685. where
  686. go (non_orphs, orphs) d
  687. | Just occ <- get_key d
  688. = (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs)
  689. | otherwise = (non_orphs, d:orphs)
  690. \end{code}
  691. %************************************************************************
  692. %* *
  693. Keeping track of what we've slurped, and fingerprints
  694. %* *
  695. %************************************************************************
  696. \begin{code}
  697. mkUsageInfo :: HscEnv -> Module -> ImportedMods -> NameSet -> IO [Usage]
  698. mkUsageInfo hsc_env this_mod dir_imp_mods used_names
  699. = do { eps <- hscEPS hsc_env
  700. ; let usages = mk_usage_info (eps_PIT eps) hsc_env this_mod
  701. dir_imp_mods used_names
  702. ; usages `seqList` return usages }
  703. -- seq the list of Usages returned: occasionally these
  704. -- don't get evaluated for a while and we can end up hanging on to
  705. -- the entire collection of Ifaces.
  706. mk_usage_info :: PackageIfaceTable
  707. -> HscEnv
  708. -> Module
  709. -> ImportedMods
  710. -> NameSet
  711. -> [Usage]
  712. mk_usage_info pit hsc_env this_mod direct_imports used_names
  713. = mapCatMaybes mkUsage usage_mods
  714. where
  715. hpt = hsc_HPT hsc_env
  716. dflags = hsc_dflags hsc_env
  717. this_pkg = thisPackage dflags
  718. used_mods = moduleEnvKeys ent_map
  719. dir_imp_mods = (moduleEnvKeys direct_imports)
  720. all_mods = used_mods ++ filter (`notElem` used_mods) dir_imp_mods
  721. usage_mods = sortBy stableModuleCmp all_mods
  722. -- canonical order is imported, to avoid interface-file
  723. -- wobblage.
  724. -- ent_map groups together all the things imported and used
  725. -- from a particular module
  726. ent_map :: ModuleEnv [OccName]
  727. ent_map = foldNameSet add_mv emptyModuleEnv used_names
  728. where
  729. add_mv name mv_map
  730. | isWiredInName name = mv_map -- ignore wired-in names
  731. | otherwise
  732. = case nameModule_maybe name of
  733. Nothing -> pprPanic "mkUsageInfo: internal name?" (ppr name)
  734. Just mod -> -- This lambda function is really just a
  735. -- specialised (++); originally came about to
  736. -- avoid quadratic behaviour (trac #2680)
  737. extendModuleEnvWith (\_ xs -> occ:xs) mv_map mod [occ]
  738. where occ = nameOccName name
  739. -- We want to create a Usage for a home module if
  740. -- a) we used something from it; has something in used_names
  741. -- b) we imported it, even if we used nothing from it
  742. -- (need to recompile if its export list changes: export_fprint)
  743. mkUsage :: Module -> Maybe Usage
  744. mkUsage mod
  745. | isNothing maybe_iface -- We can't depend on it if we didn't
  746. -- load its interface.
  747. || mod == this_mod -- We don't care about usages of
  748. -- things in *this* module
  749. = Nothing
  750. | modulePackageId mod /= this_pkg
  751. = Just UsagePackageModule{ usg_mod = mod,
  752. usg_mod_hash = mod_hash }
  753. -- for package modules, we record the module hash only
  754. | (null used_occs
  755. && isNothing export_hash
  756. && not is_direct_import
  757. && not finsts_mod)
  758. = Nothing -- Record no usage info
  759. -- for directly-imported modules, we always want to record a usage
  760. -- on the orphan hash. This is what triggers a recompilation if
  761. -- an orphan is added or removed somewhere below us in the future.
  762. | otherwise
  763. = Just UsageHomeModule {
  764. usg_mod_name = moduleName mod,
  765. usg_mod_hash = mod_hash,
  766. usg_exports = export_hash,
  767. usg_entities = Map.toList ent_hashs }
  768. where
  769. maybe_iface = lookupIfaceByModule dflags hpt pit mod
  770. -- In one-shot mode, the interfaces for home-package
  771. -- modules accumulate in the PIT not HPT. Sigh.
  772. is_direct_import = mod `elemModuleEnv` direct_imports
  773. Just iface = maybe_iface
  774. finsts_mod = mi_finsts iface
  775. hash_env = mi_hash_fn iface
  776. mod_hash = mi_mod_hash iface
  777. export_hash | depend_on_exports mod = Just (mi_exp_hash iface)
  778. | otherwise = Nothing
  779. used_occs = lookupModuleEnv ent_map mod `orElse` []
  780. -- Making a Map here ensures that (a) we remove duplicates
  781. -- when we have usages on several subordinates of a single parent,
  782. -- and (b) that the usages emerge in a canonical order, which
  783. -- is why we use Map rather than OccEnv: Map works
  784. -- using Ord on the OccNames, which is a lexicographic ordering.
  785. ent_hashs :: Map OccName Fingerprint
  786. ent_hashs = Map.fromList (map lookup_occ used_occs)
  787. lookup_occ occ =
  788. case hash_env occ of
  789. Nothing -> pprPanic "mkUsage" (ppr mod <+> ppr occ <+> ppr used_names)
  790. Just r -> r
  791. depend_on_exports mod =
  792. case lookupModuleEnv direct_imports mod of
  793. Just _ -> True
  794. -- Even if we used 'import M ()', we have to register a
  795. -- usage on the export list because we are sensitive to
  796. -- changes in orphan instances/rules.
  797. Nothing -> False
  798. -- In GHC 6.8.x the above line read "True", and in
  799. -- fact it recorded a dependency on *all* the
  800. -- modules underneath in the dependency tree. This
  801. -- happens to make orphans work right, but is too
  802. -- expensive: it'll read too many interface files.
  803. -- The 'isNothing maybe_iface' check above saved us
  804. -- from generating many of these usages (at least in
  805. -- one-shot mode), but that's even more bogus!
  806. \end{code}
  807. \begin{code}
  808. mkIfaceAnnotations :: [Annotation] -> [IfaceAnnotation]
  809. mkIfaceAnnotations = map mkIfaceAnnotation
  810. mkIfaceAnnotation :: Annotation -> IfaceAnnotation
  811. mkIfaceAnnotation (Annotation { ann_target = target, ann_value = serialized }) = IfaceAnnotation {
  812. ifAnnotatedTarget = fmap nameOccName target,
  813. ifAnnotatedValue = serialized
  814. }
  815. \end{code}
  816. \begin{code}
  817. mkIfaceExports :: [AvailInfo]
  818. -> [(Module, [GenAvailInfo OccName])]
  819. -- Group by module and sort by occurrence
  820. mkIfaceExports exports
  821. = [ (mod, Map.elems avails)
  822. | (mod, avails) <- sortBy (stableModuleCmp `on` fst)
  823. (moduleEnvToList groupFM)
  824. -- NB. the Map.toList is in a random order,
  825. -- because Ord Module is not a predictable
  826. -- ordering. Hence we perform a final sort
  827. -- using the stable Module ordering.
  828. ]
  829. where
  830. -- Group by the module where the exported entities are defined
  831. -- (which may not be the same for all Names in an Avail)
  832. -- Deliberately use Map rather than UniqFM so we
  833. -- get a canonical ordering
  834. groupFM :: ModuleEnv (Map FastString (GenAvailInfo OccName))
  835. groupFM = foldl add emptyModuleEnv exports
  836. add_one :: ModuleEnv (Map FastString (GenAvailInfo OccName))
  837. -> Module -> GenAvailInfo OccName
  838. -> ModuleEnv (Map FastString (GenAvailInfo OccName))
  839. add_one env mod avail
  840. -- XXX Is there a need to flip Map.union here?
  841. = extendModuleEnvWith (flip Map.union) env mod
  842. (Map.singleton (occNameFS (availName avail)) avail)
  843. -- NB: we should not get T(X) and T(Y) in the export list
  844. -- else the Map.union will simply discard one! They
  845. -- should have been combined by now.
  846. add env (Avail n)
  847. = ASSERT( isExternalName n )
  848. add_one env (nameModule n) (Avail (nameOccName n))
  849. add env (AvailTC tc ns)
  850. = ASSERT( all isExternalName ns )
  851. foldl add_for_mod env mods
  852. where
  853. tc_occ = nameOccName tc
  854. mods = nub (map nameModule ns)
  855. -- Usually just one, but see Note [Original module]
  856. add_for_mod env mod
  857. = add_one env mod (AvailTC tc_occ (sort names_from_mod))
  858. -- NB. sort the children, we need a canonical order
  859. where
  860. names_from_mod = [nameOccName n | n <- ns, nameModule n == mod]
  861. \end{code}
  862. Note [Orignal module]
  863. ~~~~~~~~~~~~~~~~~~~~~
  864. Consider this:
  865. module X where { data family T }
  866. module Y( T(..) ) where { import X; data instance T Int = MkT Int }
  867. The exported Avail from Y will look like
  868. X.T{X.T, Y.MkT}
  869. That is, in Y,
  870. - only MkT is brought into scope by the data instance;
  871. - but the parent (used for grouping and naming in T(..) exports) is X.T
  872. - and in this case we export X.T too
  873. In the result of MkIfaceExports, the names are grouped by defining module,
  874. so we may need to split up a single Avail into multiple ones.
  875. %************************************************************************
  876. %* *
  877. Load the old interface file for this module (unless
  878. we have it aleady), and check whether it is up to date
  879. %* *
  880. %************************************************************************
  881. \begin{code}
  882. checkOldIface :: HscEnv
  883. -> ModSummary
  884. -> Bool -- Source unchanged
  885. -> Maybe ModIface -- Old interface from compilation manager, if any
  886. -> IO (RecompileRequired, Maybe ModIface)
  887. checkOldIface hsc_env mod_summary source_unchanged maybe_iface
  888. = do { showPass (hsc_dflags hsc_env)
  889. ("Checking old interface for " ++
  890. showSDoc (ppr (ms_mod mod_summary))) ;
  891. ; initIfaceCheck hsc_env $
  892. check_old_iface hsc_env mod_summary source_unchanged maybe_iface
  893. }
  894. check_old_iface :: HscEnv -> ModSummary -> Bool -> Maybe ModIface
  895. -> IfG (Bool, Maybe ModIface)
  896. check_old_iface hsc_env mod_summary source_unchanged maybe_iface
  897. = do -- CHECK WHETHER THE SOURCE HAS CHANGED
  898. { when (not source_unchanged)
  899. (traceHiDiffs (nest 4 (text "Source file changed or recompilation check turned off")))
  900. -- If the source has changed and we're in interactive mode, avoid reading
  901. -- an interface; just return the one we might have been supplied with.
  902. ; let dflags = hsc_dflags hsc_env
  903. ; if not (isObjectTarget (hscTarget dflags)) && not source_unchanged then
  904. return (outOfDate, maybe_iface)
  905. else
  906. case maybe_iface of {
  907. Just old_iface -> do -- Use the one we already have
  908. { traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
  909. ; recomp <- checkVersions hsc_env source_unchanged mod_summary old_iface
  910. ; return (recomp, Just old_iface) }
  911. ; Nothing -> do
  912. -- Try and read the old interface for the current module
  913. -- from the .hi file left from the last time we compiled it
  914. { let iface_path = msHiFilePath mod_summary
  915. ; read_result <- readIface (ms_mod mod_summary) iface_path False
  916. ; case read_result of {
  917. Failed err -> do -- Old interface file not found, or garbled; give up
  918. { traceIf (text "FYI: cannot read old interface file:"
  919. $$ nest 4 err)
  920. ; return (outOfDate, Nothing) }
  921. ; Succeeded iface -> do
  922. -- We have got the old iface; check its versions
  923. { traceIf (text "Read the interface file" <+> text iface_path)
  924. ; recomp <- checkVersions hsc_env source_unchanged mod_summary iface
  925. ; return (recomp, Just iface)
  926. }}}}}
  927. \end{code}
  928. @recompileRequired@ is called from the HscMain. It checks whether
  929. a recompilation is required. It needs access to the persistent state,
  930. finder, etc, because it may have to load lots of interface files to
  931. check their versions.
  932. \begin{code}
  933. type RecompileRequired = Bool
  934. upToDate, outOfDate :: Bool
  935. upToDate = False -- Recompile not required
  936. outOfDate = True -- Recompile required
  937. checkVersions :: HscEnv
  938. -> Bool -- True <=> source unchanged
  939. -> ModSummary
  940. -> ModIface -- Old interface
  941. -> IfG RecompileRequired
  942. checkVersions hsc_env source_unchanged mod_summary iface
  943. | not source_unchanged
  944. = return outOfDate
  945. | otherwise
  946. = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
  947. ppr (mi_module iface) <> colon)
  948. ; recomp <- checkDependencies hsc_env mod_summary iface
  949. ; if recomp then return outOfDate else do {
  950. -- Source code unchanged and no errors yet... carry on
  951. --
  952. -- First put the dependent-module info, read from the old
  953. -- interface, into the envt, so that when we look for
  954. -- interfaces we look for the right one (.hi or .hi-boot)
  955. --
  956. -- It's just temporary because either the usage check will succeed
  957. -- (in which case we are done with this module) or it'll fail (in which
  958. -- case we'll compile the module from scratch anyhow).
  959. --
  960. -- We do this regardless of compilation mode, although in --make mode
  961. -- all the dependent modules should be in the HPT already, so it's
  962. -- quite redundant
  963. updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
  964. ; let this_pkg = thisPackage (hsc_dflags hsc_env)
  965. ; checkList [checkModUsage this_pkg u | u <- mi_usages iface]
  966. }}
  967. where
  968. -- This is a bit of a hack really
  969. mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
  970. mod_deps = mkModDeps (dep_mods (mi_deps iface))
  971. -- If the direct imports of this module are resolved to targets that
  972. -- are not among the dependencies of the previous interface file,
  973. -- then we definitely need to recompile. This catches cases like
  974. -- - an exposed package has been upgraded
  975. -- - we are compiling with different package flags
  976. -- - a home module that was shadowing a package module has been removed
  977. -- - a new home module has been added that shadows a package module
  978. -- See bug #1372.
  979. --
  980. -- Returns True if recompilation is required.
  981. checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
  982. checkDependencies hsc_env summary iface
  983. = orM (map dep_missing (ms_imps summary ++ ms_srcimps summary))
  984. where
  985. prev_dep_mods = dep_mods (mi_deps iface)
  986. prev_dep_pkgs = dep_pkgs (mi_deps iface)
  987. this_pkg = thisPackage (hsc_dflags hsc_env)
  988. orM = foldr f (return False)
  989. where f m rest = do b <- m; if b then return True else rest
  990. dep_missing (L _ (ImportDecl (L _ mod) pkg _ _ _ _)) = do
  991. find_res <- liftIO $ findImportedModule hsc_env mod pkg
  992. case find_res of
  993. Found _ mod
  994. | pkg == this_pkg
  995. -> if moduleName mod `notElem` map fst prev_dep_mods
  996. then do traceHiDiffs $
  997. text "imported module " <> quotes (ppr mod) <>
  998. text " not among previous dependencies"
  999. return outOfDate
  1000. else
  1001. return upToDate
  1002. | otherwise
  1003. -> if pkg `notElem` prev_dep_pkgs
  1004. then do traceHiDiffs $
  1005. text "imported module " <> quotes (ppr mod) <>
  1006. text " is from package " <> quotes (ppr pkg) <>
  1007. text ", which is not among previous dependencies"
  1008. return outOfDate
  1009. else
  1010. return upToDate
  1011. where pkg = modulePackageId mod
  1012. _otherwise -> return outOfDate
  1013. needInterface :: Module -> (ModIface -> IfG RecompileRequired)
  1014. -> IfG RecompileRequired
  1015. needInterface mod continue
  1016. = do -- Load the imported interface if possible
  1017. let doc_str = sep [ptext (sLit "need version info for"), ppr mod]
  1018. traceHiDiffs (text "Checking usages for module" <+> ppr mod)
  1019. mb_iface <- loadInterface doc_str mod ImportBySystem
  1020. -- Load the interface, but don't complain on failure;
  1021. -- Instead, get an Either back which we can test
  1022. case mb_iface of
  1023. Failed _ -> (out_of_date (sep [ptext (sLit "Couldn't load interface for module"),
  1024. ppr mod]))
  1025. -- Couldn't find or parse a module mentioned in the
  1026. -- old interface file. Don't complain: it might
  1027. -- just be that the current module doesn't need that
  1028. -- import and it's been deleted
  1029. Succeeded iface -> continue iface
  1030. checkModUsage :: PackageId ->Usage -> IfG RecompileRequired
  1031. -- Given the usage information extracted from the old
  1032. -- M.hi file for the module being compiled, figure out
  1033. -- whether M needs to be recompiled.
  1034. checkModUsage _this_pkg UsagePackageModule{
  1035. usg_mod = mod,
  1036. usg_mod_hash = old_mod_hash }
  1037. = needInterface mod $ \iface -> do
  1038. checkModuleFingerprint old_mod_hash (mi_mod_hash iface)
  1039. -- We only track the ABI hash of package modules, rather than
  1040. -- individual entity usages, so if the ABI hash changes we must
  1041. -- recompile. This is safe but may entail more recompilation when
  1042. -- a dependent package has changed.
  1043. checkModUsage this_pkg UsageHomeModule{
  1044. usg_mod_name = mod_name,
  1045. usg_mod_hash = old_mod_hash,
  1046. usg_exports = maybe_old_export_hash,
  1047. usg_entities = old_decl_hash }
  1048. = do
  1049. let mod = mkModule this_pkg mod_name
  1050. needInterface mod $ \iface -> do
  1051. let
  1052. new_mod_hash = mi_mod_hash iface
  1053. new_decl_hash = mi_hash_fn iface
  1054. new_export_hash = mi_exp_hash iface
  1055. -- CHECK MODULE
  1056. recompile <- checkModuleFingerprint old_mod_hash new_mod_hash
  1057. if not recompile then return upToDate else do
  1058. -- CHECK EXPORT LIST
  1059. checkMaybeHash maybe_old_export_hash new_export_hash
  1060. (ptext (sLit " Export list changed")) $ do
  1061. -- CHECK ITEMS ONE BY ONE
  1062. recompile <- checkList [ checkEntityUsage new_decl_hash u
  1063. | u <- old_decl_hash]
  1064. if recompile
  1065. then return outOfDate -- This one failed, so just bail out now
  1066. else up_to_date (ptext (sLit " Great! The bits I use are up to date"))
  1067. ------------------------
  1068. checkModuleFingerprint :: Fingerprint -> Fingerprint -> IfG Bool
  1069. checkModuleFingerprint old_mod_hash new_mod_hash
  1070. | new_mod_hash == old_mod_hash
  1071. = up_to_date (ptext (sLit "Module fingerprint unchanged"))
  1072. | otherwise
  1073. = out_of_date_hash (ptext (sLit " Module fingerprint has changed"))
  1074. old_mod_hash new_mod_hash
  1075. ------------------------
  1076. checkMaybeHash :: Maybe Fingerprint -> Fingerprint -> SDoc
  1077. -> IfG RecompileRequired -> IfG RecompileRequired
  1078. checkMaybeHash maybe_old_hash new_hash doc continue
  1079. | Just hash <- maybe_old_hash, hash /= new_hash
  1080. = out_of_date_hash doc hash new_hash
  1081. | otherwise
  1082. = continue
  1083. ------------------------
  1084. checkEntityUsage :: (OccName -> Maybe (OccName, Fingerprint))
  1085. -> (OccName, Fingerprint)
  1086. -> IfG Bool
  1087. checkEntityUsage new_hash (name,old_hash)
  1088. = case new_hash name of
  1089. Nothing -> -- We used it before, but it ain't there now
  1090. out_of_date (sep [ptext (sLit "No longer exported:"), ppr name])
  1091. Just (_, new_hash) -- It's there, but is it up to date?
  1092. | new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash))
  1093. retur

Large files files are truncated, but you can click here to view the full file