PageRenderTime 33ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/compiler/iface/MkIface.lhs

https://github.com/luite/ghc
Haskell | 1864 lines | 1256 code | 254 blank | 354 comment | 55 complexity | 7c199006a747c421f3ffd16b12f6c782 MD5 | raw 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 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. mkUsedNames,
  11. mkDependencies,
  12. mkIface, -- Build a ModIface from a ModGuts,
  13. -- including computing version information
  14. mkIfaceTc,
  15. writeIfaceFile, -- Write the interface file
  16. checkOldIface, -- See if recompilation is required, by
  17. -- comparing version information
  18. RecompileRequired(..), recompileRequired,
  19. tyThingToIfaceDecl -- Converting things to their Iface equivalents
  20. ) where
  21. \end{code}
  22. -----------------------------------------------
  23. Recompilation checking
  24. -----------------------------------------------
  25. A complete description of how recompilation checking works can be
  26. found in the wiki commentary:
  27. http://hackage.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
  28. Please read the above page for a top-down description of how this all
  29. works. Notes below cover specific issues related to the implementation.
  30. Basic idea:
  31. * In the mi_usages information in an interface, we record the
  32. fingerprint of each free variable of the module
  33. * In mkIface, we compute the fingerprint of each exported thing A.f.
  34. For each external thing that A.f refers to, we include the fingerprint
  35. of the external reference when computing the fingerprint of A.f. So
  36. if anything that A.f depends on changes, then A.f's fingerprint will
  37. change.
  38. Also record any dependent files added with addDependentFile.
  39. In the future record any #include usages.
  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. \begin{code}
  43. #include "HsVersions.h"
  44. import IfaceSyn
  45. import LoadIface
  46. import FlagChecker
  47. import Id
  48. import IdInfo
  49. import Demand
  50. import Coercion( tidyCo )
  51. import Annotations
  52. import CoreSyn
  53. import CoreFVs
  54. import Class
  55. import Kind
  56. import TyCon
  57. import CoAxiom
  58. import DataCon
  59. import Type
  60. import TcType
  61. import InstEnv
  62. import FamInstEnv
  63. import TcRnMonad
  64. import HsSyn
  65. import HscTypes
  66. import Finder
  67. import DynFlags
  68. import VarEnv
  69. import VarSet
  70. import Var
  71. import Name
  72. import Avail
  73. import RdrName
  74. import NameEnv
  75. import NameSet
  76. import Module
  77. import BinIface
  78. import ErrUtils
  79. import Digraph
  80. import SrcLoc
  81. import Outputable
  82. import BasicTypes hiding ( SuccessFlag(..) )
  83. import UniqFM
  84. import Unique
  85. import Util hiding ( eqListBy )
  86. import FastString
  87. import Maybes
  88. import ListSetOps
  89. import Binary
  90. import Fingerprint
  91. import Bag
  92. import Exception
  93. import Control.Monad
  94. import Data.Function
  95. import Data.List
  96. import Data.Map (Map)
  97. import qualified Data.Map as Map
  98. import Data.Ord
  99. import Data.IORef
  100. import System.Directory
  101. import System.FilePath
  102. \end{code}
  103. %************************************************************************
  104. %* *
  105. \subsection{Completing an interface}
  106. %* *
  107. %************************************************************************
  108. \begin{code}
  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 (Messages,
  114. Maybe (ModIface, -- The new one
  115. Bool)) -- True <=> there was an old Iface, and the
  116. -- new one is identical, so no need
  117. -- to write it
  118. mkIface hsc_env maybe_old_fingerprint mod_details
  119. ModGuts{ mg_module = this_mod,
  120. mg_boot = is_boot,
  121. mg_used_names = used_names,
  122. mg_used_th = used_th,
  123. mg_deps = deps,
  124. mg_dir_imps = dir_imp_mods,
  125. mg_rdr_env = rdr_env,
  126. mg_fix_env = fix_env,
  127. mg_warns = warns,
  128. mg_hpc_info = hpc_info,
  129. mg_safe_haskell = safe_mode,
  130. mg_trust_pkg = self_trust,
  131. mg_dependent_files = dependent_files
  132. }
  133. = mkIface_ hsc_env maybe_old_fingerprint
  134. this_mod is_boot used_names used_th deps rdr_env fix_env
  135. warns hpc_info dir_imp_mods self_trust dependent_files
  136. safe_mode mod_details
  137. -- | make an interface from the results of typechecking only. Useful
  138. -- for non-optimising compilation, or where we aren't generating any
  139. -- object code at all ('HscNothing').
  140. mkIfaceTc :: HscEnv
  141. -> Maybe Fingerprint -- The old fingerprint, if we have it
  142. -> SafeHaskellMode -- The safe haskell mode
  143. -> ModDetails -- gotten from mkBootModDetails, probably
  144. -> TcGblEnv -- Usages, deprecations, etc
  145. -> IO (Messages, Maybe (ModIface, Bool))
  146. mkIfaceTc hsc_env maybe_old_fingerprint safe_mode mod_details
  147. tc_result@TcGblEnv{ tcg_mod = this_mod,
  148. tcg_src = hsc_src,
  149. tcg_imports = imports,
  150. tcg_rdr_env = rdr_env,
  151. tcg_fix_env = fix_env,
  152. tcg_warns = warns,
  153. tcg_hpc = other_hpc_info,
  154. tcg_th_splice_used = tc_splice_used,
  155. tcg_dependent_files = dependent_files
  156. }
  157. = do
  158. let used_names = mkUsedNames tc_result
  159. deps <- mkDependencies tc_result
  160. let hpc_info = emptyHpcInfo other_hpc_info
  161. used_th <- readIORef tc_splice_used
  162. dep_files <- (readIORef dependent_files)
  163. mkIface_ hsc_env maybe_old_fingerprint
  164. this_mod (isHsBoot hsc_src) used_names used_th deps rdr_env
  165. fix_env warns hpc_info (imp_mods imports)
  166. (imp_trust_own_pkg imports) dep_files safe_mode mod_details
  167. mkUsedNames :: TcGblEnv -> NameSet
  168. mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
  169. -- | Extract information from the rename and typecheck phases to produce
  170. -- a dependencies information for the module being compiled.
  171. mkDependencies :: TcGblEnv -> IO Dependencies
  172. mkDependencies
  173. TcGblEnv{ tcg_mod = mod,
  174. tcg_imports = imports,
  175. tcg_th_used = th_var
  176. }
  177. = do
  178. -- Template Haskell used?
  179. th_used <- readIORef th_var
  180. let dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
  181. -- M.hi-boot can be in the imp_dep_mods, but we must remove
  182. -- it before recording the modules on which this one depends!
  183. -- (We want to retain M.hi-boot in imp_dep_mods so that
  184. -- loadHiBootInterface can see if M's direct imports depend
  185. -- on M.hi-boot, and hence that we should do the hi-boot consistency
  186. -- check.)
  187. pkgs | th_used = insertList thPackageId (imp_dep_pkgs imports)
  188. | otherwise = imp_dep_pkgs imports
  189. -- Set the packages required to be Safe according to Safe Haskell.
  190. -- See Note [RnNames . Tracking Trust Transitively]
  191. sorted_pkgs = sortBy stablePackageIdCmp pkgs
  192. trust_pkgs = imp_trust_pkgs imports
  193. dep_pkgs' = map (\x -> (x, x `elem` trust_pkgs)) sorted_pkgs
  194. return Deps { dep_mods = sortBy (stableModuleNameCmp `on` fst) dep_mods,
  195. dep_pkgs = dep_pkgs',
  196. dep_orphs = sortBy stableModuleCmp (imp_orphs imports),
  197. dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
  198. -- sort to get into canonical order
  199. -- NB. remember to use lexicographic ordering
  200. mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> IsBootInterface
  201. -> NameSet -> Bool -> Dependencies -> GlobalRdrEnv
  202. -> NameEnv FixItem -> Warnings -> HpcInfo
  203. -> ImportedMods -> Bool
  204. -> [FilePath]
  205. -> SafeHaskellMode
  206. -> ModDetails
  207. -> IO (Messages, Maybe (ModIface, Bool))
  208. mkIface_ hsc_env maybe_old_fingerprint
  209. this_mod is_boot used_names used_th deps rdr_env fix_env src_warns
  210. hpc_info dir_imp_mods pkg_trust_req dependent_files safe_mode
  211. ModDetails{ md_insts = insts,
  212. md_fam_insts = fam_insts,
  213. md_rules = rules,
  214. md_anns = anns,
  215. md_vect_info = vect_info,
  216. md_types = type_env,
  217. md_exports = exports }
  218. -- NB: notice that mkIface does not look at the bindings
  219. -- only at the TypeEnv. The previous Tidy phase has
  220. -- put exactly the info into the TypeEnv that we want
  221. -- to expose in the interface
  222. = do { usages <- mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
  223. ; let { entities = typeEnvElts type_env ;
  224. decls = [ tyThingToIfaceDecl entity
  225. | entity <- entities,
  226. let name = getName entity,
  227. not (isImplicitTyThing entity),
  228. -- No implicit Ids and class tycons in the interface file
  229. not (isWiredInName name),
  230. -- Nor wired-in things; the compiler knows about them anyhow
  231. nameIsLocalOrFrom this_mod name ]
  232. -- Sigh: see Note [Root-main Id] in TcRnDriver
  233. ; fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
  234. ; warns = src_warns
  235. ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
  236. ; iface_insts = map instanceToIfaceInst insts
  237. ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
  238. ; iface_vect_info = flattenVectInfo vect_info
  239. ; trust_info = setSafeMode safe_mode
  240. ; intermediate_iface = ModIface {
  241. mi_module = this_mod,
  242. mi_boot = is_boot,
  243. mi_deps = deps,
  244. mi_usages = usages,
  245. mi_exports = mkIfaceExports exports,
  246. -- Sort these lexicographically, so that
  247. -- the result is stable across compilations
  248. mi_insts = sortBy cmp_inst iface_insts,
  249. mi_fam_insts = sortBy cmp_fam_inst iface_fam_insts,
  250. mi_rules = sortBy cmp_rule iface_rules,
  251. mi_vect_info = iface_vect_info,
  252. mi_fixities = fixities,
  253. mi_warns = warns,
  254. mi_anns = mkIfaceAnnotations anns,
  255. mi_globals = maybeGlobalRdrEnv rdr_env,
  256. -- Left out deliberately: filled in by addFingerprints
  257. mi_iface_hash = fingerprint0,
  258. mi_mod_hash = fingerprint0,
  259. mi_flag_hash = fingerprint0,
  260. mi_exp_hash = fingerprint0,
  261. mi_used_th = used_th,
  262. mi_orphan_hash = fingerprint0,
  263. mi_orphan = False, -- Always set by addFingerprints, but
  264. -- it's a strict field, so we can't omit it.
  265. mi_finsts = False, -- Ditto
  266. mi_decls = deliberatelyOmitted "decls",
  267. mi_hash_fn = deliberatelyOmitted "hash_fn",
  268. mi_hpc = isHpcUsed hpc_info,
  269. mi_trust = trust_info,
  270. mi_trust_pkg = pkg_trust_req,
  271. -- And build the cached values
  272. mi_warn_fn = mkIfaceWarnCache warns,
  273. mi_fix_fn = mkIfaceFixCache fixities }
  274. }
  275. ; (new_iface, no_change_at_all)
  276. <- {-# SCC "versioninfo" #-}
  277. addFingerprints hsc_env maybe_old_fingerprint
  278. intermediate_iface decls
  279. -- Warn about orphans
  280. ; let warn_orphs = wopt Opt_WarnOrphans dflags
  281. warn_auto_orphs = wopt Opt_WarnAutoOrphans dflags
  282. orph_warnings --- Laziness means no work done unless -fwarn-orphans
  283. | warn_orphs || warn_auto_orphs = rule_warns `unionBags` inst_warns
  284. | otherwise = emptyBag
  285. errs_and_warns = (orph_warnings, emptyBag)
  286. unqual = mkPrintUnqualified dflags rdr_env
  287. inst_warns = listToBag [ instOrphWarn dflags unqual d
  288. | (d,i) <- insts `zip` iface_insts
  289. , isNothing (ifInstOrph i) ]
  290. rule_warns = listToBag [ ruleOrphWarn dflags unqual this_mod r
  291. | r <- iface_rules
  292. , isNothing (ifRuleOrph r)
  293. , if ifRuleAuto r then warn_auto_orphs
  294. else warn_orphs ]
  295. ; if errorsFound dflags errs_and_warns
  296. then return ( errs_and_warns, Nothing )
  297. else do {
  298. -- Debug printing
  299. ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
  300. (pprModIface new_iface)
  301. -- bug #1617: on reload we weren't updating the PrintUnqualified
  302. -- correctly. This stems from the fact that the interface had
  303. -- not changed, so addFingerprints returns the old ModIface
  304. -- with the old GlobalRdrEnv (mi_globals).
  305. ; let final_iface = new_iface{ mi_globals = maybeGlobalRdrEnv rdr_env }
  306. ; return (errs_and_warns, Just (final_iface, no_change_at_all)) }}
  307. where
  308. cmp_rule = comparing ifRuleName
  309. -- Compare these lexicographically by OccName, *not* by unique,
  310. -- because the latter is not stable across compilations:
  311. cmp_inst = comparing (nameOccName . ifDFun)
  312. cmp_fam_inst = comparing (nameOccName . ifFamInstTcName)
  313. dflags = hsc_dflags hsc_env
  314. -- We only fill in mi_globals if the module was compiled to byte
  315. -- code. Otherwise, the compiler may not have retained all the
  316. -- top-level bindings and they won't be in the TypeEnv (see
  317. -- Desugar.addExportFlagsAndRules). The mi_globals field is used
  318. -- by GHCi to decide whether the module has its full top-level
  319. -- scope available. (#5534)
  320. maybeGlobalRdrEnv :: GlobalRdrEnv -> Maybe GlobalRdrEnv
  321. maybeGlobalRdrEnv rdr_env
  322. | targetRetainsAllBindings (hscTarget dflags) = Just rdr_env
  323. | otherwise = Nothing
  324. deliberatelyOmitted :: String -> a
  325. deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
  326. ifFamInstTcName = ifFamInstFam
  327. flattenVectInfo (VectInfo { vectInfoVar = vVar
  328. , vectInfoTyCon = vTyCon
  329. , vectInfoParallelVars = vParallelVars
  330. , vectInfoParallelTyCons = vParallelTyCons
  331. }) =
  332. IfaceVectInfo
  333. { ifaceVectInfoVar = [Var.varName v | (v, _ ) <- varEnvElts vVar]
  334. , ifaceVectInfoTyCon = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t /= t_v]
  335. , ifaceVectInfoTyConReuse = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t == t_v]
  336. , ifaceVectInfoParallelVars = [Var.varName v | v <- varSetElems vParallelVars]
  337. , ifaceVectInfoParallelTyCons = nameSetToList vParallelTyCons
  338. }
  339. -----------------------------
  340. writeIfaceFile :: DynFlags -> FilePath -> ModIface -> IO ()
  341. writeIfaceFile dflags hi_file_path new_iface
  342. = do createDirectoryIfMissing True (takeDirectory hi_file_path)
  343. writeBinIface dflags hi_file_path new_iface
  344. -- -----------------------------------------------------------------------------
  345. -- Look up parents and versions of Names
  346. -- This is like a global version of the mi_hash_fn field in each ModIface.
  347. -- Given a Name, it finds the ModIface, and then uses mi_hash_fn to get
  348. -- the parent and version info.
  349. mkHashFun
  350. :: HscEnv -- needed to look up versions
  351. -> ExternalPackageState -- ditto
  352. -> (Name -> Fingerprint)
  353. mkHashFun hsc_env eps
  354. = \name ->
  355. let
  356. mod = ASSERT2( isExternalName name, ppr name ) nameModule name
  357. occ = nameOccName name
  358. iface = lookupIfaceByModule (hsc_dflags hsc_env) hpt pit mod `orElse`
  359. pprPanic "lookupVers2" (ppr mod <+> ppr occ)
  360. in
  361. snd (mi_hash_fn iface occ `orElse`
  362. pprPanic "lookupVers1" (ppr mod <+> ppr occ))
  363. where
  364. hpt = hsc_HPT hsc_env
  365. pit = eps_PIT eps
  366. -- ---------------------------------------------------------------------------
  367. -- Compute fingerprints for the interface
  368. addFingerprints
  369. :: HscEnv
  370. -> Maybe Fingerprint -- the old fingerprint, if any
  371. -> ModIface -- The new interface (lacking decls)
  372. -> [IfaceDecl] -- The new decls
  373. -> IO (ModIface, -- Updated interface
  374. Bool) -- True <=> no changes at all;
  375. -- no need to write Iface
  376. addFingerprints hsc_env mb_old_fingerprint iface0 new_decls
  377. = do
  378. eps <- hscEPS hsc_env
  379. let
  380. -- The ABI of a declaration represents everything that is made
  381. -- visible about the declaration that a client can depend on.
  382. -- see IfaceDeclABI below.
  383. declABI :: IfaceDecl -> IfaceDeclABI
  384. declABI decl = (this_mod, decl, extras)
  385. where extras = declExtras fix_fn non_orph_rules non_orph_insts
  386. non_orph_fis decl
  387. edges :: [(IfaceDeclABI, Unique, [Unique])]
  388. edges = [ (abi, getUnique (ifName decl), out)
  389. | decl <- new_decls
  390. , let abi = declABI decl
  391. , let out = localOccs $ freeNamesDeclABI abi
  392. ]
  393. name_module n = ASSERT2( isExternalName n, ppr n ) nameModule n
  394. localOccs = map (getUnique . getParent . getOccName)
  395. . filter ((== this_mod) . name_module)
  396. . nameSetToList
  397. where getParent occ = lookupOccEnv parent_map occ `orElse` occ
  398. -- maps OccNames to their parents in the current module.
  399. -- e.g. a reference to a constructor must be turned into a reference
  400. -- to the TyCon for the purposes of calculating dependencies.
  401. parent_map :: OccEnv OccName
  402. parent_map = foldr extend emptyOccEnv new_decls
  403. where extend d env =
  404. extendOccEnvList env [ (b,n) | b <- ifaceDeclImplicitBndrs d ]
  405. where n = ifName d
  406. -- strongly-connected groups of declarations, in dependency order
  407. groups = stronglyConnCompFromEdgedVertices edges
  408. global_hash_fn = mkHashFun hsc_env eps
  409. -- how to output Names when generating the data to fingerprint.
  410. -- Here we want to output the fingerprint for each top-level
  411. -- Name, whether it comes from the current module or another
  412. -- module. In this way, the fingerprint for a declaration will
  413. -- change if the fingerprint for anything it refers to (transitively)
  414. -- changes.
  415. mk_put_name :: (OccEnv (OccName,Fingerprint))
  416. -> BinHandle -> Name -> IO ()
  417. mk_put_name local_env bh name
  418. | isWiredInName name = putNameLiterally bh name
  419. -- wired-in names don't have fingerprints
  420. | otherwise
  421. = ASSERT2( isExternalName name, ppr name )
  422. let hash | nameModule name /= this_mod = global_hash_fn name
  423. | otherwise = snd (lookupOccEnv local_env (getOccName name)
  424. `orElse` pprPanic "urk! lookup local fingerprint"
  425. (ppr name)) -- (undefined,fingerprint0))
  426. -- This panic indicates that we got the dependency
  427. -- analysis wrong, because we needed a fingerprint for
  428. -- an entity that wasn't in the environment. To debug
  429. -- it, turn the panic into a trace, uncomment the
  430. -- pprTraces below, run the compile again, and inspect
  431. -- the output and the generated .hi file with
  432. -- --show-iface.
  433. in put_ bh hash
  434. -- take a strongly-connected group of declarations and compute
  435. -- its fingerprint.
  436. fingerprint_group :: (OccEnv (OccName,Fingerprint),
  437. [(Fingerprint,IfaceDecl)])
  438. -> SCC IfaceDeclABI
  439. -> IO (OccEnv (OccName,Fingerprint),
  440. [(Fingerprint,IfaceDecl)])
  441. fingerprint_group (local_env, decls_w_hashes) (AcyclicSCC abi)
  442. = do let hash_fn = mk_put_name local_env
  443. decl = abiDecl abi
  444. -- pprTrace "fingerprinting" (ppr (ifName decl) ) $ do
  445. hash <- computeFingerprint hash_fn abi
  446. env' <- extend_hash_env local_env (hash,decl)
  447. return (env', (hash,decl) : decls_w_hashes)
  448. fingerprint_group (local_env, decls_w_hashes) (CyclicSCC abis)
  449. = do let decls = map abiDecl abis
  450. local_env1 <- foldM extend_hash_env local_env
  451. (zip (repeat fingerprint0) decls)
  452. let hash_fn = mk_put_name local_env1
  453. -- pprTrace "fingerprinting" (ppr (map ifName decls) ) $ do
  454. let stable_abis = sortBy cmp_abiNames abis
  455. -- put the cycle in a canonical order
  456. hash <- computeFingerprint hash_fn stable_abis
  457. let pairs = zip (repeat hash) decls
  458. local_env2 <- foldM extend_hash_env local_env pairs
  459. return (local_env2, pairs ++ decls_w_hashes)
  460. -- we have fingerprinted the whole declaration, but we now need
  461. -- to assign fingerprints to all the OccNames that it binds, to
  462. -- use when referencing those OccNames in later declarations.
  463. --
  464. extend_hash_env :: OccEnv (OccName,Fingerprint)
  465. -> (Fingerprint,IfaceDecl)
  466. -> IO (OccEnv (OccName,Fingerprint))
  467. extend_hash_env env0 (hash,d) = do
  468. return (foldr (\(b,fp) env -> extendOccEnv env b (b,fp)) env0
  469. (ifaceDeclFingerprints hash d))
  470. --
  471. (local_env, decls_w_hashes) <-
  472. foldM fingerprint_group (emptyOccEnv, []) groups
  473. -- when calculating fingerprints, we always need to use canonical
  474. -- ordering for lists of things. In particular, the mi_deps has various
  475. -- lists of modules and suchlike, so put these all in canonical order:
  476. let sorted_deps = sortDependencies (mi_deps iface0)
  477. -- the export hash of a module depends on the orphan hashes of the
  478. -- orphan modules below us in the dependency tree. This is the way
  479. -- that changes in orphans get propagated all the way up the
  480. -- dependency tree. We only care about orphan modules in the current
  481. -- package, because changes to orphans outside this package will be
  482. -- tracked by the usage on the ABI hash of package modules that we import.
  483. let orph_mods = filter ((== this_pkg) . modulePackageId)
  484. $ dep_orphs sorted_deps
  485. dep_orphan_hashes <- getOrphanHashes hsc_env orph_mods
  486. orphan_hash <- computeFingerprint (mk_put_name local_env)
  487. (map ifDFun orph_insts, orph_rules, orph_fis)
  488. -- the export list hash doesn't depend on the fingerprints of
  489. -- the Names it mentions, only the Names themselves, hence putNameLiterally.
  490. export_hash <- computeFingerprint putNameLiterally
  491. (mi_exports iface0,
  492. orphan_hash,
  493. dep_orphan_hashes,
  494. dep_pkgs (mi_deps iface0),
  495. -- dep_pkgs: see "Package Version Changes" on
  496. -- wiki/Commentary/Compiler/RecompilationAvoidance
  497. mi_trust iface0)
  498. -- Make sure change of Safe Haskell mode causes recomp.
  499. -- put the declarations in a canonical order, sorted by OccName
  500. let sorted_decls = Map.elems $ Map.fromList $
  501. [(ifName d, e) | e@(_, d) <- decls_w_hashes]
  502. -- the flag hash depends on:
  503. -- - (some of) dflags
  504. -- it returns two hashes, one that shouldn't change
  505. -- the abi hash and one that should
  506. flag_hash <- fingerprintDynFlags dflags this_mod putNameLiterally
  507. -- the ABI hash depends on:
  508. -- - decls
  509. -- - export list
  510. -- - orphans
  511. -- - deprecations
  512. -- - vect info
  513. -- - flag abi hash
  514. mod_hash <- computeFingerprint putNameLiterally
  515. (map fst sorted_decls,
  516. export_hash, -- includes orphan_hash
  517. mi_warns iface0,
  518. mi_vect_info iface0)
  519. -- The interface hash depends on:
  520. -- - the ABI hash, plus
  521. -- - usages
  522. -- - deps
  523. -- - hpc
  524. iface_hash <- computeFingerprint putNameLiterally
  525. (mod_hash,
  526. mi_usages iface0,
  527. sorted_deps,
  528. mi_hpc iface0)
  529. let
  530. no_change_at_all = Just iface_hash == mb_old_fingerprint
  531. final_iface = iface0 {
  532. mi_mod_hash = mod_hash,
  533. mi_iface_hash = iface_hash,
  534. mi_exp_hash = export_hash,
  535. mi_orphan_hash = orphan_hash,
  536. mi_flag_hash = flag_hash,
  537. mi_orphan = not ( null orph_rules
  538. && null orph_insts
  539. && null orph_fis
  540. && isNoIfaceVectInfo (mi_vect_info iface0)),
  541. mi_finsts = not . null $ mi_fam_insts iface0,
  542. mi_decls = sorted_decls,
  543. mi_hash_fn = lookupOccEnv local_env }
  544. --
  545. return (final_iface, no_change_at_all)
  546. where
  547. this_mod = mi_module iface0
  548. dflags = hsc_dflags hsc_env
  549. this_pkg = thisPackage dflags
  550. (non_orph_insts, orph_insts) = mkOrphMap ifInstOrph (mi_insts iface0)
  551. (non_orph_rules, orph_rules) = mkOrphMap ifRuleOrph (mi_rules iface0)
  552. (non_orph_fis, orph_fis) = mkOrphMap ifFamInstOrph (mi_fam_insts iface0)
  553. fix_fn = mi_fix_fn iface0
  554. getOrphanHashes :: HscEnv -> [Module] -> IO [Fingerprint]
  555. getOrphanHashes hsc_env mods = do
  556. eps <- hscEPS hsc_env
  557. let
  558. hpt = hsc_HPT hsc_env
  559. pit = eps_PIT eps
  560. dflags = hsc_dflags hsc_env
  561. get_orph_hash mod =
  562. case lookupIfaceByModule dflags hpt pit mod of
  563. Nothing -> pprPanic "moduleOrphanHash" (ppr mod)
  564. Just iface -> mi_orphan_hash iface
  565. --
  566. return (map get_orph_hash mods)
  567. sortDependencies :: Dependencies -> Dependencies
  568. sortDependencies d
  569. = Deps { dep_mods = sortBy (compare `on` (moduleNameFS.fst)) (dep_mods d),
  570. dep_pkgs = sortBy (stablePackageIdCmp `on` fst) (dep_pkgs d),
  571. dep_orphs = sortBy stableModuleCmp (dep_orphs d),
  572. dep_finsts = sortBy stableModuleCmp (dep_finsts d) }
  573. \end{code}
  574. %************************************************************************
  575. %* *
  576. The ABI of an IfaceDecl
  577. %* *
  578. %************************************************************************
  579. Note [The ABI of an IfaceDecl]
  580. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  581. The ABI of a declaration consists of:
  582. (a) the full name of the identifier (inc. module and package,
  583. because these are used to construct the symbol name by which
  584. the identifier is known externally).
  585. (b) the declaration itself, as exposed to clients. That is, the
  586. definition of an Id is included in the fingerprint only if
  587. it is made available as as unfolding in the interface.
  588. (c) the fixity of the identifier
  589. (d) for Ids: rules
  590. (e) for classes: instances, fixity & rules for methods
  591. (f) for datatypes: instances, fixity & rules for constrs
  592. Items (c)-(f) are not stored in the IfaceDecl, but instead appear
  593. elsewhere in the interface file. But they are *fingerprinted* with
  594. the declaration itself. This is done by grouping (c)-(f) in IfaceDeclExtras,
  595. and fingerprinting that as part of the declaration.
  596. \begin{code}
  597. type IfaceDeclABI = (Module, IfaceDecl, IfaceDeclExtras)
  598. data IfaceDeclExtras
  599. = IfaceIdExtras Fixity [IfaceRule]
  600. | IfaceDataExtras
  601. Fixity -- Fixity of the tycon itself
  602. [IfaceInstABI] -- Local class and family instances of this tycon
  603. -- See Note [Orphans] in IfaceSyn
  604. [(Fixity,[IfaceRule])] -- For each construcotr, fixity and RULES
  605. | IfaceClassExtras
  606. Fixity -- Fixity of the class itself
  607. [IfaceInstABI] -- Local instances of this class *or*
  608. -- of its associated data types
  609. -- See Note [Orphans] in IfaceSyn
  610. [(Fixity,[IfaceRule])] -- For each class method, fixity and RULES
  611. | IfaceSynExtras Fixity [IfaceInstABI]
  612. | IfaceOtherDeclExtras
  613. -- When hashing a class or family instance, we hash only the
  614. -- DFunId or CoAxiom, because that depends on all the
  615. -- information about the instance.
  616. --
  617. type IfaceInstABI = IfExtName -- Name of DFunId or CoAxiom that is evidence for the instance
  618. abiDecl :: IfaceDeclABI -> IfaceDecl
  619. abiDecl (_, decl, _) = decl
  620. cmp_abiNames :: IfaceDeclABI -> IfaceDeclABI -> Ordering
  621. cmp_abiNames abi1 abi2 = ifName (abiDecl abi1) `compare`
  622. ifName (abiDecl abi2)
  623. freeNamesDeclABI :: IfaceDeclABI -> NameSet
  624. freeNamesDeclABI (_mod, decl, extras) =
  625. freeNamesIfDecl decl `unionNameSets` freeNamesDeclExtras extras
  626. freeNamesDeclExtras :: IfaceDeclExtras -> NameSet
  627. freeNamesDeclExtras (IfaceIdExtras _ rules)
  628. = unionManyNameSets (map freeNamesIfRule rules)
  629. freeNamesDeclExtras (IfaceDataExtras _ insts subs)
  630. = unionManyNameSets (mkNameSet insts : map freeNamesSub subs)
  631. freeNamesDeclExtras (IfaceClassExtras _ insts subs)
  632. = unionManyNameSets (mkNameSet insts : map freeNamesSub subs)
  633. freeNamesDeclExtras (IfaceSynExtras _ insts)
  634. = mkNameSet insts
  635. freeNamesDeclExtras IfaceOtherDeclExtras
  636. = emptyNameSet
  637. freeNamesSub :: (Fixity,[IfaceRule]) -> NameSet
  638. freeNamesSub (_,rules) = unionManyNameSets (map freeNamesIfRule rules)
  639. instance Outputable IfaceDeclExtras where
  640. ppr IfaceOtherDeclExtras = empty
  641. ppr (IfaceIdExtras fix rules) = ppr_id_extras fix rules
  642. ppr (IfaceSynExtras fix finsts) = vcat [ppr fix, ppr finsts]
  643. ppr (IfaceDataExtras fix insts stuff) = vcat [ppr fix, ppr_insts insts,
  644. ppr_id_extras_s stuff]
  645. ppr (IfaceClassExtras fix insts stuff) = vcat [ppr fix, ppr_insts insts,
  646. ppr_id_extras_s stuff]
  647. ppr_insts :: [IfaceInstABI] -> SDoc
  648. ppr_insts _ = ptext (sLit "<insts>")
  649. ppr_id_extras_s :: [(Fixity, [IfaceRule])] -> SDoc
  650. ppr_id_extras_s stuff = vcat [ppr_id_extras f r | (f,r)<- stuff]
  651. ppr_id_extras :: Fixity -> [IfaceRule] -> SDoc
  652. ppr_id_extras fix rules = ppr fix $$ vcat (map ppr rules)
  653. -- This instance is used only to compute fingerprints
  654. instance Binary IfaceDeclExtras where
  655. get _bh = panic "no get for IfaceDeclExtras"
  656. put_ bh (IfaceIdExtras fix rules) = do
  657. putByte bh 1; put_ bh fix; put_ bh rules
  658. put_ bh (IfaceDataExtras fix insts cons) = do
  659. putByte bh 2; put_ bh fix; put_ bh insts; put_ bh cons
  660. put_ bh (IfaceClassExtras fix insts methods) = do
  661. putByte bh 3; put_ bh fix; put_ bh insts; put_ bh methods
  662. put_ bh (IfaceSynExtras fix finsts) = do
  663. putByte bh 4; put_ bh fix; put_ bh finsts
  664. put_ bh IfaceOtherDeclExtras = do
  665. putByte bh 5
  666. declExtras :: (OccName -> Fixity)
  667. -> OccEnv [IfaceRule]
  668. -> OccEnv [IfaceClsInst]
  669. -> OccEnv [IfaceFamInst]
  670. -> IfaceDecl
  671. -> IfaceDeclExtras
  672. declExtras fix_fn rule_env inst_env fi_env decl
  673. = case decl of
  674. IfaceId{} -> IfaceIdExtras (fix_fn n)
  675. (lookupOccEnvL rule_env n)
  676. IfaceData{ifCons=cons} ->
  677. IfaceDataExtras (fix_fn n)
  678. (map ifFamInstAxiom (lookupOccEnvL fi_env n) ++
  679. map ifDFun (lookupOccEnvL inst_env n))
  680. (map (id_extras . ifConOcc) (visibleIfConDecls cons))
  681. IfaceClass{ifSigs=sigs, ifATs=ats} ->
  682. IfaceClassExtras (fix_fn n)
  683. (map ifDFun $ (concatMap at_extras ats)
  684. ++ lookupOccEnvL inst_env n)
  685. -- Include instances of the associated types
  686. -- as well as instances of the class (Trac #5147)
  687. [id_extras op | IfaceClassOp op _ _ <- sigs]
  688. IfaceSyn{} -> IfaceSynExtras (fix_fn n)
  689. (map ifFamInstAxiom (lookupOccEnvL fi_env n))
  690. _other -> IfaceOtherDeclExtras
  691. where
  692. n = ifName decl
  693. id_extras occ = (fix_fn occ, lookupOccEnvL rule_env occ)
  694. at_extras (IfaceAT decl _) = lookupOccEnvL inst_env (ifName decl)
  695. lookupOccEnvL :: OccEnv [v] -> OccName -> [v]
  696. lookupOccEnvL env k = lookupOccEnv env k `orElse` []
  697. -- used when we want to fingerprint a structure without depending on the
  698. -- fingerprints of external Names that it refers to.
  699. putNameLiterally :: BinHandle -> Name -> IO ()
  700. putNameLiterally bh name = ASSERT( isExternalName name )
  701. do { put_ bh $! nameModule name
  702. ; put_ bh $! nameOccName name }
  703. {-
  704. -- for testing: use the md5sum command to generate fingerprints and
  705. -- compare the results against our built-in version.
  706. fp' <- oldMD5 dflags bh
  707. if fp /= fp' then pprPanic "computeFingerprint" (ppr fp <+> ppr fp')
  708. else return fp
  709. oldMD5 dflags bh = do
  710. tmp <- newTempName dflags "bin"
  711. writeBinMem bh tmp
  712. tmp2 <- newTempName dflags "md5"
  713. let cmd = "md5sum " ++ tmp ++ " >" ++ tmp2
  714. r <- system cmd
  715. case r of
  716. ExitFailure _ -> throwGhcExceptionIO (PhaseFailed cmd r)
  717. ExitSuccess -> do
  718. hash_str <- readFile tmp2
  719. return $! readHexFingerprint hash_str
  720. -}
  721. instOrphWarn :: DynFlags -> PrintUnqualified -> ClsInst -> WarnMsg
  722. instOrphWarn dflags unqual inst
  723. = mkWarnMsg dflags (getSrcSpan inst) unqual $
  724. hang (ptext (sLit "Orphan instance:")) 2 (pprInstanceHdr inst)
  725. ruleOrphWarn :: DynFlags -> PrintUnqualified -> Module -> IfaceRule -> WarnMsg
  726. ruleOrphWarn dflags unqual mod rule
  727. = mkWarnMsg dflags silly_loc unqual $
  728. ptext (sLit "Orphan rule:") <+> ppr rule
  729. where
  730. silly_loc = srcLocSpan (mkSrcLoc (moduleNameFS (moduleName mod)) 1 1)
  731. -- We don't have a decent SrcSpan for a Rule, not even the CoreRule
  732. -- Could readily be fixed by adding a SrcSpan to CoreRule, if we wanted to
  733. ----------------------
  734. -- mkOrphMap partitions instance decls or rules into
  735. -- (a) an OccEnv for ones that are not orphans,
  736. -- mapping the local OccName to a list of its decls
  737. -- (b) a list of orphan decls
  738. mkOrphMap :: (decl -> Maybe OccName) -- (Just occ) for a non-orphan decl, keyed by occ
  739. -- Nothing for an orphan decl
  740. -> [decl] -- Sorted into canonical order
  741. -> (OccEnv [decl], -- Non-orphan decls associated with their key;
  742. -- each sublist in canonical order
  743. [decl]) -- Orphan decls; in canonical order
  744. mkOrphMap get_key decls
  745. = foldl go (emptyOccEnv, []) decls
  746. where
  747. go (non_orphs, orphs) d
  748. | Just occ <- get_key d
  749. = (extendOccEnv_Acc (:) singleton non_orphs occ d, orphs)
  750. | otherwise = (non_orphs, d:orphs)
  751. \end{code}
  752. %************************************************************************
  753. %* *
  754. Keeping track of what we've slurped, and fingerprints
  755. %* *
  756. %************************************************************************
  757. \begin{code}
  758. mkUsageInfo :: HscEnv -> Module -> ImportedMods -> NameSet -> [FilePath] -> IO [Usage]
  759. mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
  760. = do { eps <- hscEPS hsc_env
  761. ; mtimes <- mapM getModificationUTCTime dependent_files
  762. ; let mod_usages = mk_mod_usage_info (eps_PIT eps) hsc_env this_mod
  763. dir_imp_mods used_names
  764. ; let usages = mod_usages ++ map to_file_usage (zip dependent_files mtimes)
  765. ; usages `seqList` return usages }
  766. -- seq the list of Usages returned: occasionally these
  767. -- don't get evaluated for a while and we can end up hanging on to
  768. -- the entire collection of Ifaces.
  769. where
  770. to_file_usage (f, mtime) = UsageFile { usg_file_path = f, usg_mtime = mtime }
  771. mk_mod_usage_info :: PackageIfaceTable
  772. -> HscEnv
  773. -> Module
  774. -> ImportedMods
  775. -> NameSet
  776. -> [Usage]
  777. mk_mod_usage_info pit hsc_env this_mod direct_imports used_names
  778. = mapCatMaybes mkUsage usage_mods
  779. where
  780. hpt = hsc_HPT hsc_env
  781. dflags = hsc_dflags hsc_env
  782. this_pkg = thisPackage dflags
  783. used_mods = moduleEnvKeys ent_map
  784. dir_imp_mods = moduleEnvKeys direct_imports
  785. all_mods = used_mods ++ filter (`notElem` used_mods) dir_imp_mods
  786. usage_mods = sortBy stableModuleCmp all_mods
  787. -- canonical order is imported, to avoid interface-file
  788. -- wobblage.
  789. -- ent_map groups together all the things imported and used
  790. -- from a particular module
  791. ent_map :: ModuleEnv [OccName]
  792. ent_map = foldNameSet add_mv emptyModuleEnv used_names
  793. where
  794. add_mv name mv_map
  795. | isWiredInName name = mv_map -- ignore wired-in names
  796. | otherwise
  797. = case nameModule_maybe name of
  798. Nothing -> ASSERT2( isSystemName name, ppr name ) mv_map
  799. -- See Note [Internal used_names]
  800. Just mod -> -- This lambda function is really just a
  801. -- specialised (++); originally came about to
  802. -- avoid quadratic behaviour (trac #2680)
  803. extendModuleEnvWith (\_ xs -> occ:xs) mv_map mod [occ]
  804. where occ = nameOccName name
  805. -- We want to create a Usage for a home module if
  806. -- a) we used something from it; has something in used_names
  807. -- b) we imported it, even if we used nothing from it
  808. -- (need to recompile if its export list changes: export_fprint)
  809. mkUsage :: Module -> Maybe Usage
  810. mkUsage mod
  811. | isNothing maybe_iface -- We can't depend on it if we didn't
  812. -- load its interface.
  813. || mod == this_mod -- We don't care about usages of
  814. -- things in *this* module
  815. = Nothing
  816. | modulePackageId mod /= this_pkg
  817. = Just UsagePackageModule{ usg_mod = mod,
  818. usg_mod_hash = mod_hash,
  819. usg_safe = imp_safe }
  820. -- for package modules, we record the module hash only
  821. | (null used_occs
  822. && isNothing export_hash
  823. && not is_direct_import
  824. && not finsts_mod)
  825. = Nothing -- Record no usage info
  826. -- for directly-imported modules, we always want to record a usage
  827. -- on the orphan hash. This is what triggers a recompilation if
  828. -- an orphan is added or removed somewhere below us in the future.
  829. | otherwise
  830. = Just UsageHomeModule {
  831. usg_mod_name = moduleName mod,
  832. usg_mod_hash = mod_hash,
  833. usg_exports = export_hash,
  834. usg_entities = Map.toList ent_hashs,
  835. usg_safe = imp_safe }
  836. where
  837. maybe_iface = lookupIfaceByModule dflags hpt pit mod
  838. -- In one-shot mode, the interfaces for home-package
  839. -- modules accumulate in the PIT not HPT. Sigh.
  840. Just iface = maybe_iface
  841. finsts_mod = mi_finsts iface
  842. hash_env = mi_hash_fn iface
  843. mod_hash = mi_mod_hash iface
  844. export_hash | depend_on_exports = Just (mi_exp_hash iface)
  845. | otherwise = Nothing
  846. (is_direct_import, imp_safe)
  847. = case lookupModuleEnv direct_imports mod of
  848. Just ((_,_,_,safe):_xs) -> (True, safe)
  849. Just _ -> pprPanic "mkUsage: empty direct import" empty
  850. Nothing -> (False, safeImplicitImpsReq dflags)
  851. -- Nothing case is for implicit imports like 'System.IO' when 'putStrLn'
  852. -- is used in the source code. We require them to be safe in Safe Haskell
  853. used_occs = lookupModuleEnv ent_map mod `orElse` []
  854. -- Making a Map here ensures that (a) we remove duplicates
  855. -- when we have usages on several subordinates of a single parent,
  856. -- and (b) that the usages emerge in a canonical order, which
  857. -- is why we use Map rather than OccEnv: Map works
  858. -- using Ord on the OccNames, which is a lexicographic ordering.
  859. ent_hashs :: Map OccName Fingerprint
  860. ent_hashs = Map.fromList (map lookup_occ used_occs)
  861. lookup_occ occ =
  862. case hash_env occ of
  863. Nothing -> pprPanic "mkUsage" (ppr mod <+> ppr occ <+> ppr used_names)
  864. Just r -> r
  865. depend_on_exports = is_direct_import
  866. {- True
  867. Even if we used 'import M ()', we have to register a
  868. usage on the export list because we are sensitive to
  869. changes in orphan instances/rules.
  870. False
  871. In GHC 6.8.x we always returned true, and in
  872. fact it recorded a dependency on *all* the
  873. modules underneath in the dependency tree. This
  874. happens to make orphans work right, but is too
  875. expensive: it'll read too many interface files.
  876. The 'isNothing maybe_iface' check above saved us
  877. from generating many of these usages (at least in
  878. one-shot mode), but that's even more bogus!
  879. -}
  880. \end{code}
  881. \begin{code}
  882. mkIfaceAnnotations :: [Annotation] -> [IfaceAnnotation]
  883. mkIfaceAnnotations = map mkIfaceAnnotation
  884. mkIfaceAnnotation :: Annotation -> IfaceAnnotation
  885. mkIfaceAnnotation (Annotation { ann_target = target, ann_value = serialized }) = IfaceAnnotation {
  886. ifAnnotatedTarget = fmap nameOccName target,
  887. ifAnnotatedValue = serialized
  888. }
  889. \end{code}
  890. \begin{code}
  891. mkIfaceExports :: [AvailInfo] -> [IfaceExport] -- Sort to make canonical
  892. mkIfaceExports exports
  893. = sortBy stableAvailCmp (map sort_subs exports)
  894. where
  895. sort_subs :: AvailInfo -> AvailInfo
  896. sort_subs (Avail n) = Avail n
  897. sort_subs (AvailTC n []) = AvailTC n []
  898. sort_subs (AvailTC n (m:ms))
  899. | n==m = AvailTC n (m:sortBy stableNameCmp ms)
  900. | otherwise = AvailTC n (sortBy stableNameCmp (m:ms))
  901. -- Maintain the AvailTC Invariant
  902. \end{code}
  903. Note [Orignal module]
  904. ~~~~~~~~~~~~~~~~~~~~~
  905. Consider this:
  906. module X where { data family T }
  907. module Y( T(..) ) where { import X; data instance T Int = MkT Int }
  908. The exported Avail from Y will look like
  909. X.T{X.T, Y.MkT}
  910. That is, in Y,
  911. - only MkT is brought into scope by the data instance;
  912. - but the parent (used for grouping and naming in T(..) exports) is X.T
  913. - and in this case we export X.T too
  914. In the result of MkIfaceExports, the names are grouped by defining module,
  915. so we may need to split up a single Avail into multiple ones.
  916. Note [Internal used_names]
  917. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  918. Most of the used_names are External Names, but we can have Internal
  919. Names too: see Note [Binders in Template Haskell] in Convert, and
  920. Trac #5362 for an example. Such Names are always
  921. - Such Names are always for locally-defined things, for which we
  922. don't gather usage info, so we can just ignore them in ent_map
  923. - They are always System Names, hence the assert, just as a double check.
  924. %************************************************************************
  925. %* *
  926. Load the old interface file for this module (unless
  927. we have it already), and check whether it is up to date
  928. %* *
  929. %************************************************************************
  930. \begin{code}
  931. data RecompileRequired
  932. = UpToDate
  933. -- ^ everything is up to date, recompilation is not required
  934. | MustCompile
  935. -- ^ The .hs file has been touched, or the .o/.hi file does not exist
  936. | RecompBecause String
  937. -- ^ The .o/.hi files are up to date, but something else has changed
  938. -- to force recompilation; the String says what (one-line summary)
  939. deriving Eq
  940. recompileRequired :: RecompileRequired -> Bool
  941. recompileRequired UpToDate = False
  942. recompileRequired _ = True
  943. -- | Top level function to check if the version of an old interface file
  944. -- is equivalent to the current source file the user asked us to compile.
  945. -- If the same, we can avoid recompilation. We return a tuple where the
  946. -- first element is a bool saying if we should recompile the object file
  947. -- and the second is maybe the interface file, where Nothng means to
  948. -- rebuild the interface file not use the exisitng one.
  949. checkOldIface :: HscEnv
  950. -> ModSummary
  951. -> SourceModified
  952. -> Maybe ModIface -- Old interface from compilation manager, if any
  953. -> IO (RecompileRequired, Maybe ModIface)
  954. checkOldIface hsc_env mod_summary source_modified maybe_iface
  955. = do let dflags = hsc_dflags hsc_env
  956. showPass dflags $
  957. "Checking old interface for " ++ (showPpr dflags $ ms_mod mod_summary)
  958. initIfaceCheck hsc_env $
  959. check_old_iface hsc_env mod_summary source_modified maybe_iface
  960. check_old_iface :: HscEnv -> ModSummary -> SourceModified -> Maybe ModIface
  961. -> IfG (RecompileRequired, Maybe ModIface)
  962. check_old_iface hsc_env mod_summary src_modified maybe_iface
  963. = let dflags = hsc_dflags hsc_env
  964. getIface =
  965. case maybe_iface of
  966. Just _ -> do
  967. traceIf (text "We already have the old interface for" <+> ppr (ms_mod mod_summary))
  968. return maybe_iface
  969. Nothing -> loadIface
  970. loadIface = do
  971. let iface_path = msHiFilePath mod_summary
  972. read_result <- readIface (ms_mod mod_summary) iface_path
  973. case read_result of
  974. Failed err -> do
  975. traceIf (text "FYI: cannot read old interface file:" $$ nest 4 err)
  976. return Nothing
  977. Succeeded iface -> do
  978. traceIf (text "Read the interface file" <+> text iface_path)
  979. return $ Just iface
  980. src_changed
  981. | gopt Opt_ForceRecomp (hsc_dflags hsc_env) = True
  982. | SourceModified <- src_modified = True
  983. | otherwise = False
  984. in do
  985. when src_changed $
  986. traceHiDiffs (nest 4 $ text "Source file changed or recompilation check turned off")
  987. case src_changed of
  988. -- If the source has changed and we're in interactive mode,
  989. -- avoid reading an interface; just return the one we might
  990. -- have been supplied with.
  991. True | not (isObjectTarget $ hscTarget dflags) ->
  992. return (MustCompile, maybe_iface)
  993. -- Try and read the old interface for the current module
  994. -- from the .hi file left from the last time we compiled it
  995. True -> do
  996. maybe_iface' <- getIface
  997. return (MustCompile, maybe_iface')
  998. False -> do
  999. maybe_iface' <- getIface
  1000. case maybe_iface' of
  1001. -- We can't retrieve the iface
  1002. Nothing -> return (MustCompile, Nothing)
  1003. -- We have got the old iface; check its versions
  1004. -- even in the SourceUnmodifiedAndStable case we
  1005. -- should check versions because some packages
  1006. -- might have changed or gone away.
  1007. Just iface -> checkVersions hsc_env mod_summary iface
  1008. -- | Check if a module is still the same 'version'.
  1009. --
  1010. -- This function is called in the recompilation checker after we have
  1011. -- determined that the module M being checked hasn't had any changes
  1012. -- to its source file since we last compiled M. So at this point in general
  1013. -- two things may have changed that mean we should recompile M:
  1014. -- * The interface export by a dependency of M has changed.
  1015. -- * The compiler flags specified this time for M have changed
  1016. -- in a manner that is significant for recompilaiton.
  1017. -- We return not just if we should recompile the object file but also
  1018. -- if we should rebuild the interface file.
  1019. checkVersions :: HscEnv
  1020. -> ModSummary
  1021. -> ModIface -- Old interface
  1022. -> IfG (RecompileRequired, Maybe ModIface)
  1023. checkVersions hsc_env mod_summary iface
  1024. = do { traceHiDiffs (text "Considering whether compilation is required for" <+>
  1025. ppr (mi_module iface) <> colon)
  1026. ; recomp <- checkFlagHash hsc_env iface
  1027. ; if recompileRequired recomp then return (recomp, Nothing) else do {
  1028. ; recomp <- checkDependencies hsc_env mod_summary iface
  1029. ; if recompileRequired recomp then return (recomp, Just iface) else do {
  1030. -- Source code unchanged and no errors yet... carry on
  1031. --
  1032. -- First put the dependent-module info, read from the old
  1033. -- interface, into the envt, so that when we look for
  1034. -- interfaces we look for the right one (.hi or .hi-boot)
  1035. --
  1036. -- It's just temporary because either the usage check will succeed
  1037. -- (in which case we are done with this module) or it'll fail (in which
  1038. -- case we'll compile the module from scratch anyhow).
  1039. --
  1040. -- We do this regardless of compilation mode, although in --make mode
  1041. -- all the dependent modules should be in the HPT already, so it's
  1042. -- quite redundant
  1043. ; updateEps_ $ \eps -> eps { eps_is_boot = mod_deps }
  1044. ; recomp <- checkList [checkModUsage this_pkg u | u <- mi_usages iface]
  1045. ; return (recomp, Just iface)
  1046. }}}
  1047. where
  1048. this_pkg = thisPackage (hsc_dflags hsc_env)
  1049. -- This is a bit of a hack really
  1050. mod_deps :: ModuleNameEnv (ModuleName, IsBootInterface)
  1051. mod_deps = mkModDeps (dep_mods (mi_deps iface))
  1052. -- | Check the flags haven't changed
  1053. checkFlagHash :: HscEnv -> ModIface -> IfG RecompileRequired
  1054. checkFlagHash hsc_env iface = do
  1055. let old_hash = mi_flag_hash iface
  1056. new_hash <- liftIO $ fingerprintDynFlags (hsc_dflags hsc_env)
  1057. (mi_module iface)
  1058. putNameLiterally
  1059. case old_hash == new_hash of
  1060. True -> up_to_date (ptext $ sLit "Module flags unchanged")
  1061. False -> out_of_date_hash "flags changed"
  1062. (ptext $ sLit " Module flags have changed")
  1063. old_hash new_hash
  1064. -- If the direct imports of this module are resolved to targets that
  1065. -- are not among the dependencies of the previous interface file,
  1066. -- then we definitely need to recompile. This catches cases like
  1067. -- - an exposed package has been upgraded
  1068. -- - we are compiling with different package flags
  1069. -- - a home module that was shadowing a package module has been removed
  1070. -- - a new home module has been added that shadows a package module
  1071. -- See bug #1372.
  1072. --
  1073. -- Returns True if recompilation is required.
  1074. checkDependencies :: HscEnv -> ModSummary -> ModIface -> IfG RecompileRequired
  1075. checkDependencies hsc_env summary iface
  1076. = checkList (map dep_missing (ms_imps summary ++ ms_srcimps summary))
  1077. where
  1078. prev_dep_mods = dep_mods (mi_deps iface)
  1079. prev_dep_pkgs = dep_pkgs (mi_deps iface)
  1080. this_pkg = thisPackage (hsc_dflags hsc_env)
  1081. dep_missing (L _ (ImportDecl { ideclName = L _ mod, ideclPkgQual = pkg })) = do
  1082. find_res <- liftIO $ findImportedModule hsc_env mod pkg
  1083. let reason = moduleNameString mod ++ " changed"
  1084. case find_res of
  1085. Found _ mod
  1086. | pkg == this_pkg
  1087. -> if moduleName mod `notElem` map fst prev_dep_mods
  1088. then do traceHiDiffs $
  1089. text "imported module " <> quotes (ppr mod) <>
  1090. text " not among previous dependencies"
  1091. return (RecompBecause reason)
  1092. else
  1093. return UpToDate
  1094. | otherwise
  1095. -> if pkg `notElem` (map fst prev_dep_pkgs)
  1096. then do traceHiDiffs $
  1097. text "imported module " <> quotes (ppr mod) <>
  1098. text " is from package " <> quotes (ppr pkg) <>
  1099. text ", which is not among previous dependencies"
  1100. return (RecompBecause reason)
  1101. else
  1102. return UpToDate
  1103. where pkg = modulePackageId mod
  1104. _otherwise -> return (RecompBecause reason)
  1105. needInterface :: Module -> (ModIface -> IfG RecompileRequired)
  1106. -> IfG RecompileRequired
  1107. needInterface mod continue
  1108. = do -- Load the imported interface if possible
  1109. let doc_str = sep [ptext (sLit "need version info for"), ppr mod]
  1110. traceHiDiffs (text "Checking usages for module" <+> ppr mod)
  1111. mb_iface <- loadInterface doc_str mod ImportBySystem
  1112. -- Load the interface, but don't complain on failure;
  1113. -- Instead, get an Either back which we can test
  1114. case mb_iface of
  1115. Failed _ -> do
  1116. traceHiDiffs (sep [ptext (sLit "Couldn't load interface for module"),
  1117. ppr mod])
  1118. return MustCompile
  1119. -- Couldn't find or parse a module mentioned in the
  1120. -- old interface file. Don't complain: it might
  1121. -- just be that the current module doesn't need that
  1122. -- import and it's been deleted
  1123. Succeeded iface -> continue iface
  1124. -- | Given the usage information extracted from the old
  1125. -- M.hi file for the module being compiled, figure out
  1126. -- whether M needs to be recompiled.
  1127. checkModUsage :: PackageId -> Usage -> IfG RecompileRequired
  1128. checkModUsage _this_pkg UsagePackageModule{
  1129. usg_mod = mod,
  1130. usg_mod_hash = old_mod_hash }
  1131. = needInterface mod $ \iface -> do
  1132. let reason = moduleNameString (moduleName mod) ++ " changed"
  1133. checkModuleFingerprint reason old_mod_hash (mi_mod_hash iface)
  1134. -- We only track the ABI hash of package modules, rather than
  1135. -- individual entity usages, so if the ABI hash changes we must
  1136. -- recompile. This is safe but may entail more recompilation when
  1137. -- a dependent package has changed.
  1138. checkModUsage this_pkg UsageHomeModule{
  1139. usg_mod_name = mod_name,
  1140. usg_mod_hash = old_mod_hash,
  1141. usg_exports = maybe_old_export_hash,
  1142. usg_entities = old_decl_hash }
  1143. = do
  1144. let mod = mkModule this_pkg mod_name
  1145. needInterface mod $ \iface -> do
  1146. let
  1147. new_mod_hash = mi_mod_hash iface
  1148. new_decl_hash = mi_hash_fn iface
  1149. new_export_hash = mi_exp_hash iface
  1150. reason = moduleNameString mod_name ++ " changed"
  1151. -- CHECK MODULE
  1152. recompile <- checkModuleFingerprint reason old_mod_hash new_mod_hash
  1153. if not (recompileRequired recompile) then return UpToDate else do
  1154. -- CHECK EXPORT LIST
  1155. checkMaybeHash reason maybe_old_export_hash new_export_hash
  1156. (ptext (sLit " Export list changed")) $ do
  1157. -- CHECK ITEMS ONE BY ONE
  1158. recompile <- checkList [ checkEntityUsage reason new_decl_hash u
  1159. | u <- old_decl_hash]
  1160. if recompileRequired recompile
  1161. then return recompile -- This one failed, so just bail out now
  1162. else up_to_date (ptext (sLit " Great! The bits I use are up to date"))
  1163. checkModUsage _this_pkg UsageFile{ usg_file_path = file,
  1164. usg_mtime = old_mtime } =
  1165. liftIO $
  1166. handleIO handle $ do
  1167. new_mtime <- getModificationUTCTime file
  1168. if (old_mtime /= new_mtime)
  1169. then return recomp
  1170. else return UpToDate
  1171. where
  1172. recomp = RecompBecause (file ++ " changed")
  1173. handle =
  1174. #ifdef DEBUG
  1175. \e -> pprTrace "UsageFile" (text (show e)) $ return recomp
  1176. #else
  1177. \_ -> return recomp -- if we can't find the file, just recompile, don't fail
  1178. #endif
  1179. ------------------------
  1180. checkModuleFingerprint :: String -> Fingerprint -> Fingerprint
  1181. -> IfG RecompileRequired
  1182. checkModuleFingerprint reason old_mod_hash new_mod_hash
  1183. | new_mod_hash == old_mod_hash
  1184. = up_to_date (ptext (sLit "Module fingerprint unchanged"))
  1185. | otherwise
  1186. = out_of_date_hash reason (ptext (sLit " Module fingerprint has changed"))
  1187. old_mod_hash new_mod_hash
  1188. ------------------------
  1189. checkMaybeHash :: String -> Maybe Fingerprint -> Fingerprint -> SDoc
  1190. -> IfG RecompileRequired -> IfG RecompileRequired
  1191. checkMaybeHash reason maybe_old_hash new_hash doc continue
  1192. | Just hash <- maybe_old_hash, hash /= new_hash
  1193. = out_of_date_hash reason doc hash new_hash
  1194. | otherwise
  1195. = continue
  1196. ------------------------
  1197. checkEntityUsage :: String
  1198. -> (OccName -> Maybe (OccName, Fingerprint))
  1199. -> (OccName, Fingerprint)
  1200. -> IfG RecompileRequired
  1201. checkEntityUsage reason new_hash (name,old_hash)
  1202. = case new_hash name of
  1203. Nothing -> -- We used it before, but it ain't there now
  1204. out_of_date reason (sep [ptext (sLit "No longer exported:"), ppr name])
  1205. Just (_, new_hash) -- It's there, but is it up to date?
  1206. | new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash))
  1207. return UpToDate
  1208. | otherwise -> out_of_date_hash reason (ptext (sLit " Out of date:") <+> ppr name)
  1209. old_hash new_hash
  1210. up_to_date :: SDoc -> IfG RecompileRequired
  1211. up_to_date msg = traceHiDiffs msg >> return UpToDate
  1212. out_of_date :: String -> SDoc -> IfG RecompileRequired
  1213. out_of_date reason msg = traceHiDiffs msg >> return (RecompBecause reason)
  1214. out_of_date_hash :: String -> SDoc -> Fingerprint -> Fingerprint -> IfG RecompileRequired
  1215. out_of_date_hash reason msg old_hash new_hash
  1216. = out_of_date reason (hsep [msg, ppr old_hash, ptext (sLit "->"), ppr new_hash])
  1217. ----------------------
  1218. checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
  1219. -- This helper is used in two places
  1220. checkList [] = return UpToDate
  1221. checkList (check:checks) = do recompile <- check
  1222. if recompileRequired recompile
  1223. then return recompile
  1224. else checkList checks
  1225. \end{code}
  1226. %************************************************************************
  1227. %* *
  1228. Converting things to their Iface equivalents
  1229. %* *
  1230. %************************************************************************
  1231. \begin{code}
  1232. tyThingToIfaceDecl :: TyThing -> IfaceDecl
  1233. tyThingToIfaceDecl (AnId id) = idToIfaceDecl id
  1234. tyThingToIfaceDecl (ATyCon tycon) = tyConToIfaceDecl emptyTidyEnv tycon
  1235. tyThingToIfaceDecl (ACoAxiom ax) = coAxiomToIfaceDecl ax
  1236. tyThingToIfaceDecl (ADataCon dc) = pprPanic "toIfaceDecl" (ppr dc)
  1237. -- Should be trimmed out earlier
  1238. --------------------------
  1239. idToIfaceDecl :: Id -> IfaceDecl
  1240. -- The Id is already tidied, so that locally-bound names
  1241. -- (lambdas, for-alls) already have non-clashing OccNames
  1242. -- We can't tidy it here, locally, because it may have
  1243. -- free variables in its type or IdInfo
  1244. idToIfaceDecl id
  1245. = IfaceId { ifName = getOccName id,
  1246. ifType = toIfaceType (idType id),
  1247. ifIdDetails = toIfaceIdDetails (idDetails id),
  1248. ifIdInfo = toIfaceIdInfo (idInfo id) }
  1249. --------------------------
  1250. coAxiomToIfaceDecl :: CoAxiom br -> IfaceDecl
  1251. -- We *do* tidy Axioms, because they are not (and cannot
  1252. -- conveniently be) built in tidy form
  1253. coAxiomToIfaceDecl ax@(CoAxiom { co_ax_tc = tycon, co_ax_branches = branches })
  1254. = IfaceAxiom { ifName = name
  1255. , ifTyCon = toIfaceTyCon tycon
  1256. , ifAxBranches = brListMap (coAxBranchToIfaceBranch emptyTidyEnv) branches }
  1257. where
  1258. name = getOccName ax
  1259. coAxBranchToIfaceBranch :: TidyEnv -> CoAxBranch -> IfaceAxBranch
  1260. coAxBranchToIfaceBranch env0 (CoAxBranch { cab_tvs = tvs, cab_lhs = lhs, cab_rhs = rhs })
  1261. = IfaceAxBranch { ifaxbTyVars = toIfaceTvBndrs tv_bndrs
  1262. , ifaxbLHS = map (tidyToIfaceType env1) lhs
  1263. , ifaxbRHS = tidyToIfaceType env1 rhs }
  1264. where
  1265. (env1, tv_bndrs) = tidyTyVarBndrs env0 tvs
  1266. -----------------
  1267. tyConToIfaceDecl :: TidyEnv -> TyCon -> IfaceDecl
  1268. -- We *do* tidy TyCons, because they are not (and cannot
  1269. -- conveniently be) built in tidy form
  1270. tyConToIfaceDecl env tycon
  1271. | Just clas <- tyConClass_maybe tycon
  1272. = classToIfaceDecl env clas
  1273. | Just syn_rhs <- synTyConRhs_maybe tycon
  1274. = IfaceSyn { ifName = getOccName tycon,
  1275. ifTyVars = toIfaceTvBndrs tyvars,
  1276. ifSynRhs = to_ifsyn_rhs syn_rhs,
  1277. ifSynKind = tidyToIfaceType env1 (synTyConResKind tycon) }
  1278. | isAlgTyCon tycon
  1279. = IfaceData { ifName = getOccName tycon,
  1280. ifCType = tyConCType tycon,
  1281. ifTyVars = toIfaceTvBndrs tyvars,
  1282. ifCtxt = tidyToIfaceContext env1 (tyConStupidTheta tycon),
  1283. ifCons = ifaceConDecls (algTyConRhs tycon),
  1284. ifRec = boolToRecFlag (isRecursiveTyCon tycon),
  1285. ifGadtSyntax = isGadtSyntaxTyCon tycon,
  1286. ifPromotable = isJust (promotableTyCon_maybe tycon),
  1287. ifAxiom = fmap coAxiomName (tyConFamilyCoercion_maybe tycon) }
  1288. | isForeignTyCon tycon
  1289. = IfaceForeign { ifName = getOccName tycon,
  1290. ifExtName = tyConExtName tycon }
  1291. | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
  1292. where
  1293. (env1, tyvars) = tidyTyClTyVarBndrs env (tyConTyVars tycon)
  1294. to_ifsyn_rhs (SynFamilyTyCon a b) = SynFamilyTyCon a b
  1295. to_ifsyn_rhs (SynonymTyCon ty) = SynonymTyCon (tidyToIfaceType env1 ty)
  1296. ifaceConDecls (NewTyCon { data_con = con }) = IfNewTyCon (ifaceConDecl con)
  1297. ifaceConDecls (DataTyCon { data_cons = cons }) = IfDataTyCon (map ifaceConDecl cons)
  1298. ifaceConDecls (DataFamilyTyCon {}) = IfDataFamTyCon
  1299. ifaceConDecls (AbstractTyCon distinct) = IfAbstractTyCon distinct
  1300. -- The last case happens when a TyCon has been trimmed during tidying
  1301. -- Furthermore, tyThingToIfaceDecl is also used
  1302. -- in TcRnDriver for GHCi, when browsing a module, in which case the
  1303. -- AbstractTyCon case is perfectly sensible.
  1304. ifaceConDecl data_con
  1305. = IfCon { ifConOcc = getOccName (dataConName data_con),
  1306. ifConInfix = dataConIsInfix data_con,
  1307. ifConWrapper = isJust (dataConWrapId_maybe data_con),
  1308. ifConUnivTvs = toIfaceTvBndrs univ_tvs',
  1309. ifConExTvs = toIfaceTvBndrs ex_tvs',
  1310. ifConEqSpec = to_eq_spec eq_spec,
  1311. ifConCtxt = tidyToIfaceContext env2 theta,
  1312. ifConArgTys = map (tidyToIfaceType env2) arg_tys,
  1313. ifConFields = map getOccName
  1314. (dataConFieldLabels data_con),
  1315. ifConStricts = map (toIfaceBang env2) (dataConRepBangs data_con) }
  1316. where
  1317. (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig data_con
  1318. -- Start with 'emptyTidyEnv' not 'env1', because the type of the
  1319. -- data constructor is fully standalone
  1320. (env1, univ_tvs') = tidyTyVarBndrs emptyTidyEnv univ_tvs
  1321. (env2, ex_tvs') = tidyTyVarBndrs env1 ex_tvs
  1322. to_eq_spec spec = [ (getOccName (tidyTyVar env2 tv), tidyToIfaceType env2 ty)
  1323. | (tv,ty) <- spec]
  1324. toIfaceBang :: TidyEnv -> HsBang -> IfaceBang
  1325. toIfaceBang _ HsNoBang = IfNoBang
  1326. toIfaceBang _ (HsUnpack Nothing) = IfUnpack
  1327. toIfaceBang env (HsUnpack (Just co)) = IfUnpackCo (coToIfaceType (tidyCo env co))
  1328. toIfaceBang _ HsStrict = IfStrict
  1329. toIfaceBang _ (HsUserBang {}) = panic "toIfaceBang"
  1330. classToIfaceDecl :: TidyEnv -> Class -> IfaceDecl
  1331. classToIfaceDecl env clas
  1332. = IfaceClass { ifCtxt = tidyToIfaceContext env1 sc_theta,
  1333. ifName = getOccName (classTyCon clas),
  1334. ifTyVars = toIfaceTvBndrs clas_tyvars',
  1335. ifFDs = map toIfaceFD clas_fds,
  1336. ifATs = map toIfaceAT clas_ats,
  1337. ifSigs = map toIfaceClassOp op_stuff,
  1338. ifRec = boolToRecFlag (isRecursiveTyCon tycon) }
  1339. where
  1340. (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
  1341. = classExtraBigSig clas
  1342. tycon = classTyCon clas
  1343. (env1, clas_tyvars') = tidyTyVarBndrs env clas_tyvars
  1344. toIfaceAT :: ClassATItem -> IfaceAT
  1345. toIfaceAT (tc, defs)
  1346. = IfaceAT (tyConToIfaceDecl env1 tc) (map (coAxBranchToIfaceBranch env1) defs)
  1347. toIfaceClassOp (sel_id, def_meth)
  1348. = ASSERT(sel_tyvars == clas_tyvars)
  1349. IfaceClassOp (getOccName sel_id) (toDmSpec def_meth)
  1350. (tidyToIfaceType env1 op_ty)
  1351. where
  1352. -- Be careful when splitting the type, because of things
  1353. -- like class Foo a where
  1354. -- op :: (?x :: String) => a -> a
  1355. -- and class Baz a where
  1356. -- op :: (Ord a) => a -> a
  1357. (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
  1358. op_ty = funResultTy rho_ty
  1359. toDmSpec NoDefMeth = NoDM
  1360. toDmSpec (GenDefMeth _) = GenericDM
  1361. toDmSpec (DefMeth _) = VanillaDM
  1362. toIfaceFD (tvs1, tvs2) = (map (getFS . tidyTyVar env1) tvs1,
  1363. map (getFS . tidyTyVar env1) tvs2)
  1364. --------------------------
  1365. tidyToIfaceType :: TidyEnv -> Type -> IfaceType
  1366. tidyToIfaceType env ty = toIfaceType (tidyType env ty)
  1367. tidyToIfaceContext :: TidyEnv -> ThetaType -> IfaceContext
  1368. tidyToIfaceContext env theta = map (tidyToIfaceType env) theta
  1369. tidyTyClTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
  1370. tidyTyClTyVarBndrs env tvs = mapAccumL tidyTyClTyVarBndr env tvs
  1371. tidyTyClTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
  1372. -- If the type variable "binder" is in scope, don't re-bind it
  1373. -- In a class decl, for example, the ATD binders mention
  1374. -- (amd must mention) the class tyvars
  1375. tidyTyClTyVarBndr env@(_, subst) tv
  1376. | Just tv' <- lookupVarEnv subst tv = (env, tv')
  1377. | otherwise = tidyTyVarBndr env tv
  1378. tidyTyVar :: TidyEnv -> TyVar -> TyVar
  1379. tidyTyVar (_, subst) tv = lookupVarEnv subst tv `orElse` tv
  1380. -- TcType.tidyTyVarOcc messes around with FlatSkols
  1381. getFS :: NamedThing a => a -> FastString
  1382. getFS x = occNameFS (getOccName x)
  1383. --------------------------
  1384. instanceToIfaceInst :: ClsInst -> IfaceClsInst
  1385. instanceToIfaceInst (ClsInst { is_dfun = dfun_id, is_flag = oflag
  1386. , is_cls_nm = cls_name, is_cls = cls
  1387. , is_tys = tys, is_tcs = mb_tcs })
  1388. = ASSERT( cls_name == className cls )
  1389. IfaceClsInst { ifDFun = dfun_name,
  1390. ifOFlag = oflag,
  1391. ifInstCls = cls_name,
  1392. ifInstTys = map do_rough mb_tcs,
  1393. ifInstOrph = orph }
  1394. where
  1395. do_rough Nothing = Nothing
  1396. do_rough (Just n) = Just (toIfaceTyCon_name n)
  1397. dfun_name = idName dfun_id
  1398. mod = ASSERT( isExternalName dfun_name ) nameModule dfun_name
  1399. is_local name = nameIsLocalOrFrom mod name
  1400. -- Compute orphanhood. See Note [Orphans] in IfaceSyn
  1401. (tvs, fds) = classTvsFds cls
  1402. arg_names = [filterNameSet is_local (orphNamesOfType ty) | ty <- tys]
  1403. -- See Note [When exactly is an instance decl an orphan?] in IfaceSyn
  1404. orph | is_local cls_name = Just (nameOccName cls_name)
  1405. | all isJust mb_ns = ASSERT( not (null mb_ns) ) head mb_ns
  1406. | otherwise = Nothing
  1407. mb_ns :: [Maybe OccName] -- One for each fundep; a locally-defined name
  1408. -- that is not in the "determined" arguments
  1409. mb_ns | null fds = [choose_one arg_names]
  1410. | otherwise = map do_one fds
  1411. do_one (_ltvs, rtvs) = choose_one [ns | (tv,ns) <- tvs `zip` arg_names
  1412. , not (tv `elem` rtvs)]
  1413. choose_one :: [NameSet] -> Maybe OccName
  1414. choose_one nss = case nameSetToList (unionManyNameSets nss) of
  1415. [] -> Nothing
  1416. (n : _) -> Just (nameOccName n)
  1417. --------------------------
  1418. famInstToIfaceFamInst :: FamInst br -> IfaceFamInst
  1419. famInstToIfaceFamInst (FamInst { fi_axiom = axiom,
  1420. fi_branched = branched,
  1421. fi_fam = fam,
  1422. fi_branches = branches })
  1423. = IfaceFamInst { ifFamInstAxiom = coAxiomName axiom
  1424. , ifFamInstFam = fam
  1425. , ifFamInstBranched = branched
  1426. , ifFamInstTys = map (map do_rough) roughs
  1427. , ifFamInstOrph = orph }
  1428. where
  1429. roughs = brListMap famInstBranchRoughMatch branches
  1430. do_rough Nothing = Nothing
  1431. do_rough (Just n) = Just (toIfaceTyCon_name n)
  1432. fam_decl = tyConName $ coAxiomTyCon axiom
  1433. mod = ASSERT( isExternalName (coAxiomName axiom) )
  1434. nameModule (coAxiomName axiom)
  1435. is_local name = nameIsLocalOrFrom mod name
  1436. lhs_names = filterNameSet is_local (orphNamesOfCoCon axiom)
  1437. orph | is_local fam_decl
  1438. = Just (nameOccName fam_decl)
  1439. | not (isEmptyNameSet lhs_names)
  1440. = Just (nameOccName (head (nameSetToList lhs_names)))
  1441. | otherwise
  1442. = Nothing
  1443. --------------------------
  1444. toIfaceLetBndr :: Id -> IfaceLetBndr
  1445. toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
  1446. (toIfaceType (idType id))
  1447. (toIfaceIdInfo (idInfo id))
  1448. -- Put into the interface file any IdInfo that CoreTidy.tidyLetBndr
  1449. -- has left on the Id. See Note [IdInfo on nested let-bindings] in IfaceSyn
  1450. --------------------------
  1451. toIfaceIdDetails :: IdDetails -> IfaceIdDetails
  1452. toIfaceIdDetails VanillaId = IfVanillaId
  1453. toIfaceIdDetails (DFunId ns _) = IfDFunId ns
  1454. toIfaceIdDetails (RecSelId { sel_naughty = n
  1455. , sel_tycon = tc }) = IfRecSelId (toIfaceTyCon tc) n
  1456. toIfaceIdDetails other = pprTrace "toIfaceIdDetails" (ppr other)
  1457. IfVanillaId -- Unexpected
  1458. toIfaceIdInfo :: IdInfo -> IfaceIdInfo
  1459. toIfaceIdInfo id_info
  1460. = case catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
  1461. inline_hsinfo, unfold_hsinfo] of
  1462. [] -> NoInfo
  1463. infos -> HasInfo infos
  1464. -- NB: strictness must appear in the list before unfolding
  1465. -- See TcIface.tcUnfolding
  1466. where
  1467. ------------ Arity --------------
  1468. arity_info = arityInfo id_info
  1469. arity_hsinfo | arity_info == 0 = Nothing
  1470. | otherwise = Just (HsArity arity_info)
  1471. ------------ Caf Info --------------
  1472. caf_info = cafInfo id_info
  1473. caf_hsinfo = case caf_info of
  1474. NoCafRefs -> Just HsNoCafRefs
  1475. _other -> Nothing
  1476. ------------ Strictness --------------
  1477. -- No point in explicitly exporting TopSig
  1478. sig_info = strictnessInfo id_info
  1479. strict_hsinfo | not (isTopSig sig_info) = Just (HsStrictness sig_info)
  1480. | otherwise = Nothing
  1481. ------------ Unfolding --------------
  1482. unfold_hsinfo = toIfUnfolding loop_breaker (unfoldingInfo id_info)
  1483. loop_breaker = isStrongLoopBreaker (occInfo id_info)
  1484. ------------ Inline prag --------------
  1485. inline_prag = inlinePragInfo id_info
  1486. inline_hsinfo | isDefaultInlinePragma inline_prag = Nothing
  1487. | otherwise = Just (HsInline inline_prag)
  1488. --------------------------
  1489. toIfUnfolding :: Bool -> Unfolding -> Maybe IfaceInfoItem
  1490. toIfUnfolding lb (CoreUnfolding { uf_tmpl = rhs, uf_arity = arity
  1491. , uf_src = src, uf_guidance = guidance })
  1492. = Just $ HsUnfold lb $
  1493. case src of
  1494. InlineStable
  1495. -> case guidance of
  1496. UnfWhen unsat_ok boring_ok -> IfInlineRule arity unsat_ok boring_ok if_rhs
  1497. _other -> IfCoreUnfold True if_rhs
  1498. InlineWrapper w | isExternalName n -> IfExtWrapper arity n
  1499. | otherwise -> IfLclWrapper arity (getFS n)
  1500. where
  1501. n = idName w
  1502. InlineCompulsory -> IfCompulsory if_rhs
  1503. InlineRhs -> IfCoreUnfold False if_rhs
  1504. -- Yes, even if guidance is UnfNever, expose the unfolding
  1505. -- If we didn't want to expose the unfolding, TidyPgm would
  1506. -- have stuck in NoUnfolding. For supercompilation we want
  1507. -- to see that unfolding!
  1508. where
  1509. if_rhs = toIfaceExpr rhs
  1510. toIfUnfolding lb (DFunUnfolding _ar _con ops)
  1511. = Just (HsUnfold lb (IfDFunUnfold (map (fmap toIfaceExpr) ops)))
  1512. -- No need to serialise the data constructor;
  1513. -- we can recover it from the type of the dfun
  1514. toIfUnfolding _ _
  1515. = Nothing
  1516. --------------------------
  1517. coreRuleToIfaceRule :: Module -> CoreRule -> IfaceRule
  1518. coreRuleToIfaceRule _ (BuiltinRule { ru_fn = fn})
  1519. = pprTrace "toHsRule: builtin" (ppr fn) $
  1520. bogusIfaceRule fn
  1521. coreRuleToIfaceRule mod rule@(Rule { ru_name = name, ru_fn = fn,
  1522. ru_act = act, ru_bndrs = bndrs,
  1523. ru_args = args, ru_rhs = rhs,
  1524. ru_auto = auto })
  1525. = IfaceRule { ifRuleName = name, ifActivation = act,
  1526. ifRuleBndrs = map toIfaceBndr bndrs,
  1527. ifRuleHead = fn,
  1528. ifRuleArgs = map do_arg args,
  1529. ifRuleRhs = toIfaceExpr rhs,
  1530. ifRuleAuto = auto,
  1531. ifRuleOrph = orph }
  1532. where
  1533. -- For type args we must remove synonyms from the outermost
  1534. -- level. Reason: so that when we read it back in we'll
  1535. -- construct the same ru_rough field as we have right now;
  1536. -- see tcIfaceRule
  1537. do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
  1538. do_arg (Coercion co) = IfaceCo (coToIfaceType co)
  1539. do_arg arg = toIfaceExpr arg
  1540. -- Compute orphanhood. See Note [Orphans] in IfaceSyn
  1541. -- A rule is an orphan only if none of the variables
  1542. -- mentioned on its left-hand side are locally defined
  1543. lhs_names = nameSetToList (ruleLhsOrphNames rule)
  1544. orph = case filter (nameIsLocalOrFrom mod) lhs_names of
  1545. (n : _) -> Just (nameOccName n)
  1546. [] -> Nothing
  1547. bogusIfaceRule :: Name -> IfaceRule
  1548. bogusIfaceRule id_name
  1549. = IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
  1550. ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
  1551. ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing, ifRuleAuto = True }
  1552. ---------------------
  1553. toIfaceExpr :: CoreExpr -> IfaceExpr
  1554. toIfaceExpr (Var v) = toIfaceVar v
  1555. toIfaceExpr (Lit l) = IfaceLit l
  1556. toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
  1557. toIfaceExpr (Coercion co) = IfaceCo (coToIfaceType co)
  1558. toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x) (toIfaceExpr b)
  1559. toIfaceExpr (App f a) = toIfaceApp f [a]
  1560. toIfaceExpr (Case s x ty as)
  1561. | null as = IfaceECase (toIfaceExpr s) (toIfaceType ty)
  1562. | otherwise = IfaceCase (toIfaceExpr s) (getFS x) (map toIfaceAlt as)
  1563. toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
  1564. toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (coToIfaceType co)
  1565. toIfaceExpr (Tick t e) = IfaceTick (toIfaceTickish t) (toIfaceExpr e)
  1566. ---------------------
  1567. toIfaceTickish :: Tickish Id -> IfaceTickish
  1568. toIfaceTickish (ProfNote cc tick push) = IfaceSCC cc tick push
  1569. toIfaceTickish (HpcTick modl ix) = IfaceHpcTick modl ix
  1570. toIfaceTickish _ = panic "toIfaceTickish"
  1571. ---------------------
  1572. toIfaceBind :: Bind Id -> IfaceBinding
  1573. toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
  1574. toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
  1575. ---------------------
  1576. toIfaceAlt :: (AltCon, [Var], CoreExpr)
  1577. -> (IfaceConAlt, [FastString], IfaceExpr)
  1578. toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
  1579. ---------------------
  1580. toIfaceCon :: AltCon -> IfaceConAlt
  1581. toIfaceCon (DataAlt dc) = IfaceDataAlt (getName dc)
  1582. toIfaceCon (LitAlt l) = IfaceLitAlt l
  1583. toIfaceCon DEFAULT = IfaceDefault
  1584. ---------------------
  1585. toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr
  1586. toIfaceApp (App f a) as = toIfaceApp f (a:as)
  1587. toIfaceApp (Var v) as
  1588. = case isDataConWorkId_maybe v of
  1589. -- We convert the *worker* for tuples into IfaceTuples
  1590. Just dc | isTupleTyCon tc && saturated
  1591. -> IfaceTuple (tupleTyConSort tc) tup_args
  1592. where
  1593. val_args = dropWhile isTypeArg as
  1594. saturated = val_args `lengthIs` idArity v
  1595. tup_args = map toIfaceExpr val_args
  1596. tc = dataConTyCon dc
  1597. _ -> mkIfaceApps (toIfaceVar v) as
  1598. toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
  1599. mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr
  1600. mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
  1601. ---------------------
  1602. toIfaceVar :: Id -> IfaceExpr
  1603. toIfaceVar v
  1604. | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
  1605. -- Foreign calls have special syntax
  1606. | isExternalName name = IfaceExt name
  1607. | otherwise = IfaceLcl (getFS name)
  1608. where name = idName v
  1609. \end{code}