PageRenderTime 30ms CodeModel.GetById 27ms 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
  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_hash]
  1040. if recompileRequired recompile
  1041. then return recompile -- This one failed, so just bail out now
  1042. else up_to_date (text " Great! The bits I use are up to date")
  1043. checkModUsage _this_pkg UsageFile{ usg_file_path = file,
  1044. usg_file_hash = old_hash } =
  1045. liftIO $
  1046. handleIO handle $ do
  1047. new_hash <- getFileHash file
  1048. if (old_hash /= new_hash)
  1049. then return recomp
  1050. else return UpToDate
  1051. where
  1052. recomp = RecompBecause (file ++ " changed")
  1053. handle =
  1054. #ifdef DEBUG
  1055. \e -> pprTrace "UsageFile" (text (show e)) $ return recomp
  1056. #else
  1057. \_ -> return recomp -- if we can't find the file, just recompile, don't fail
  1058. #endif
  1059. ------------------------
  1060. checkModuleFingerprint :: String -> Fingerprint -> Fingerprint
  1061. -> IfG RecompileRequired
  1062. checkModuleFingerprint reason old_mod_hash new_mod_hash
  1063. | new_mod_hash == old_mod_hash
  1064. = up_to_date (text "Module fingerprint unchanged")
  1065. | otherwise
  1066. = out_of_date_hash reason (text " Module fingerprint has changed")
  1067. old_mod_hash new_mod_hash
  1068. ------------------------
  1069. checkMaybeHash :: String -> Maybe Fingerprint -> Fingerprint -> SDoc
  1070. -> IfG RecompileRequired -> IfG RecompileRequired
  1071. checkMaybeHash reason maybe_old_hash new_hash doc continue
  1072. | Just hash <- maybe_old_hash, hash /= new_hash
  1073. = out_of_date_hash reason doc hash new_hash
  1074. | otherwise
  1075. = continue
  1076. ------------------------
  1077. checkEntityUsage :: String
  1078. -> (OccName -> Maybe (OccName, Fingerprint))
  1079. -> (OccName, Fingerprint)
  1080. -> IfG RecompileRequired
  1081. checkEntityUsage reason new_hash (name,old_hash)
  1082. = case new_hash name of
  1083. Nothing -> -- We used it before, but it ain't there now
  1084. out_of_date reason (sep [text "No longer exported:", ppr name])
  1085. Just (_, new_hash) -- It's there, but is it up to date?
  1086. | new_hash == old_hash -> do traceHiDiffs (text " Up to date" <+> ppr name <+> parens (ppr new_hash))
  1087. return UpToDate
  1088. | otherwise -> out_of_date_hash reason (text " Out of date:" <+> ppr name)
  1089. old_hash new_hash
  1090. up_to_date :: SDoc -> IfG RecompileRequired
  1091. up_to_date msg = traceHiDiffs msg >> return UpToDate
  1092. out_of_date :: String -> SDoc -> IfG RecompileRequired
  1093. out_of_date reason msg = traceHiDiffs msg >> return (RecompBecause reason)
  1094. out_of_date_hash :: String -> SDoc -> Fingerprint -> Fingerprint -> IfG RecompileRequired
  1095. out_of_date_hash reason msg old_hash new_hash
  1096. = out_of_date reason (hsep [msg, ppr old_hash, text "->", ppr new_hash])
  1097. ----------------------
  1098. checkList :: [IfG RecompileRequired] -> IfG RecompileRequired
  1099. -- This helper is used in two places
  1100. checkList [] = return UpToDate
  1101. checkList (check:checks) = do recompile <- check
  1102. if recompileRequired recompile
  1103. then return recompile
  1104. else checkList checks
  1105. {-
  1106. ************************************************************************
  1107. * *
  1108. Converting things to their Iface equivalents
  1109. * *
  1110. ************************************************************************
  1111. -}
  1112. tyThingToIfaceDecl :: TyThing -> IfaceDecl
  1113. tyThingToIfaceDecl (AnId id) = idToIfaceDecl id
  1114. tyThingToIfaceDecl (ATyCon tycon) = snd (tyConToIfaceDecl emptyTidyEnv tycon)
  1115. tyThingToIfaceDecl (ACoAxiom ax) = coAxiomToIfaceDecl ax
  1116. tyThingToIfaceDecl (AConLike cl) = case cl of
  1117. RealDataCon dc -> dataConToIfaceDecl dc -- for ppr purposes only
  1118. PatSynCon ps -> patSynToIfaceDecl ps
  1119. --------------------------
  1120. idToIfaceDecl :: Id -> IfaceDecl
  1121. -- The Id is already tidied, so that locally-bound names
  1122. -- (lambdas, for-alls) already have non-clashing OccNames
  1123. -- We can't tidy it here, locally, because it may have
  1124. -- free variables in its type or IdInfo
  1125. idToIfaceDecl id
  1126. = IfaceId { ifName = getOccName id,
  1127. ifType = toIfaceType (idType id),
  1128. ifIdDetails = toIfaceIdDetails (idDetails id),
  1129. ifIdInfo = toIfaceIdInfo (idInfo id) }
  1130. --------------------------
  1131. dataConToIfaceDecl :: DataCon -> IfaceDecl
  1132. dataConToIfaceDecl dataCon
  1133. = IfaceId { ifName = getOccName dataCon,
  1134. ifType = toIfaceType (dataConUserType dataCon),
  1135. ifIdDetails = IfVanillaId,
  1136. ifIdInfo = NoInfo }
  1137. --------------------------
  1138. patSynToIfaceDecl :: PatSyn -> IfaceDecl
  1139. patSynToIfaceDecl ps
  1140. = IfacePatSyn { ifName = getOccName . getName $ ps
  1141. , ifPatMatcher = to_if_pr (patSynMatcher ps)
  1142. , ifPatBuilder = fmap to_if_pr (patSynBuilder ps)
  1143. , ifPatIsInfix = patSynIsInfix ps
  1144. , ifPatUnivBndrs = map toIfaceForAllBndr univ_bndrs'
  1145. , ifPatExBndrs = map toIfaceForAllBndr ex_bndrs'
  1146. , ifPatProvCtxt = tidyToIfaceContext env2 prov_theta
  1147. , ifPatReqCtxt = tidyToIfaceContext env2 req_theta
  1148. , ifPatArgs = map (tidyToIfaceType env2) args
  1149. , ifPatTy = tidyToIfaceType env2 rhs_ty
  1150. , ifFieldLabels = (patSynFieldLabels ps)
  1151. }
  1152. where
  1153. (_univ_tvs, req_theta, _ex_tvs, prov_theta, args, rhs_ty) = patSynSig ps
  1154. univ_bndrs = patSynUnivTyVarBinders ps
  1155. ex_bndrs = patSynExTyVarBinders ps
  1156. (env1, univ_bndrs') = tidyTyVarBinders emptyTidyEnv univ_bndrs
  1157. (env2, ex_bndrs') = tidyTyVarBinders env1 ex_bndrs
  1158. to_if_pr (id, needs_dummy) = (idName id, needs_dummy)
  1159. --------------------------
  1160. coAxiomToIfaceDecl :: CoAxiom br -> IfaceDecl
  1161. -- We *do* tidy Axioms, because they are not (and cannot
  1162. -- conveniently be) built in tidy form
  1163. coAxiomToIfaceDecl ax@(CoAxiom { co_ax_tc = tycon, co_ax_branches = branches
  1164. , co_ax_role = role })
  1165. = IfaceAxiom { ifName = name
  1166. , ifTyCon = toIfaceTyCon tycon
  1167. , ifRole = role
  1168. , ifAxBranches = map (coAxBranchToIfaceBranch tycon
  1169. (map coAxBranchLHS branch_list))
  1170. branch_list }
  1171. where
  1172. branch_list = fromBranches branches
  1173. name = getOccName ax
  1174. -- 2nd parameter is the list of branch LHSs, for conversion from incompatible branches
  1175. -- to incompatible indices
  1176. -- See Note [Storing compatibility] in CoAxiom
  1177. coAxBranchToIfaceBranch :: TyCon -> [[Type]] -> CoAxBranch -> IfaceAxBranch
  1178. coAxBranchToIfaceBranch tc lhs_s
  1179. branch@(CoAxBranch { cab_incomps = incomps })
  1180. = (coAxBranchToIfaceBranch' tc branch) { ifaxbIncomps = iface_incomps }
  1181. where
  1182. iface_incomps = map (expectJust "iface_incomps"
  1183. . (flip findIndex lhs_s
  1184. . eqTypes)
  1185. . coAxBranchLHS) incomps
  1186. -- use this one for standalone branches without incompatibles
  1187. coAxBranchToIfaceBranch' :: TyCon -> CoAxBranch -> IfaceAxBranch
  1188. coAxBranchToIfaceBranch' tc (CoAxBranch { cab_tvs = tvs, cab_cvs = cvs
  1189. , cab_lhs = lhs
  1190. , cab_roles = roles, cab_rhs = rhs })
  1191. = IfaceAxBranch { ifaxbTyVars = toIfaceTvBndrs tidy_tvs
  1192. , ifaxbCoVars = map toIfaceIdBndr cvs
  1193. , ifaxbLHS = tidyToIfaceTcArgs env1 tc lhs
  1194. , ifaxbRoles = roles
  1195. , ifaxbRHS = tidyToIfaceType env1 rhs
  1196. , ifaxbIncomps = [] }
  1197. where
  1198. (env1, tidy_tvs) = tidyTyCoVarBndrs emptyTidyEnv tvs
  1199. -- Don't re-bind in-scope tyvars
  1200. -- See Note [CoAxBranch type variables] in CoAxiom
  1201. -----------------
  1202. tyConToIfaceDecl :: TidyEnv -> TyCon -> (TidyEnv, IfaceDecl)
  1203. -- We *do* tidy TyCons, because they are not (and cannot
  1204. -- conveniently be) built in tidy form
  1205. -- The returned TidyEnv is the one after tidying the tyConTyVars
  1206. tyConToIfaceDecl env tycon
  1207. | Just clas <- tyConClass_maybe tycon
  1208. = classToIfaceDecl env clas
  1209. | Just syn_rhs <- synTyConRhs_maybe tycon
  1210. = ( tc_env1
  1211. , IfaceSynonym { ifName = getOccName tycon,
  1212. ifRoles = tyConRoles tycon,
  1213. ifSynRhs = if_syn_type syn_rhs,
  1214. ifBinders = if_binders,
  1215. ifResKind = if_res_kind
  1216. })
  1217. | Just fam_flav <- famTyConFlav_maybe tycon
  1218. = ( tc_env1
  1219. , IfaceFamily { ifName = getOccName tycon,
  1220. ifResVar = if_res_var,
  1221. ifFamFlav = to_if_fam_flav fam_flav,
  1222. ifBinders = if_binders,
  1223. ifResKind = if_res_kind,
  1224. ifFamInj = familyTyConInjectivityInfo tycon
  1225. })
  1226. | isAlgTyCon tycon
  1227. = ( tc_env1
  1228. , IfaceData { ifName = getOccName tycon,
  1229. ifBinders = if_binders,
  1230. ifResKind = if_res_kind,
  1231. ifCType = tyConCType tycon,
  1232. ifRoles = tyConRoles tycon,
  1233. ifCtxt = tidyToIfaceContext tc_env1 (tyConStupidTheta tycon),
  1234. ifCons = ifaceConDecls (algTyConRhs tycon) (algTcFields tycon),
  1235. ifGadtSyntax = isGadtSyntaxTyCon tycon,
  1236. ifParent = parent })
  1237. | otherwise -- FunTyCon, PrimTyCon, promoted TyCon/DataCon
  1238. -- We only convert these TyCons to IfaceTyCons when we are
  1239. -- just about to pretty-print them, not because we are going
  1240. -- to put them into interface files
  1241. = ( env
  1242. , IfaceData { ifName = getOccName tycon,
  1243. ifBinders = if_binders,
  1244. ifResKind = if_res_kind,
  1245. ifCType = Nothing,
  1246. ifRoles = tyConRoles tycon,
  1247. ifCtxt = [],
  1248. ifCons = IfDataTyCon [] False [],
  1249. ifGadtSyntax = False,
  1250. ifParent = IfNoParent })
  1251. where
  1252. -- NOTE: Not all TyCons have `tyConTyVars` field. Forcing this when `tycon`
  1253. -- is one of these TyCons (FunTyCon, PrimTyCon, PromotedDataCon) will cause
  1254. -- an error.
  1255. (tc_env1, tc_binders) = tidyTyConBinders env (tyConBinders tycon)
  1256. tc_tyvars = binderVars tc_binders
  1257. if_binders = toIfaceTyVarBinders tc_binders
  1258. if_res_kind = tidyToIfaceType tc_env1 (tyConResKind tycon)
  1259. if_syn_type ty = tidyToIfaceType tc_env1 ty
  1260. if_res_var = getOccFS `fmap` tyConFamilyResVar_maybe tycon
  1261. parent = case tyConFamInstSig_maybe tycon of
  1262. Just (tc, ty, ax) -> IfDataInstance (coAxiomName ax)
  1263. (toIfaceTyCon tc)
  1264. (tidyToIfaceTcArgs tc_env1 tc ty)
  1265. Nothing -> IfNoParent
  1266. to_if_fam_flav OpenSynFamilyTyCon = IfaceOpenSynFamilyTyCon
  1267. to_if_fam_flav (ClosedSynFamilyTyCon (Just ax))
  1268. = IfaceClosedSynFamilyTyCon (Just (axn, ibr))
  1269. where defs = fromBranches $ coAxiomBranches ax
  1270. ibr = map (coAxBranchToIfaceBranch' tycon) defs
  1271. axn = coAxiomName ax
  1272. to_if_fam_flav (ClosedSynFamilyTyCon Nothing)
  1273. = IfaceClosedSynFamilyTyCon Nothing
  1274. to_if_fam_flav AbstractClosedSynFamilyTyCon = IfaceAbstractClosedSynFamilyTyCon
  1275. to_if_fam_flav (DataFamilyTyCon {}) = IfaceDataFamilyTyCon
  1276. to_if_fam_flav (BuiltInSynFamTyCon {}) = IfaceBuiltInSynFamTyCon
  1277. ifaceConDecls (NewTyCon { data_con = con }) flds = IfNewTyCon (ifaceConDecl con) (ifaceOverloaded flds) (ifaceFields flds)
  1278. ifaceConDecls (DataTyCon { data_cons = cons }) flds = IfDataTyCon (map ifaceConDecl cons) (ifaceOverloaded flds) (ifaceFields flds)
  1279. ifaceConDecls (TupleTyCon { data_con = con }) _ = IfDataTyCon [ifaceConDecl con] False []
  1280. ifaceConDecls (SumTyCon { data_cons = cons }) flds = IfDataTyCon (map ifaceConDecl cons) (ifaceOverloaded flds) (ifaceFields flds)
  1281. ifaceConDecls (AbstractTyCon distinct) _ = IfAbstractTyCon distinct
  1282. -- The AbstractTyCon case happens when a TyCon has been trimmed
  1283. -- during tidying.
  1284. -- Furthermore, tyThingToIfaceDecl is also used in TcRnDriver
  1285. -- for GHCi, when browsing a module, in which case the
  1286. -- AbstractTyCon and TupleTyCon cases are perfectly sensible.
  1287. -- (Tuple declarations are not serialised into interface files.)
  1288. ifaceConDecl data_con
  1289. = IfCon { ifConOcc = getOccName (dataConName data_con),
  1290. ifConInfix = dataConIsInfix data_con,
  1291. ifConWrapper = isJust (dataConWrapId_maybe data_con),
  1292. ifConExTvs = map toIfaceForAllBndr ex_bndrs',
  1293. ifConEqSpec = map (to_eq_spec . eqSpecPair) eq_spec,
  1294. ifConCtxt = tidyToIfaceContext con_env2 theta,
  1295. ifConArgTys = map (tidyToIfaceType con_env2) arg_tys,
  1296. ifConFields = map (nameOccName . flSelector)
  1297. (dataConFieldLabels data_con),
  1298. ifConStricts = map (toIfaceBang con_env2)
  1299. (dataConImplBangs data_con),
  1300. ifConSrcStricts = map toIfaceSrcBang
  1301. (dataConSrcBangs data_con)}
  1302. where
  1303. (univ_tvs, _ex_tvs, eq_spec, theta, arg_tys, _)
  1304. = dataConFullSig data_con
  1305. ex_bndrs = dataConExTyVarBinders data_con
  1306. -- Tidy the univ_tvs of the data constructor to be identical
  1307. -- to the tyConTyVars of the type constructor. This means
  1308. -- (a) we don't need to redundantly put them into the interface file
  1309. -- (b) when pretty-printing an Iface data declaration in H98-style syntax,
  1310. -- we know that the type variables will line up
  1311. -- The latter (b) is important because we pretty-print type constructors
  1312. -- by converting to IfaceSyn and pretty-printing that
  1313. con_env1 = (fst tc_env1, mkVarEnv (zipEqual "ifaceConDecl" univ_tvs tc_tyvars))
  1314. -- A bit grimy, perhaps, but it's simple!
  1315. (con_env2, ex_bndrs') = tidyTyVarBinders con_env1 ex_bndrs
  1316. to_eq_spec (tv,ty) = (tidyTyVar con_env2 tv, tidyToIfaceType con_env2 ty)
  1317. ifaceOverloaded flds = case dFsEnvElts flds of
  1318. fl:_ -> flIsOverloaded fl
  1319. [] -> False
  1320. ifaceFields flds = map flLabel $ dFsEnvElts flds
  1321. toIfaceBang :: TidyEnv -> HsImplBang -> IfaceBang
  1322. toIfaceBang _ HsLazy = IfNoBang
  1323. toIfaceBang _ (HsUnpack Nothing) = IfUnpack
  1324. toIfaceBang env (HsUnpack (Just co)) = IfUnpackCo (toIfaceCoercion (tidyCo env co))
  1325. toIfaceBang _ HsStrict = IfStrict
  1326. toIfaceSrcBang :: HsSrcBang -> IfaceSrcBang
  1327. toIfaceSrcBang (HsSrcBang _ unpk bang) = IfSrcBang unpk bang
  1328. classToIfaceDecl :: TidyEnv -> Class -> (TidyEnv, IfaceDecl)
  1329. classToIfaceDecl env clas
  1330. = ( env1
  1331. , IfaceClass { ifCtxt = tidyToIfaceContext env1 sc_theta,
  1332. ifName = getOccName tycon,
  1333. ifRoles = tyConRoles (classTyCon clas),
  1334. ifBinders = toIfaceTyVarBinders tc_binders,
  1335. ifFDs = map toIfaceFD clas_fds,
  1336. ifATs = map toIfaceAT clas_ats,
  1337. ifSigs = map toIfaceClassOp op_stuff,
  1338. ifMinDef = fmap getOccFS (classMinimalDef clas) })
  1339. where
  1340. (_, clas_fds, sc_theta, _, clas_ats, op_stuff)
  1341. = classExtraBigSig clas
  1342. tycon = classTyCon clas
  1343. (env1, tc_binders) = tidyTyConBinders env (tyConBinders tycon)
  1344. toIfaceAT :: ClassATItem -> IfaceAT
  1345. toIfaceAT (ATI tc def)
  1346. = IfaceAT if_decl (fmap (tidyToIfaceType env2 . fst) def)
  1347. where
  1348. (env2, if_decl) = tyConToIfaceDecl env1 tc
  1349. toIfaceClassOp (sel_id, def_meth)
  1350. = ASSERT( sel_tyvars == binderVars tc_binders )
  1351. IfaceClassOp (getOccName sel_id)
  1352. (tidyToIfaceType env1 op_ty)
  1353. (fmap toDmSpec def_meth)
  1354. where
  1355. -- Be careful when splitting the type, because of things
  1356. -- like class Foo a where
  1357. -- op :: (?x :: String) => a -> a
  1358. -- and class Baz a where
  1359. -- op :: (Ord a) => a -> a
  1360. (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
  1361. op_ty = funResultTy rho_ty
  1362. toDmSpec :: (Name, DefMethSpec Type) -> DefMethSpec IfaceType
  1363. toDmSpec (_, VanillaDM) = VanillaDM
  1364. toDmSpec (_, GenericDM dm_ty) = GenericDM (tidyToIfaceType env1 dm_ty)
  1365. toIfaceFD (tvs1, tvs2) = (map (tidyTyVar env1) tvs1
  1366. ,map (tidyTyVar env1) tvs2)
  1367. --------------------------
  1368. tidyToIfaceType :: TidyEnv -> Type -> IfaceType
  1369. tidyToIfaceType env ty = toIfaceType (tidyType env ty)
  1370. tidyToIfaceTcArgs :: TidyEnv -> TyCon -> [Type] -> IfaceTcArgs
  1371. tidyToIfaceTcArgs env tc tys = toIfaceTcArgs tc (tidyTypes env tys)
  1372. tidyToIfaceContext :: TidyEnv -> ThetaType -> IfaceContext
  1373. tidyToIfaceContext env theta = map (tidyToIfaceType env) theta
  1374. toIfaceTyVarBinder :: TyVarBndr TyVar vis -> TyVarBndr IfaceTvBndr vis
  1375. toIfaceTyVarBinder (TvBndr tv vis) = TvBndr (toIfaceTvBndr tv) vis
  1376. toIfaceTyVarBinders :: [TyVarBndr TyVar vis] -> [TyVarBndr IfaceTvBndr vis]
  1377. toIfaceTyVarBinders = map toIfaceTyVarBinder
  1378. tidyTyConBinder :: TidyEnv -> TyConBinder -> (TidyEnv, TyConBinder)
  1379. -- If the type variable "binder" is in scope, don't re-bind it
  1380. -- In a class decl, for example, the ATD binders mention
  1381. -- (amd must mention) the class tyvars
  1382. tidyTyConBinder env@(_, subst) tvb@(TvBndr tv vis)
  1383. = case lookupVarEnv subst tv of
  1384. Just tv' -> (env, TvBndr tv' vis)
  1385. Nothing -> tidyTyVarBinder env tvb
  1386. tidyTyConBinders :: TidyEnv -> [TyConBinder] -> (TidyEnv, [TyConBinder])
  1387. tidyTyConBinders = mapAccumL tidyTyConBinder
  1388. tidyTyVar :: TidyEnv -> TyVar -> FastString
  1389. tidyTyVar (_, subst) tv = toIfaceTyVar (lookupVarEnv subst tv `orElse` tv)
  1390. --------------------------
  1391. instanceToIfaceInst :: ClsInst -> IfaceClsInst
  1392. instanceToIfaceInst (ClsInst { is_dfun = dfun_id, is_flag = oflag
  1393. , is_cls_nm = cls_name, is_cls = cls
  1394. , is_tcs = mb_tcs
  1395. , is_orphan = orph })
  1396. = ASSERT( cls_name == className cls )
  1397. IfaceClsInst { ifDFun = dfun_name,
  1398. ifOFlag = oflag,
  1399. ifInstCls = cls_name,
  1400. ifInstTys = map do_rough mb_tcs,
  1401. ifInstOrph = orph }
  1402. where
  1403. do_rough Nothing = Nothing
  1404. do_rough (Just n) = Just (toIfaceTyCon_name n)
  1405. dfun_name = idName dfun_id
  1406. --------------------------
  1407. famInstToIfaceFamInst :: FamInst -> IfaceFamInst
  1408. famInstToIfaceFamInst (FamInst { fi_axiom = axiom,
  1409. fi_fam = fam,
  1410. fi_tcs = roughs })
  1411. = IfaceFamInst { ifFamInstAxiom = coAxiomName axiom
  1412. , ifFamInstFam = fam
  1413. , ifFamInstTys = map do_rough roughs
  1414. , ifFamInstOrph = orph }
  1415. where
  1416. do_rough Nothing = Nothing
  1417. do_rough (Just n) = Just (toIfaceTyCon_name n)
  1418. fam_decl = tyConName $ coAxiomTyCon axiom
  1419. mod = ASSERT( isExternalName (coAxiomName axiom) )
  1420. nameModule (coAxiomName axiom)
  1421. is_local name = nameIsLocalOrFrom mod name
  1422. lhs_names = filterNameSet is_local (orphNamesOfCoCon axiom)
  1423. orph | is_local fam_decl
  1424. = NotOrphan (nameOccName fam_decl)
  1425. | otherwise
  1426. = chooseOrphanAnchor lhs_names
  1427. --------------------------
  1428. toIfaceLetBndr :: Id -> IfaceLetBndr
  1429. toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
  1430. (toIfaceType (idType id))
  1431. (toIfaceIdInfo (idInfo id))
  1432. -- Put into the interface file any IdInfo that CoreTidy.tidyLetBndr
  1433. -- has left on the Id. See Note [IdInfo on nested let-bindings] in IfaceSyn
  1434. --------------------------t
  1435. toIfaceIdDetails :: IdDetails -> IfaceIdDetails
  1436. toIfaceIdDetails VanillaId = IfVanillaId
  1437. toIfaceIdDetails (DFunId {}) = IfDFunId
  1438. toIfaceIdDetails (RecSelId { sel_naughty = n
  1439. , sel_tycon = tc }) =
  1440. let iface = case tc of
  1441. RecSelData ty_con -> Left (toIfaceTyCon ty_con)
  1442. RecSelPatSyn pat_syn -> Right (patSynToIfaceDecl pat_syn)
  1443. in IfRecSelId iface n
  1444. -- The remaining cases are all "implicit Ids" which don't
  1445. -- appear in interface files at all
  1446. toIfaceIdDetails other = pprTrace "toIfaceIdDetails" (ppr other)
  1447. IfVanillaId -- Unexpected; the other
  1448. toIfaceIdInfo :: IdInfo -> IfaceIdInfo
  1449. toIfaceIdInfo id_info
  1450. = case catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
  1451. inline_hsinfo, unfold_hsinfo] of
  1452. [] -> NoInfo
  1453. infos -> HasInfo infos
  1454. -- NB: strictness and arity must appear in the list before unfolding
  1455. -- See TcIface.tcUnfolding
  1456. where
  1457. ------------ Arity --------------
  1458. arity_info = arityInfo id_info
  1459. arity_hsinfo | arity_info == 0 = Nothing
  1460. | otherwise = Just (HsArity arity_info)
  1461. ------------ Caf Info --------------
  1462. caf_info = cafInfo id_info
  1463. caf_hsinfo = case caf_info of
  1464. NoCafRefs -> Just HsNoCafRefs
  1465. _other -> Nothing
  1466. ------------ Strictness --------------
  1467. -- No point in explicitly exporting TopSig
  1468. sig_info = strictnessInfo id_info
  1469. strict_hsinfo | not (isTopSig sig_info) = Just (HsStrictness sig_info)
  1470. | otherwise = Nothing
  1471. ------------ Unfolding --------------
  1472. unfold_hsinfo = toIfUnfolding loop_breaker (unfoldingInfo id_info)
  1473. loop_breaker = isStrongLoopBreaker (occInfo id_info)
  1474. ------------ Inline prag --------------
  1475. inline_prag = inlinePragInfo id_info
  1476. inline_hsinfo | isDefaultInlinePragma inline_prag = Nothing
  1477. | otherwise = Just (HsInline inline_prag)
  1478. --------------------------
  1479. toIfUnfolding :: Bool -> Unfolding -> Maybe IfaceInfoItem
  1480. toIfUnfolding lb (CoreUnfolding { uf_tmpl = rhs
  1481. , uf_src = src
  1482. , uf_guidance = guidance })
  1483. = Just $ HsUnfold lb $
  1484. case src of
  1485. InlineStable
  1486. -> case guidance of
  1487. UnfWhen {ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok }
  1488. -> IfInlineRule arity unsat_ok boring_ok if_rhs
  1489. _other -> IfCoreUnfold True if_rhs
  1490. InlineCompulsory -> IfCompulsory if_rhs
  1491. InlineRhs -> IfCoreUnfold False if_rhs
  1492. -- Yes, even if guidance is UnfNever, expose the unfolding
  1493. -- If we didn't want to expose the unfolding, TidyPgm would
  1494. -- have stuck in NoUnfolding. For supercompilation we want
  1495. -- to see that unfolding!
  1496. where
  1497. if_rhs = toIfaceExpr rhs
  1498. toIfUnfolding lb (DFunUnfolding { df_bndrs = bndrs, df_args = args })
  1499. = Just (HsUnfold lb (IfDFunUnfold (map toIfaceBndr bndrs) (map toIfaceExpr args)))
  1500. -- No need to serialise the data constructor;
  1501. -- we can recover it from the type of the dfun
  1502. toIfUnfolding _ _
  1503. = Nothing
  1504. --------------------------
  1505. coreRuleToIfaceRule :: CoreRule -> IfaceRule
  1506. coreRuleToIfaceRule (BuiltinRule { ru_fn = fn})
  1507. = pprTrace "toHsRule: builtin" (ppr fn) $
  1508. bogusIfaceRule fn
  1509. coreRuleToIfaceRule (Rule { ru_name = name, ru_fn = fn,
  1510. ru_act = act, ru_bndrs = bndrs,
  1511. ru_args = args, ru_rhs = rhs,
  1512. ru_orphan = orph, ru_auto = auto })
  1513. = IfaceRule { ifRuleName = name, ifActivation = act,
  1514. ifRuleBndrs = map toIfaceBndr bndrs,
  1515. ifRuleHead = fn,
  1516. ifRuleArgs = map do_arg args,
  1517. ifRuleRhs = toIfaceExpr rhs,
  1518. ifRuleAuto = auto,
  1519. ifRuleOrph = orph }
  1520. where
  1521. -- For type args we must remove synonyms from the outermost
  1522. -- level. Reason: so that when we read it back in we'll
  1523. -- construct the same ru_rough field as we have right now;
  1524. -- see tcIfaceRule
  1525. do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
  1526. do_arg (Coercion co) = IfaceCo (toIfaceCoercion co)
  1527. do_arg arg = toIfaceExpr arg
  1528. bogusIfaceRule :: Name -> IfaceRule
  1529. bogusIfaceRule id_name
  1530. = IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
  1531. ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
  1532. ifRuleRhs = IfaceExt id_name, ifRuleOrph = IsOrphan,
  1533. ifRuleAuto = True }
  1534. ---------------------
  1535. toIfaceExpr :: CoreExpr -> IfaceExpr
  1536. toIfaceExpr (Var v) = toIfaceVar v
  1537. toIfaceExpr (Lit l) = IfaceLit l
  1538. toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
  1539. toIfaceExpr (Coercion co) = IfaceCo (toIfaceCoercion co)
  1540. toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x, toIfaceOneShot x) (toIfaceExpr b)
  1541. toIfaceExpr (App f a) = toIfaceApp f [a]
  1542. toIfaceExpr (Case s x ty as)
  1543. | null as = IfaceECase (toIfaceExpr s) (toIfaceType ty)
  1544. | otherwise = IfaceCase (toIfaceExpr s) (getOccFS x) (map toIfaceAlt as)
  1545. toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
  1546. toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (toIfaceCoercion co)
  1547. toIfaceExpr (Tick t e)
  1548. | Just t' <- toIfaceTickish t = IfaceTick t' (toIfaceExpr e)
  1549. | otherwise = toIfaceExpr e
  1550. toIfaceOneShot :: Id -> IfaceOneShot
  1551. toIfaceOneShot id | isId id
  1552. , OneShotLam <- oneShotInfo (idInfo id)
  1553. = IfaceOneShot
  1554. | otherwise
  1555. = IfaceNoOneShot
  1556. ---------------------
  1557. toIfaceTickish :: Tickish Id -> Maybe IfaceTickish
  1558. toIfaceTickish (ProfNote cc tick push) = Just (IfaceSCC cc tick push)
  1559. toIfaceTickish (HpcTick modl ix) = Just (IfaceHpcTick modl ix)
  1560. toIfaceTickish (SourceNote src names) = Just (IfaceSource src names)
  1561. toIfaceTickish (Breakpoint {}) = Nothing
  1562. -- Ignore breakpoints, since they are relevant only to GHCi, and
  1563. -- should not be serialised (Trac #8333)
  1564. ---------------------
  1565. toIfaceBind :: Bind Id -> IfaceBinding
  1566. toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
  1567. toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
  1568. ---------------------
  1569. toIfaceAlt :: (AltCon, [Var], CoreExpr)
  1570. -> (IfaceConAlt, [FastString], IfaceExpr)
  1571. toIfaceAlt (c,bs,r) = (toIfaceCon c, map getOccFS bs, toIfaceExpr r)
  1572. ---------------------
  1573. toIfaceCon :: AltCon -> IfaceConAlt
  1574. toIfaceCon (DataAlt dc) = IfaceDataAlt (getName dc)
  1575. toIfaceCon (LitAlt l) = IfaceLitAlt l
  1576. toIfaceCon DEFAULT = IfaceDefault
  1577. ---------------------
  1578. toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr
  1579. toIfaceApp (App f a) as = toIfaceApp f (a:as)
  1580. toIfaceApp (Var v) as
  1581. = case isDataConWorkId_maybe v of
  1582. -- We convert the *worker* for tuples into IfaceTuples
  1583. Just dc | saturated
  1584. , Just tup_sort <- tyConTuple_maybe tc
  1585. -> IfaceTuple tup_sort tup_args
  1586. where
  1587. val_args = dropWhile isTypeArg as
  1588. saturated = val_args `lengthIs` idArity v
  1589. tup_args = map toIfaceExpr val_args
  1590. tc = dataConTyCon dc
  1591. _ -> mkIfaceApps (toIfaceVar v) as
  1592. toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
  1593. mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr
  1594. mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
  1595. ---------------------
  1596. toIfaceVar :: Id -> IfaceExpr
  1597. toIfaceVar v
  1598. | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
  1599. -- Foreign calls have special syntax
  1600. | isExternalName name = IfaceExt name
  1601. | otherwise = IfaceLcl (getOccFS name)
  1602. where name = idName v