PageRenderTime 74ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/iface/MkIface.hs

http://github.com/ghc/ghc
Haskell | 1837 lines | 1168 code | 218 blank | 451 comment | 33 complexity | 007651e57fe65cde325739d859ad974f MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0

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. {-# LANGUAGE CPP, NondecreasingIndentation #-}
  6. -- | Module for constructing @ModIface@ values (interface files),
  7. -- writing them to disk and comparing two versions to see if
  8. -- recompilation is required.
  9. module MkIface (
  10. mkIface, -- Build a ModIface from a ModGuts,
  11. -- including computing version information
  12. mkIfaceTc,
  13. writeIfaceFile, -- Write the interface file
  14. checkOldIface, -- See if recompilation is required, by
  15. -- comparing version information
  16. RecompileRequired(..), recompileRequired,
  17. tyThingToIfaceDecl -- Converting things to their Iface equivalents
  18. ) where
  19. {-
  20. -----------------------------------------------
  21. Recompilation checking
  22. -----------------------------------------------
  23. A complete description of how recompilation checking works can be
  24. found in the wiki commentary:
  25. http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
  26. Please read the above page for a top-down description of how this all
  27. works. Notes below cover specific issues related to the implementation.
  28. Basic idea:
  29. * In the mi_usages information in an interface, we record the
  30. fingerprint of each free variable of the module
  31. * In mkIface, we compute the fingerprint of each exported thing A.f.
  32. For each external thing that A.f refers to, we include the fingerprint
  33. of the external reference when computing the fingerprint of A.f. So
  34. if anything that A.f depends on changes, then A.f's fingerprint will
  35. change.
  36. Also record any dependent files added with
  37. * addDependentFile
  38. * #include
  39. * -optP-include
  40. * In checkOldIface we compare the mi_usages for the module with
  41. the actual fingerprint for all each thing recorded in mi_usages
  42. -}
  43. #include "HsVersions.h"
  44. import IfaceSyn
  45. import LoadIface
  46. import FlagChecker
  47. import Desugar ( mkUsageInfo, mkUsedNames, mkDependencies )
  48. import Id
  49. import IdInfo
  50. import Demand
  51. import Coercion( tidyCo )
  52. import Annotations
  53. import CoreSyn
  54. import Class
  55. import TyCon
  56. import CoAxiom
  57. import ConLike
  58. import DataCon
  59. import PatSyn
  60. import Type
  61. import TcType
  62. import InstEnv
  63. import FamInstEnv
  64. import TcRnMonad
  65. import HsSyn
  66. import HscTypes
  67. import Finder
  68. import DynFlags
  69. import VarEnv
  70. import VarSet
  71. import Var
  72. import Name
  73. import Avail
  74. import RdrName
  75. import NameEnv
  76. import NameSet
  77. import Module
  78. import BinIface
  79. import ErrUtils
  80. import Digraph
  81. import SrcLoc
  82. import Outputable
  83. import BasicTypes hiding ( SuccessFlag(..) )
  84. import Unique
  85. import Util hiding ( eqListBy )
  86. import FastString
  87. import FastStringEnv
  88. import Maybes
  89. import Binary
  90. import Fingerprint
  91. import Exception
  92. import UniqFM
  93. import UniqDFM
  94. import Control.Monad
  95. import Data.Function
  96. import Data.List
  97. import qualified Data.Map as Map
  98. import Data.Ord
  99. import Data.IORef
  100. import System.Directory
  101. import System.FilePath
  102. {-
  103. ************************************************************************
  104. * *
  105. \subsection{Completing an interface}
  106. * *
  107. ************************************************************************
  108. -}
  109. mkIface :: HscEnv
  110. -> Maybe Fingerprint -- The old fingerprint, if we have it
  111. -> ModDetails -- The trimmed, tidied interface
  112. -> ModGuts -- Usages, deprecations, etc
  113. -> IO (ModIface, -- The new one
  114. Bool) -- True <=> there was an old Iface, and the
  115. -- new one is identical, so no need
  116. -- to write it
  117. mkIface hsc_env maybe_old_fingerprint mod_details
  118. ModGuts{ mg_module = this_mod,
  119. mg_hsc_src = hsc_src,
  120. mg_usages = usages,
  121. mg_used_th = used_th,
  122. mg_deps = deps,
  123. mg_rdr_env = rdr_env,
  124. mg_fix_env = fix_env,
  125. mg_warns = warns,
  126. mg_hpc_info = hpc_info,
  127. mg_safe_haskell = safe_mode,
  128. mg_trust_pkg = self_trust
  129. }
  130. = mkIface_ hsc_env maybe_old_fingerprint
  131. this_mod hsc_src used_th deps rdr_env fix_env
  132. warns hpc_info self_trust
  133. safe_mode usages mod_details
  134. -- | make an interface from the results of typechecking only. Useful
  135. -- for non-optimising compilation, or where we aren't generating any
  136. -- object code at all ('HscNothing').
  137. mkIfaceTc :: HscEnv
  138. -> Maybe Fingerprint -- The old fingerprint, if we have it
  139. -> SafeHaskellMode -- The safe haskell mode
  140. -> ModDetails -- gotten from mkBootModDetails, probably
  141. -> TcGblEnv -- Usages, deprecations, etc
  142. -> IO (ModIface, Bool)
  143. mkIfaceTc hsc_env maybe_old_fingerprint safe_mode mod_details
  144. tc_result@TcGblEnv{ tcg_mod = this_mod,
  145. tcg_src = hsc_src,
  146. tcg_imports = imports,
  147. tcg_rdr_env = rdr_env,
  148. tcg_fix_env = fix_env,
  149. tcg_warns = warns,
  150. tcg_hpc = other_hpc_info,
  151. tcg_th_splice_used = tc_splice_used,
  152. tcg_dependent_files = dependent_files
  153. }
  154. = do
  155. let used_names = mkUsedNames tc_result
  156. deps <- mkDependencies tc_result
  157. let hpc_info = emptyHpcInfo other_hpc_info
  158. used_th <- readIORef tc_splice_used
  159. dep_files <- (readIORef dependent_files)
  160. usages <- mkUsageInfo hsc_env this_mod (imp_mods imports) used_names dep_files
  161. mkIface_ hsc_env maybe_old_fingerprint
  162. this_mod hsc_src
  163. used_th deps rdr_env
  164. fix_env warns hpc_info
  165. (imp_trust_own_pkg imports) safe_mode usages mod_details
  166. mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> HscSource
  167. -> Bool -> Dependencies -> GlobalRdrEnv
  168. -> NameEnv FixItem -> Warnings -> HpcInfo
  169. -> Bool
  170. -> SafeHaskellMode
  171. -> [Usage]
  172. -> ModDetails
  173. -> IO (ModIface, Bool)
  174. mkIface_ hsc_env maybe_old_fingerprint
  175. this_mod hsc_src used_th deps rdr_env fix_env src_warns
  176. hpc_info pkg_trust_req safe_mode usages
  177. ModDetails{ md_insts = insts,
  178. md_fam_insts = fam_insts,
  179. md_rules = rules,
  180. md_anns = anns,
  181. md_vect_info = vect_info,
  182. md_types = type_env,
  183. md_exports = exports }
  184. -- NB: notice that mkIface does not look at the bindings
  185. -- only at the TypeEnv. The previous Tidy phase has
  186. -- put exactly the info into the TypeEnv that we want
  187. -- to expose in the interface
  188. = do
  189. let entities = typeEnvElts type_env
  190. decls = [ tyThingToIfaceDecl entity
  191. | entity <- entities,
  192. let name = getName entity,
  193. not (isImplicitTyThing entity),
  194. -- No implicit Ids and class tycons in the interface file
  195. not (isWiredInName name),
  196. -- Nor wired-in things; the compiler knows about them anyhow
  197. nameIsLocalOrFrom this_mod name ]
  198. -- Sigh: see Note [Root-main Id] in TcRnDriver
  199. fixities = sortBy (comparing fst)
  200. [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
  201. -- The order of fixities returned from nameEnvElts is not
  202. -- deterministic, so we sort by OccName to canonicalize it.
  203. -- See Note [Deterministic UniqFM] in UniqDFM for more details.
  204. warns = src_warns
  205. iface_rules = map coreRuleToIfaceRule rules
  206. iface_insts = map instanceToIfaceInst $ fixSafeInstances safe_mode insts
  207. iface_fam_insts = map famInstToIfaceFamInst fam_insts
  208. iface_vect_info = flattenVectInfo vect_info
  209. trust_info = setSafeMode safe_mode
  210. annotations = map mkIfaceAnnotation anns
  211. sig_of = getSigOf dflags (moduleName this_mod)
  212. intermediate_iface = ModIface {
  213. mi_module = this_mod,
  214. mi_sig_of = sig_of,
  215. mi_hsc_src = hsc_src,
  216. mi_deps = deps,
  217. mi_usages = usages,
  218. mi_exports = mkIfaceExports exports,
  219. -- Sort these lexicographically, so that
  220. -- the result is stable across compilations
  221. mi_insts = sortBy cmp_inst iface_insts,
  222. mi_fam_insts = sortBy cmp_fam_inst iface_fam_insts,
  223. mi_rules = sortBy cmp_rule iface_rules,
  224. mi_vect_info = iface_vect_info,
  225. mi_fixities = fixities,
  226. mi_warns = warns,
  227. mi_anns = annotations,
  228. mi_globals = maybeGlobalRdrEnv rdr_env,
  229. -- Left out deliberately: filled in by addFingerprints
  230. mi_iface_hash = fingerprint0,
  231. mi_mod_hash = fingerprint0,
  232. mi_flag_hash = fingerprint0,
  233. mi_exp_hash = fingerprint0,
  234. mi_used_th = used_th,
  235. mi_orphan_hash = fingerprint0,
  236. mi_orphan = False, -- Always set by addFingerprints, but
  237. -- it's a strict field, so we can't omit it.
  238. mi_finsts = False, -- Ditto
  239. mi_decls = deliberatelyOmitted "decls",
  240. mi_hash_fn = deliberatelyOmitted "hash_fn",
  241. mi_hpc = isHpcUsed hpc_info,
  242. mi_trust = trust_info,
  243. mi_trust_pkg = pkg_trust_req,
  244. -- And build the cached values
  245. mi_warn_fn = mkIfaceWarnCache warns,
  246. mi_fix_fn = mkIfaceFixCache fixities }
  247. (new_iface, no_change_at_all)
  248. <- {-# SCC "versioninfo" #-}
  249. addFingerprints hsc_env maybe_old_fingerprint
  250. intermediate_iface decls
  251. -- Debug printing
  252. dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
  253. (pprModIface new_iface)
  254. -- bug #1617: on reload we weren't updating the PrintUnqualified
  255. -- correctly. This stems from the fact that the interface had
  256. -- not changed, so addFingerprints returns the old ModIface
  257. -- with the old GlobalRdrEnv (mi_globals).
  258. let final_iface = new_iface{ mi_globals = maybeGlobalRdrEnv rdr_env }
  259. return (final_iface, no_change_at_all)
  260. where
  261. cmp_rule = comparing ifRuleName
  262. -- Compare these lexicographically by OccName, *not* by unique,
  263. -- because the latter is not stable across compilations:
  264. cmp_inst = comparing (nameOccName . ifDFun)
  265. cmp_fam_inst = comparing (nameOccName . ifFamInstTcName)
  266. dflags = hsc_dflags hsc_env
  267. -- We only fill in mi_globals if the module was compiled to byte
  268. -- code. Otherwise, the compiler may not have retained all the
  269. -- top-level bindings and they won't be in the TypeEnv (see
  270. -- Desugar.addExportFlagsAndRules). The mi_globals field is used
  271. -- by GHCi to decide whether the module has its full top-level
  272. -- scope available. (#5534)
  273. maybeGlobalRdrEnv :: GlobalRdrEnv -> Maybe GlobalRdrEnv
  274. maybeGlobalRdrEnv rdr_env
  275. | targetRetainsAllBindings (hscTarget dflags) = Just rdr_env
  276. | otherwise = Nothing
  277. deliberatelyOmitted :: String -> a
  278. deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
  279. ifFamInstTcName = ifFamInstFam
  280. flattenVectInfo (VectInfo { vectInfoVar = vVar
  281. , vectInfoTyCon = vTyCon
  282. , vectInfoParallelVars = vParallelVars
  283. , vectInfoParallelTyCons = vParallelTyCons
  284. }) =
  285. IfaceVectInfo
  286. { ifaceVectInfoVar = [Var.varName v | (v, _ ) <- dVarEnvElts vVar]
  287. , ifaceVectInfoTyCon = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t /= t_v]
  288. , ifaceVectInfoTyConReuse = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t == t_v]
  289. , ifaceVectInfoParallelVars = [Var.varName v | v <- dVarSetElems vParallelVars]
  290. , ifaceVectInfoParallelTyCons = nameSetElemsStable vParallelTyCons
  291. }
  292. -----------------------------
  293. writeIfaceFile :: DynFlags -> FilePath -> ModIface -> IO ()
  294. writeIfaceFile dflags hi_file_path new_iface
  295. = do createDirectoryIfMissing True (takeDirectory hi_file_path)
  296. writeBinIface dflags hi_file_path new_iface
  297. -- -----------------------------------------------------------------------------
  298. -- Look up parents and versions of Names
  299. -- This is like a global version of the mi_hash_fn field in each ModIface.
  300. -- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get
  301. -- the parent and version info.
  302. mkHashFun
  303. :: HscEnv -- needed to look up versions
  304. -> ExternalPackageState -- ditto
  305. -> (Name -> Fingerprint)
  306. mkHashFun hsc_env eps
  307. = \name ->
  308. let
  309. mod = ASSERT2( isExternalName name, ppr name ) nameModule name
  310. occ = nameOccName name
  311. iface = lookupIfaceByModule dflags hpt pit mod `orElse`
  312. pprPanic "lookupVers2" (ppr mod <+> ppr occ)
  313. in
  314. snd (mi_hash_fn iface occ `orElse`
  315. pprPanic "lookupVers1" (ppr mod <+> ppr occ))
  316. where
  317. dflags = hsc_dflags hsc_env
  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 ann_fn non_orph_rules non_orph_insts
  340. non_orph_fis decl
  341. edges :: [(IfaceDeclABI, Unique, [Unique])]
  342. edges = [ (abi, getUnique (ifName decl), out)
  343. | decl <- new_decls
  344. , let abi = declABI decl
  345. , let out = localOccs $ freeNamesDeclABI abi
  346. ]
  347. name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n
  348. localOccs = map (getUnique . getParent . getOccName)
  349. . filter ((== this_mod) . name_module)
  350. . nonDetEltsUFM
  351. -- It's OK to use nonDetEltsUFM as localOccs is only
  352. -- used to construct the edges and
  353. -- stronglyConnCompFromEdgedVertices is deterministic
  354. -- even with non-deterministic order of edges as
  355. -- explained in Note [Deterministic SCC] in Digraph.
  356. where getParent occ = lookupOccEnv parent_map occ `orElse` occ
  357. -- maps OccNames to their parents in the current module.
  358. -- e.g. a reference to a constructor must be turned into a reference
  359. -- to the TyCon for the purposes of calculating dependencies.
  360. parent_map :: OccEnv OccName
  361. parent_map = foldr extend emptyOccEnv new_decls
  362. where extend d env =
  363. extendOccEnvList env [ (b,n) | b <- ifaceDeclImplicitBndrs d ]
  364. where n = ifName d
  365. -- strongly-connected groups of declarations, in dependency order
  366. groups = stronglyConnCompFromEdgedVerticesUniq edges
  367. global_hash_fn = mkHashFun hsc_env eps
  368. -- how to output Names when generating the data to fingerprint.
  369. -- Here we want to output the fingerprint for each top-level
  370. -- Name, whether it comes from the current module or another
  371. -- module. In this way, the fingerprint for a declaration will
  372. -- change if the fingerprint for anything it refers to (transitively)
  373. -- changes.
  374. mk_put_name :: (OccEnv (OccName,Fingerprint))
  375. -> BinHandle -> Name -> IO ()
  376. mk_put_name local_env bh name
  377. | isWiredInName name = putNameLiterally bh name
  378. -- wired-in names don't have fingerprints
  379. | otherwise
  380. = ASSERT2( isExternalName name, ppr name )
  381. let hash | nameModule name /= this_mod = global_hash_fn name
  382. | otherwise = snd (lookupOccEnv local_env (getOccName name)
  383. `orElse` pprPanic "urk! lookup local fingerprint"
  384. (ppr name)) -- (undefined,fingerprint0))
  385. -- This panic indicates that we got the dependency
  386. -- analysis wrong, because we needed a fingerprint for
  387. -- an entity that wasn't in the environment. To debug
  388. -- it, turn the panic into a trace, uncomment the
  389. -- pprTraces below, run the compile again, and inspect
  390. -- the output and the generated .hi file with
  391. -- --show-iface.
  392. in put_ bh hash
  393. -- take a strongly-connected group of declarations and compute
  394. -- its fingerprint.
  395. fingerprint_group :: (OccEnv (OccName,Fingerprint),
  396. [(Fingerprint,IfaceDecl)])
  397. -> SCC IfaceDeclABI
  398. -> IO (OccEnv (OccName,Fingerprint),
  399. [(Fingerprint,IfaceDecl)])
  400. fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi)
  401. = do let hash_fn = mk_put_name local_env
  402. decl = abiDecl abi
  403. --pprTrace "fingerprinting" (ppr (ifName decl) ) $ do
  404. hash <- computeFingerprint hash_fn abi
  405. env' <- extend_hash_env local_env (hash,decl)
  406. return (env', (hash,decl) : decls_w_hashes)
  407. fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis)
  408. = do let decls = map abiDecl abis
  409. local_env1 <- foldM extend_hash_env local_env
  410. (zip (repeat fingerprint0) decls)
  411. let hash_fn = mk_put_name local_env1
  412. -- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do
  413. let stable_abis = sortBy cmp_abiNames abis
  414. -- put the cycle in a canonical order
  415. hash <- computeFingerprint hash_fn stable_abis
  416. let pairs = zip (repeat hash) decls
  417. local_env2 <- foldM extend_hash_env local_env pairs
  418. return (local_env2, pairs ++ decls_w_hashes)
  419. -- we have fingerprinted the whole declaration, but we now need
  420. -- to assign fingerprints to all the OccNames that it binds, to
  421. -- use when referencing those OccNames in later declarations.
  422. --
  423. extend_hash_env :: OccEnv (OccName,Fingerprint)
  424. -> (Fingerprint,IfaceDecl)
  425. -> IO (OccEnv (OccName,Fingerprint))
  426. extend_hash_env env0 (hash,d) = do
  427. return (foldr (\(b,fp) env -> extendOccEnv env b (b,fp)) env0
  428. (ifaceDeclFingerprints hash d))
  429. --
  430. (local_env, decls_w_hashes) <-
  431. foldM fingerprint_group (emptyOccEnv, []) groups
  432. -- when calculating fingerprints, we always need to use canonical
  433. -- ordering for lists of things. In particular, the mi_deps has various
  434. -- lists of modules and suchlike, so put these all in canonical order:
  435. let sorted_deps = sortDependencies (mi_deps iface0)
  436. -- the export hash of a module depends on the orphan hashes of the
  437. -- orphan modules below us in the dependency tree. This is the way
  438. -- that changes in orphans get propagated all the way up the
  439. -- dependency tree. We only care about orphan modules in the current
  440. -- package, because changes to orphans outside this package will be
  441. -- tracked by the usage on the ABI hash of package modules that we import.
  442. let orph_mods
  443. = filter (/= this_mod) -- Note [Do not update EPS with your own hi-boot]
  444. . filter ((== this_pkg) . moduleUnitId)
  445. $ dep_orphs sorted_deps
  446. dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods
  447. -- Note [Do not update EPS with your own hi-boot]
  448. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  449. -- (See also Trac #10182). When your hs-boot file includes an orphan
  450. -- instance declaration, you may find that the dep_orphs of a module you
  451. -- import contains reference to yourself. DO NOT actually load this module
  452. -- or add it to the orphan hashes: you're going to provide the orphan
  453. -- instances yourself, no need to consult hs-boot; if you do load the
  454. -- interface into EPS, you will see a duplicate orphan instance.
  455. orphan_hash <- computeFingerprint (mk_put_name local_env)
  456. (map ifDFun orph_insts, orph_rules, orph_fis)
  457. -- the export list hash doesn't depend on the fingerprints of
  458. -- the Names it mentions, only the Names themselves, hence putNameLiterally.
  459. export_hash <- computeFingerprint putNameLiterally
  460. (mi_exports iface0,
  461. orphan_hash,
  462. dep_orphan_hashes,
  463. dep_pkgs (mi_deps iface0),
  464. -- dep_pkgs: see "Package Version Changes" on
  465. -- wiki/Commentary/Compiler/RecompilationAvoidance
  466. mi_trust iface0)
  467. -- Make sure change of Safe Haskell mode causes recomp.
  468. -- put the declarations in a canonical order, sorted by OccName
  469. let sorted_decls = Map.elems $ Map.fromList $
  470. [(ifName d, e) | e@(_, d) <- decls_w_hashes]
  471. -- the flag hash depends on:
  472. -- - (some of) dflags
  473. -- it returns two hashes, one that shouldn't change
  474. -- the abi hash and one that should
  475. flag_hash <- fingerprintDynFlags dflags this_mod putNameLiterally
  476. -- the ABI hash depends on:
  477. -- - decls
  478. -- - export list
  479. -- - orphans
  480. -- - deprecations
  481. -- - vect info
  482. -- - flag abi hash
  483. mod_hash <- computeFingerprint putNameLiterally
  484. (map fst sorted_decls,
  485. export_hash, -- includes orphan_hash
  486. mi_warns iface0,
  487. mi_vect_info iface0)
  488. -- The interface hash depends on:
  489. -- - the ABI hash, plus
  490. -- - the module level annotations,
  491. -- - usages
  492. -- - deps (home and external packages, dependent files)
  493. -- - hpc
  494. iface_hash <- computeFingerprint putNameLiterally
  495. (mod_hash,
  496. ann_fn (mkVarOcc "module"), -- See mkIfaceAnnCache
  497. mi_usages iface0,
  498. sorted_deps,
  499. mi_hpc iface0)
  500. let
  501. no_change_at_all = Just iface_hash == mb_old_fingerprint
  502. final_iface = iface0 {
  503. mi_mod_hash = mod_hash,
  504. mi_iface_hash = iface_hash,
  505. mi_exp_hash = export_hash,
  506. mi_orphan_hash = orphan_hash,
  507. mi_flag_hash = flag_hash,
  508. mi_orphan = not ( all ifRuleAuto orph_rules
  509. -- See Note [Orphans and auto-generated rules]
  510. && null orph_insts
  511. && null orph_fis
  512. && isNoIfaceVectInfo (mi_vect_info iface0)),
  513. mi_finsts = not . null $ mi_fam_insts iface0,
  514. mi_decls = sorted_decls,
  515. mi_hash_fn = lookupOccEnv local_env }
  516. --
  517. return (final_iface, no_change_at_all)
  518. where
  519. this_mod = mi_module iface0
  520. dflags = hsc_dflags hsc_env
  521. this_pkg = thisPackage dflags
  522. (non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0)
  523. (non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0)
  524. (non_orph_fis, orph_fis) = mkOrphMap ifFamInstOrph (mi_fam_insts iface0)
  525. fix_fn = mi_fix_fn iface0
  526. ann_fn = mkIfaceAnnCache (mi_anns iface0)
  527. getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint]
  528. getOrphanHashes hsc_env mods = do
  529. eps <- hscEPS hsc_env
  530. let
  531. hpt = hsc_HPT hsc_env
  532. pit = eps_PIT eps
  533. dflags = hsc_dflags hsc_env
  534. get_orph_hash mod =
  535. case lookupIfaceByModule dflags hpt pit mod of
  536. Nothing -> pprPanic "moduleOrphanHash" (ppr mod)
  537. Just iface -> mi_orphan_hash iface
  538. --
  539. return (map get_orph_hash mods)
  540. sortDependencies :: Dependencies -> Dependencies
  541. sortDependencies d
  542. = Deps { dep_mods = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d),
  543. dep_pkgs = sortBy (stableUnitIdCmp `on` fst) (dep_pkgs d),
  544. dep_orphs = sortBy stableModuleCmp (dep_orphs d),
  545. dep_finsts = sortBy stableModuleCmp (dep_finsts d) }
  546. -- | Creates cached lookup for the 'mi_anns' field of ModIface
  547. -- Hackily, we use "module" as the OccName for any module-level annotations
  548. mkIfaceAnnCache :: [IfaceAnnotation] -> OccName -> [AnnPayload]
  549. mkIfaceAnnCache anns
  550. = \n -> lookupOccEnv env n `orElse` []
  551. where
  552. pair (IfaceAnnotation target value) =
  553. (case target of
  554. NamedTarget occn -> occn
  555. ModuleTarget _ -> mkVarOcc "module"
  556. , [value])
  557. -- flipping (++), so the first argument is always short
  558. env = mkOccEnv_C (flip (++)) (map pair anns)
  559. {-
  560. ************************************************************************
  561. * *
  562. The ABI of an IfaceDecl
  563. * *
  564. ************************************************************************
  565. Note [The ABI of an IfaceDecl]
  566. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  567. The ABI of a declaration consists of:
  568. (a) the full name of the identifier (inc. module and package,
  569. because these are used to construct the symbol name by which
  570. the identifier is known externally).
  571. (b) the declaration itself, as exposed to clients. That is, the
  572. definition of an Id is included in the fingerprint only if
  573. it is made available as an unfolding in the interface.
  574. (c) the fixity of the identifier (if it exists)
  575. (d) for Ids: rules
  576. (e) for classes: instances, fixity & rules for methods
  577. (f) for datatypes: instances, fixity & rules for constrs
  578. Items (c)-(f) are not stored in the IfaceDecl, but instead appear
  579. elsewhere in the interface file. But they are *fingerprinted* with
  580. the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras,
  581. and fingerprinting that as part of the declaration.
  582. -}
  583. type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras)
  584. data IfaceDeclExtras
  585. = IfaceIdExtras IfaceIdExtras
  586. | IfaceDataExtras
  587. (Maybe Fixity) -- Fixity of the tycon itself (if it exists)
  588. [IfaceInstABI] -- Local class and family instances of this tycon
  589. -- See Note [Orphans] in InstEnv
  590. [AnnPayload] -- Annotations of the type itself
  591. [IfaceIdExtras] -- For each constructor: fixity, RULES and annotations
  592. | IfaceClassExtras
  593. (Maybe Fixity) -- Fixity of the class itself (if it exists)
  594. [IfaceInstABI] -- Local instances of this class *or*
  595. -- of its associated data types
  596. -- See Note [Orphans] in InstEnv
  597. [AnnPayload] -- Annotations of the type itself
  598. [IfaceIdExtras] -- For each class method: fixity, RULES and annotations
  599. | IfaceSynonymExtras (Maybe Fixity) [AnnPayload]
  600. | IfaceFamilyExtras (Maybe Fixity) [IfaceInstABI] [AnnPayload]
  601. | IfaceOtherDeclExtras
  602. data IfaceIdExtras
  603. = IdExtras
  604. (Maybe Fixity) -- Fixity of the Id (if it exists)
  605. [IfaceRule] -- Rules for the Id
  606. [AnnPayload] -- Annotations for the Id
  607. -- When hashing a class or family instance, we hash only the
  608. -- DFunId or CoAxiom, because that depends on all the
  609. -- information about the instance.
  610. --
  611. type IfaceInstABI = IfExtName -- Name of DFunId or CoAxiom that is evidence for the instance
  612. abiDecl :: IfaceDeclABI -> IfaceDecl
  613. abiDecl (_, decl, _) = decl
  614. cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering
  615. cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare`
  616. ifName (abiDecl abi2)
  617. freeNamesDeclABI :: IfaceDeclABI -> NameSet
  618. freeNamesDeclABI (_mod, decl, extras) =
  619. freeNamesIfDecl decl `unionNameSet` freeNamesDeclExtras extras
  620. freeNamesDeclExtras :: IfaceDeclExtras -> NameSet
  621. freeNamesDeclExtras (IfaceIdExtras id_extras)
  622. = freeNamesIdExtras id_extras
  623. freeNamesDeclExtras (IfaceDataExtras _ insts _ subs)
  624. = unionNameSets (mkNameSet insts : map freeNamesIdExtras subs)
  625. freeNamesDeclExtras (IfaceClassExtras _ insts _ subs)
  626. = unionNameSets (mkNameSet insts : map freeNamesIdExtras subs)
  627. freeNamesDeclExtras (IfaceSynonymExtras _ _)
  628. = emptyNameSet
  629. freeNamesDeclExtras (IfaceFamilyExtras _ insts _)
  630. = mkNameSet insts
  631. freeNamesDeclExtras IfaceOtherDeclExtras
  632. = emptyNameSet
  633. freeNamesIdExtras :: IfaceIdExtras -> NameSet
  634. freeNamesIdExtras (IdExtras _ rules _) = unionNameSets (map freeNamesIfRule rules)
  635. instance Outputable IfaceDeclExtras where
  636. ppr IfaceOtherDeclExtras = Outputable.empty
  637. ppr (IfaceIdExtras extras) = ppr_id_extras extras
  638. ppr (IfaceSynonymExtras fix anns) = vcat [ppr fix, ppr anns]
  639. ppr (IfaceFamilyExtras fix finsts anns) = vcat [ppr fix, ppr finsts, ppr anns]
  640. ppr (IfaceDataExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns,
  641. ppr_id_extras_s stuff]
  642. ppr (IfaceClassExtras fix insts anns stuff) = vcat [ppr fix, ppr_insts insts, ppr anns,
  643. ppr_id_extras_s stuff]
  644. ppr_insts :: [IfaceInstABI] -> SDoc
  645. ppr_insts _ = text "<insts>"
  646. ppr_id_extras_s :: [IfaceIdExtras] -> SDoc
  647. ppr_id_extras_s stuff = vcat (map ppr_id_extras stuff)
  648. ppr_id_extras :: IfaceIdExtras -> SDoc
  649. ppr_id_extras (IdExtras fix rules anns) = ppr fix $$ vcat (map ppr rules) $$ vcat (map ppr anns)
  650. -- This instance is used only to compute fingerprints
  651. instance Binary IfaceDeclExtras where
  652. get _bh = panic "no get for IfaceDeclExtras"
  653. put_ bh (IfaceIdExtras extras) = do
  654. putByte bh 1; put_ bh extras
  655. put_ bh (IfaceDataExtras fix insts anns cons) = do
  656. putByte bh 2; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh cons
  657. put_ bh (IfaceClassExtras fix insts anns methods) = do
  658. putByte bh 3; put_ bh fix; put_ bh insts; put_ bh anns; put_ bh methods
  659. put_ bh (IfaceSynonymExtras fix anns) = do
  660. putByte bh 4; put_ bh fix; put_ bh anns
  661. put_ bh (IfaceFamilyExtras fix finsts anns) = do
  662. putByte bh 5; put_ bh fix; put_ bh finsts; put_ bh anns
  663. put_ bh IfaceOtherDeclExtras = putByte bh 6
  664. instance Binary IfaceIdExtras where
  665. get _bh = panic "no get for IfaceIdExtras"
  666. put_ bh (IdExtras fix rules anns)= do { put_ bh fix; put_ bh rules; put_ bh anns }
  667. declExtras :: (OccName -> Maybe Fixity)
  668. -> (OccName -> [AnnPayload])
  669. -> OccEnv [IfaceRule]
  670. -> OccEnv [IfaceClsInst]
  671. -> OccEnv [IfaceFamInst]
  672. -> IfaceDecl
  673. -> IfaceDeclExtras
  674. declExtras fix_fn ann_fn rule_env inst_env fi_env decl
  675. = case decl of
  676. IfaceId{} -> IfaceIdExtras (id_extras n)
  677. IfaceData{ifCons=cons} ->
  678. IfaceDataExtras (fix_fn n)
  679. (map ifFamInstAxiom (lookupOccEnvL fi_env n) ++
  680. map ifDFun (lookupOccEnvL inst_env n))
  681. (ann_fn n)
  682. (map (id_extras . ifConOcc) (visibleIfConDecls cons))
  683. IfaceClass{ifSigs=sigs, ifATs=ats} ->
  684. IfaceClassExtras (fix_fn n)
  685. (map ifDFun $ (concatMap at_extras ats)
  686. ++ lookupOccEnvL inst_env n)
  687. -- Include instances of the associated types
  688. -- as well as instances of the class (Trac #5147)
  689. (ann_fn n)
  690. [id_extras op | IfaceClassOp op _ _ <- sigs]
  691. IfaceSynonym{} -> IfaceSynonymExtras (fix_fn n)
  692. (ann_fn n)
  693. IfaceFamily{} -> IfaceFamilyExtras (fix_fn n)
  694. (map ifFamInstAxiom (lookupOccEnvL fi_env n))
  695. (ann_fn n)
  696. _other -> IfaceOtherDeclExtras
  697. where
  698. n = ifName decl
  699. id_extras occ = IdExtras (fix_fn occ) (lookupOccEnvL rule_env occ) (ann_fn occ)
  700. at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (ifName decl)
  701. lookupOccEnvL :: OccEnv [v] -> OccName -> [v]
  702. lookupOccEnvL env k = lookupOccEnv env k `orElse` []
  703. -- used when we want to fingerprint a structure without depending on the
  704. -- fingerprints of external Names that it refers to.
  705. putNameLiterally :: BinHandle -> Name -> IO ()
  706. putNameLiterally bh name = ASSERT( isExternalName name )
  707. do
  708. put_ bh $! nameModule name
  709. put_ bh $! nameOccName name
  710. {-
  711. -- for testing: use the md5sum command to generate fingerprints and
  712. -- compare the results against our built-in version.
  713. fp' <- oldMD5 dflags bh
  714. if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp')
  715. else return fp
  716. oldMD5 dflags bh = do
  717. tmp <- newTempName dflags "bin"
  718. writeBinMem bh tmp
  719. tmp2 <- newTempName dflags "md5"
  720. let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2
  721. r <- system cmd
  722. case r of
  723. ExitFailure _ -> throwGhcExceptionIO (PhaseFailed cmd r)
  724. ExitSuccess -> do
  725. hash_str <- readFile tmp2
  726. return $! readHexFingerprint hash_str
  727. -}
  728. ----------------------
  729. -- mkOrphMap partitions instance decls or rules into
  730. -- (a) an OccEnv for ones that are not orphans,
  731. -- mapping the local OccName to a list of its decls
  732. -- (b) a list of orphan decls
  733. mkOrphMap :: (decl -> IsOrphan) -- Extract orphan status from decl
  734. -> [decl] -- Sorted into canonical order
  735. -> (OccEnv [decl], -- Non-orphan decls associated with their key;
  736. -- each sublist in canonical order
  737. [decl]) -- Orphan decls; in canonical order
  738. mkOrphMap get_key decls
  739. = foldl go (emptyOccEnv, []) decls
  740. where
  741. go (non_orphs, orphs) d
  742. | NotOrphan occ <- get_key d
  743. = (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs)
  744. | otherwise = (non_orphs, d:orphs)
  745. {-
  746. ************************************************************************
  747. * *
  748. Keeping track of what we've slurped, and fingerprints
  749. * *
  750. ************************************************************************
  751. -}
  752. mkIfaceAnnotation :: Annotation -> IfaceAnnotation
  753. mkIfaceAnnotation (Annotation { ann_target = target, ann_value = payload })
  754. = IfaceAnnotation {
  755. ifAnnotatedTarget = fmap nameOccName target,
  756. ifAnnotatedValue = payload
  757. }
  758. mkIfaceExports :: [AvailInfo] -> [IfaceExport] -- Sort to make canonical
  759. mkIfaceExports exports
  760. = sortBy stableAvailCmp (map sort_subs exports)
  761. where
  762. sort_subs :: AvailInfo -> AvailInfo
  763. sort_subs (Avail b n) = Avail b n
  764. sort_subs (AvailTC n [] fs) = AvailTC n [] (sort_flds fs)
  765. sort_subs (AvailTC n (m:ms) fs)
  766. | n==m = AvailTC n (m:sortBy stableNameCmp ms) (sort_flds fs)
  767. | otherwise = AvailTC n (sortBy stableNameCmp (m:ms)) (sort_flds fs)
  768. -- Maintain the AvailTC Invariant
  769. sort_flds = sortBy (stableNameCmp `on` flSelector)
  770. {-
  771. Note [Orignal module]
  772. ~~~~~~~~~~~~~~~~~~~~~
  773. Consider this:
  774. module X where { data family T }
  775. module Y( T(..) ) where { import X; data instance T Int = MkT Int }
  776. The exported Avail from Y will look like
  777. X.T{X.T, Y.MkT}
  778. That is, in Y,
  779. - only MkT is brought into scope by the data instance;
  780. - but the parent (used for grouping and naming in T(..) exports) is X.T
  781. - and in this case we export X.T too
  782. In the result of MkIfaceExports, the names are grouped by defining module,
  783. so we may need to split up a single Avail into multiple ones.
  784. Note [Internal used_names]
  785. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  786. Most of the used_names are External Names, but we can have Internal
  787. Names too: see Note [Binders in Template Haskell] in Convert, and
  788. Trac #5362 for an example. Such Names are always
  789. - Such Names are always for locally-defined things, for which we
  790. don't gather usage info, so we can just ignore them in ent_map
  791. - They are always System Names, hence the assert, just as a double check.
  792. ************************************************************************
  793. * *
  794. Load the old interface file for this module (unless
  795. we have it already), and check whether it is up to date
  796. * *
  797. ************************************************************************
  798. -}
  799. data RecompileRequired
  800. = UpToDate
  801. -- ^ everything is up to date, recompilation is not required
  802. | MustCompile
  803. -- ^ The .hs file has been touched, or the .o/.hi file does not exist
  804. | RecompBecause String
  805. -- ^ The .o/.hi files are up to date, but something else has changed
  806. -- to force recompilation; the String says what (one-line summary)
  807. deriving Eq
  808. recompileRequired :: RecompileRequired -> Bool
  809. recompileRequired UpToDate = False
  810. recompileRequired _ = True
  811. -- | Top level function to check if the version of an old interface file
  812. -- is equivalent to the current source file the user asked us to compile.
  813. -- If the same, we can avoid recompilation. We return a tuple where the
  814. -- first element is a bool saying if we should recompile the object file
  815. -- and the second is maybe the interface file, where Nothng means to
  816. -- rebuild the interface file not use the exisitng one.
  817. checkOldIface
  818. :: HscEnv
  819. -> ModSummary
  820. -> SourceModified
  821. -> Maybe ModIface -- Old interface from compilation manager, if any
  822. -> IO (RecompileRequired, Maybe ModIface)
  823. checkOldIface hsc_env mod_summary source_modified maybe_iface
  824. = do let dflags = hsc_dflags hsc_env
  825. showPass dflags $
  826. "Checking old interface for " ++
  827. (showPpr dflags $ ms_mod mod_summary)
  828. initIfaceCheck hsc_env $
  829. check_old_iface hsc_env mod_summary source_modified maybe_iface
  830. check_old_iface
  831. :: HscEnv
  832. -> ModSummary
  833. -> SourceModified
  834. -> Maybe ModIface
  835. -> IfG (RecompileRequired, Maybe ModIface)
  836. check_old_iface hsc_env mod_summary src_modified maybe_iface
  837. = let dflags = hsc_dflags hsc_env
  838. getIface =
  839. case maybe_iface of
  840. Just _ -> do
  841. traceIf (text "We already have the old interface for" <+>
  842. ppr (ms_mod mod_summary))
  843. return maybe_iface
  844. Nothing -> loadIface
  845. loadIface = do
  846. let iface_path = msHiFilePath mod_summary
  847. read_result <- readIface (ms_mod mod_summary) iface_path
  848. case read_result of
  849. Failed err -> do
  850. traceIf (text "FYI: cannot read old interface file:" $$ nest 4 err)
  851. return Nothing
  852. Succeeded iface -> do
  853. traceIf (text "Read the interface file" <+> text iface_path)
  854. return $ Just iface
  855. src_changed
  856. | gopt Opt_ForceRecomp (hsc_dflags hsc_env) = True
  857. | SourceModified <- src_modified = True
  858. | otherwise = False
  859. in do
  860. when src_changed $
  861. traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off")
  862. case src_changed of
  863. -- If the source has changed and we're in interactive mode,
  864. -- avoid reading an interface; just return the one we might
  865. -- have been supplied with.
  866. True | not (isObjectTarget $ hscTarget dflags) ->
  867. return (MustCompile, maybe_iface)
  868. -- Try and read the old interface for the current module
  869. -- from the .hi file left from the last time we compiled it
  870. True -> do
  871. maybe_iface' <- getIface
  872. return (MustCompile, maybe_iface')
  873. False -> do
  874. maybe_iface' <- getIface
  875. case maybe_iface' of
  876. -- We can't retrieve the iface
  877. Nothing -> return (MustCompile, Nothing)
  878. -- We have got the old iface; check its versions
  879. -- even in the SourceUnmodifiedAndStable case we
  880. -- should check versions because some packages
  881. -- might have changed or gone away.
  882. Just iface -> checkVersions hsc_env mod_summary iface
  883. -- | Check if a module is still the same 'version'.
  884. --
  885. -- This function is called in the recompilation checker after we have
  886. -- determined that the module M being checked hasn't had any changes
  887. -- to its source file since we last compiled M. So at this point in general
  888. -- two things may have changed that mean we should recompile M:
  889. -- * The interface export by a dependency of M has changed.
  890. -- * The compiler flags specified this time for M have changed
  891. -- in a manner that is significant for recompilaiton.
  892. -- We return not just if we should recompile the object file but also
  893. -- if we should rebuild the interface file.
  894. checkVersions :: HscEnv
  895. -> ModSummary
  896. -> ModIface -- Old interface
  897. -> IfG (RecompileRequired, Maybe ModIface)
  898. checkVersions hsc_env mod_summary iface
  899. = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
  900. ppr (mi_module iface) <> colon)
  901. ; recomp <- checkFlagHash hsc_env iface
  902. ; if recompileRequired recomp then return (recomp, Nothing) else do {
  903. ; if getSigOf (hsc_dflags hsc_env) (moduleName (mi_module iface))
  904. /= mi_sig_of iface
  905. then return (RecompBecause "sig-of changed", Nothing) else do {
  906. ; recomp <- checkDependencies hsc_env mod_summary iface
  907. ; if recompileRequired recomp then return (recomp, Just iface) else do {
  908. -- Source code unchanged and no errors yet... carry on
  909. --
  910. -- First put the dependent-module info, read from the old
  911. -- interface, into the envt, so that when we look for
  912. -- interfaces we look for the right one (.hi or .hi-boot)
  913. --
  914. -- It's just temporary because either the usage check will succeed
  915. -- (in which case we are done with this module) or it'll fail (in which
  916. -- case we'll compile the module from scratch anyhow).
  917. --
  918. -- We do this regardless of compilation mode, although in --make mode
  919. -- all the dependent modules should be in the HPT already, so it's
  920. -- quite redundant
  921. ; updateEps_ $ \eps -> eps { eps_is_boot = udfmToUfm mod_deps }
  922. ; recomp <- checkList [checkModUsage this_pkg u | u <- mi_usages iface]
  923. ; return (recomp, Just iface)
  924. }}}}
  925. where
  926. this_pkg = thisPackage (hsc_dflags hsc_env)
  927. -- This is a bit of a hack really
  928. mod_deps :: DModuleNameEnv (ModuleName, IsBootInterface)
  929. mod_deps = mkModDeps (dep_mods (mi_deps iface))
  930. -- | Check the flags haven't changed
  931. checkFlagHash :: HscEnv -> ModIface -> IfG RecompileRequired
  932. checkFlagHash hsc_env iface = do
  933. let old_hash = mi_flag_hash iface
  934. new_hash <- liftIO $ fingerprintDynFlags (hsc_dflags hsc_env)
  935. (mi_module iface)
  936. putNameLiterally
  937. case old_hash == new_hash of
  938. True -> up_to_date (text "Module flags unchanged")
  939. False -> out_of_date_hash "flags changed"
  940. (text " Module flags have changed")
  941. old_hash new_hash
  942. -- If the direct imports of this module are resolved to targets that
  943. -- are not among the dependencies of the previous interface file,
  944. -- then we definitely need to recompile. This catches cases like
  945. -- - an exposed package has been upgraded
  946. -- - we are compiling with different package flags
  947. -- - a home module that was shadowing a package module has been removed
  948. -- - a new home module has been added that shadows a package module
  949. -- See bug #1372.
  950. --
  951. -- Returns True if recompilation is required.
  952. checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
  953. checkDependencies hsc_env summary iface
  954. = checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary))
  955. where
  956. prev_dep_mods = dep_mods (mi_deps iface)
  957. prev_dep_pkgs = dep_pkgs (mi_deps iface)
  958. this_pkg = thisPackage (hsc_dflags hsc_env)
  959. dep_missing (mb_pkg, L _ mod) = do
  960. find_res <- liftIO $ findImportedModule hsc_env mod (mb_pkg)
  961. let reason = moduleNameString mod ++ " changed"
  962. case find_res of
  963. Found _ mod
  964. | pkg == this_pkg
  965. -> if moduleName mod `notElem` map fst prev_dep_mods
  966. then do traceHiDiffs $
  967. text "imported module " <> quotes (ppr mod) <>
  968. text " not among previous dependencies"
  969. return (RecompBecause reason)
  970. else
  971. return UpToDate
  972. | otherwise
  973. -> if pkg `notElem` (map fst prev_dep_pkgs)
  974. then do traceHiDiffs $
  975. text "imported module " <> quotes (ppr mod) <>
  976. text " is from package " <> quotes (ppr pkg) <>
  977. text ", which is not among previous dependencies"
  978. return (RecompBecause reason)
  979. else
  980. return UpToDate
  981. where pkg = moduleUnitId mod
  982. _otherwise -> return (RecompBecause reason)
  983. needInterface :: Module -> (ModIface -> IfG RecompileRequired)
  984. -> IfG RecompileRequired
  985. needInterface mod continue
  986. = do -- Load the imported interface if possible
  987. let doc_str = sep [text "need version info for", ppr mod]
  988. traceHiDiffs (text "Checking usages for module" <+> ppr mod)
  989. mb_iface <- loadInterface doc_str mod ImportBySystem
  990. -- Load the interface, but don't complain on failure;
  991. -- Instead, get an Either back which we can test
  992. case mb_iface of
  993. Failed _ -> do
  994. traceHiDiffs (sep [text "Couldn't load interface for module",
  995. ppr mod])
  996. return MustCompile
  997. -- Couldn't find or parse a module mentioned in the
  998. -- old interface file. Don't complain: it might
  999. -- just be that the current module doesn't need that
  1000. -- import and it's been deleted
  1001. Succeeded iface -> continue iface
  1002. -- | Given the usage information extracted from the old
  1003. -- M.hi file for the module being compiled, figure out
  1004. -- whether M needs to be recompiled.
  1005. checkModUsage :: UnitId -> Usage -> IfG RecompileRequired
  1006. checkModUsage _this_pkg UsagePackageModule{
  1007. usg_mod = mod,
  1008. usg_mod_hash = old_mod_hash }
  1009. = needInterface mod $ \iface -> do
  1010. let reason = moduleNameString (moduleName mod) ++ " changed"
  1011. checkModuleFingerprint reason old_mod_hash (mi_mod_hash iface)
  1012. -- We only track the ABI hash of package modules, rather than
  1013. -- individual entity usages, so if the ABI hash changes we must
  1014. -- recompile. This is safe but may entail more recompilation when
  1015. -- a dependent package has changed.
  1016. checkModUsage this_pkg UsageHomeModule{
  1017. usg_mod_name = mod_name,
  1018. usg_mod_hash = old_mod_hash,
  1019. usg_exports = maybe_old_export_hash,
  1020. usg_entities = old_decl_hash }
  1021. = do
  1022. let mod = mkModule this_pkg mod_name
  1023. needInterface mod $ \iface -> do
  1024. let
  1025. new_mod_hash = mi_mod_hash iface
  1026. new_decl_hash = mi_hash_fn iface
  1027. new_export_hash = mi_exp_hash iface
  1028. reason = moduleNameString mod_name ++ " changed"
  1029. -- CHECK MODULE
  1030. recompile <- checkModuleFingerprint reason old_mod_hash new_mod_hash
  1031. if not (recompileRequired recompile)
  1032. then return UpToDate
  1033. else do
  1034. -- CHECK EXPORT LIST
  1035. checkMaybeHash reason maybe_old_export_hash new_export_hash
  1036. (text " Export list changed") $ do
  1037. -- CHECK ITEMS ONE BY ONE
  1038. recompile <- checkList [ checkEntityUsage reason new_decl_hash u
  1039. | u <- old_decl_has

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