PageRenderTime 219ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 1ms

/compiler/iface/MkIface.lhs

https://bitbucket.org/carter/ghc
Haskell | 1851 lines | 1248 code | 250 blank | 353 comment | 55 complexity | 0a10bcd2d5e130a2f1e748d0980bf01c 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 Annotations
  51. import CoreSyn
  52. import CoreFVs
  53. import Class
  54. import Kind
  55. import TyCon
  56. import Coercion ( coAxiomSplitLHS )
  57. import DataCon
  58. import Type
  59. import TcType
  60. import InstEnv
  61. import FamInstEnv
  62. import TcRnMonad
  63. import HsSyn
  64. import HscTypes
  65. import Finder
  66. import DynFlags
  67. import VarEnv
  68. import VarSet
  69. import Var
  70. import Name
  71. import Avail
  72. import RdrName
  73. import NameEnv
  74. import NameSet
  75. import Module
  76. import BinIface
  77. import ErrUtils
  78. import Digraph
  79. import SrcLoc
  80. import Outputable
  81. import BasicTypes hiding ( SuccessFlag(..) )
  82. import UniqFM
  83. import Unique
  84. import Util hiding ( eqListBy )
  85. import FastString
  86. import Maybes
  87. import ListSetOps
  88. import Binary
  89. import Fingerprint
  90. import Bag
  91. import Exception
  92. import Control.Monad
  93. import Data.Function
  94. import Data.List
  95. import Data.Map (Map)
  96. import qualified Data.Map as Map
  97. import Data.Ord
  98. import Data.IORef
  99. import System.Directory
  100. import System.FilePath
  101. \end{code}
  102. %************************************************************************
  103. %* *
  104. \subsection{Completing an interface}
  105. %* *
  106. %************************************************************************
  107. \begin{code}
  108. mkIface :: HscEnv
  109. -> Maybe Fingerprint -- The old fingerprint, if we have it
  110. -> ModDetails -- The trimmed, tidied interface
  111. -> ModGuts -- Usages, deprecations, etc
  112. -> IO (Messages,
  113. Maybe (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_boot = is_boot,
  120. mg_used_names = used_names,
  121. mg_used_th = used_th,
  122. mg_deps = deps,
  123. mg_dir_imps = dir_imp_mods,
  124. mg_rdr_env = rdr_env,
  125. mg_fix_env = fix_env,
  126. mg_warns = warns,
  127. mg_hpc_info = hpc_info,
  128. mg_safe_haskell = safe_mode,
  129. mg_trust_pkg = self_trust,
  130. mg_dependent_files = dependent_files
  131. }
  132. = mkIface_ hsc_env maybe_old_fingerprint
  133. this_mod is_boot used_names used_th deps rdr_env fix_env
  134. warns hpc_info dir_imp_mods self_trust dependent_files
  135. safe_mode mod_details
  136. -- | make an interface from the results of typechecking only. Useful
  137. -- for non-optimising compilation, or where we aren't generating any
  138. -- object code at all ('HscNothing').
  139. mkIfaceTc :: HscEnv
  140. -> Maybe Fingerprint -- The old fingerprint, if we have it
  141. -> SafeHaskellMode -- The safe haskell mode
  142. -> ModDetails -- gotten from mkBootModDetails, probably
  143. -> TcGblEnv -- Usages, deprecations, etc
  144. -> IO (Messages, Maybe (ModIface, Bool))
  145. mkIfaceTc hsc_env maybe_old_fingerprint safe_mode mod_details
  146. tc_result@TcGblEnv{ tcg_mod = this_mod,
  147. tcg_src = hsc_src,
  148. tcg_imports = imports,
  149. tcg_rdr_env = rdr_env,
  150. tcg_fix_env = fix_env,
  151. tcg_warns = warns,
  152. tcg_hpc = other_hpc_info,
  153. tcg_th_splice_used = tc_splice_used,
  154. tcg_dependent_files = dependent_files
  155. }
  156. = do
  157. let used_names = mkUsedNames tc_result
  158. deps <- mkDependencies tc_result
  159. let hpc_info = emptyHpcInfo other_hpc_info
  160. used_th <- readIORef tc_splice_used
  161. dep_files <- (readIORef dependent_files)
  162. mkIface_ hsc_env maybe_old_fingerprint
  163. this_mod (isHsBoot hsc_src) used_names used_th deps rdr_env
  164. fix_env warns hpc_info (imp_mods imports)
  165. (imp_trust_own_pkg imports) dep_files safe_mode mod_details
  166. mkUsedNames :: TcGblEnv -> NameSet
  167. mkUsedNames TcGblEnv{ tcg_dus = dus } = allUses dus
  168. -- | Extract information from the rename and typecheck phases to produce
  169. -- a dependencies information for the module being compiled.
  170. mkDependencies :: TcGblEnv -> IO Dependencies
  171. mkDependencies
  172. TcGblEnv{ tcg_mod = mod,
  173. tcg_imports = imports,
  174. tcg_th_used = th_var
  175. }
  176. = do
  177. -- Template Haskell used?
  178. th_used <- readIORef th_var
  179. let dep_mods = eltsUFM (delFromUFM (imp_dep_mods imports) (moduleName mod))
  180. -- M.hi-boot can be in the imp_dep_mods, but we must remove
  181. -- it before recording the modules on which this one depends!
  182. -- (We want to retain M.hi-boot in imp_dep_mods so that
  183. -- loadHiBootInterface can see if M's direct imports depend
  184. -- on M.hi-boot, and hence that we should do the hi-boot consistency
  185. -- check.)
  186. pkgs | th_used = insertList thPackageId (imp_dep_pkgs imports)
  187. | otherwise = imp_dep_pkgs imports
  188. -- Set the packages required to be Safe according to Safe Haskell.
  189. -- See Note [RnNames . Tracking Trust Transitively]
  190. sorted_pkgs = sortBy stablePackageIdCmp pkgs
  191. trust_pkgs = imp_trust_pkgs imports
  192. dep_pkgs' = map (\x -> (x, x `elem` trust_pkgs)) sorted_pkgs
  193. return Deps { dep_mods = sortBy (stableModuleNameCmp `on` fst) dep_mods,
  194. dep_pkgs = dep_pkgs',
  195. dep_orphs = sortBy stableModuleCmp (imp_orphs imports),
  196. dep_finsts = sortBy stableModuleCmp (imp_finsts imports) }
  197. -- sort to get into canonical order
  198. -- NB. remember to use lexicographic ordering
  199. mkIface_ :: HscEnv -> Maybe Fingerprint -> Module -> IsBootInterface
  200. -> NameSet -> Bool -> Dependencies -> GlobalRdrEnv
  201. -> NameEnv FixItem -> Warnings -> HpcInfo
  202. -> ImportedMods -> Bool
  203. -> [FilePath]
  204. -> SafeHaskellMode
  205. -> ModDetails
  206. -> IO (Messages, Maybe (ModIface, Bool))
  207. mkIface_ hsc_env maybe_old_fingerprint
  208. this_mod is_boot used_names used_th deps rdr_env fix_env src_warns
  209. hpc_info dir_imp_mods pkg_trust_req dependent_files safe_mode
  210. ModDetails{ md_insts = insts,
  211. md_fam_insts = fam_insts,
  212. md_rules = rules,
  213. md_anns = anns,
  214. md_vect_info = vect_info,
  215. md_types = type_env,
  216. md_exports = exports }
  217. -- NB: notice that mkIface does not look at the bindings
  218. -- only at the TypeEnv. The previous Tidy phase has
  219. -- put exactly the info into the TypeEnv that we want
  220. -- to expose in the interface
  221. = do { usages <- mkUsageInfo hsc_env this_mod dir_imp_mods used_names dependent_files
  222. ; let { entities = typeEnvElts type_env ;
  223. decls = [ tyThingToIfaceDecl entity
  224. | entity <- entities,
  225. let name = getName entity,
  226. not (isImplicitTyThing entity),
  227. -- No implicit Ids and class tycons in the interface file
  228. not (isWiredInName name),
  229. -- Nor wired-in things; the compiler knows about them anyhow
  230. nameIsLocalOrFrom this_mod name ]
  231. -- Sigh: see Note [Root-main Id] in TcRnDriver
  232. ; fixities = [(occ,fix) | FixItem occ fix <- nameEnvElts fix_env]
  233. ; warns = src_warns
  234. ; iface_rules = map (coreRuleToIfaceRule this_mod) rules
  235. ; iface_insts = map instanceToIfaceInst insts
  236. ; iface_fam_insts = map famInstToIfaceFamInst fam_insts
  237. ; iface_vect_info = flattenVectInfo vect_info
  238. ; trust_info = setSafeMode safe_mode
  239. ; intermediate_iface = ModIface {
  240. mi_module = this_mod,
  241. mi_boot = is_boot,
  242. mi_deps = deps,
  243. mi_usages = usages,
  244. mi_exports = mkIfaceExports exports,
  245. -- Sort these lexicographically, so that
  246. -- the result is stable across compilations
  247. mi_insts = sortBy cmp_inst iface_insts,
  248. mi_fam_insts = sortBy cmp_fam_inst iface_fam_insts,
  249. mi_rules = sortBy cmp_rule iface_rules,
  250. mi_vect_info = iface_vect_info,
  251. mi_fixities = fixities,
  252. mi_warns = warns,
  253. mi_anns = mkIfaceAnnotations anns,
  254. mi_globals = maybeGlobalRdrEnv rdr_env,
  255. -- Left out deliberately: filled in by addFingerprints
  256. mi_iface_hash = fingerprint0,
  257. mi_mod_hash = fingerprint0,
  258. mi_flag_hash = fingerprint0,
  259. mi_exp_hash = fingerprint0,
  260. mi_used_th = used_th,
  261. mi_orphan_hash = fingerprint0,
  262. mi_orphan = False, -- Always set by addFingerprints, but
  263. -- it's a strict field, so we can't omit it.
  264. mi_finsts = False, -- Ditto
  265. mi_decls = deliberatelyOmitted "decls",
  266. mi_hash_fn = deliberatelyOmitted "hash_fn",
  267. mi_hpc = isHpcUsed hpc_info,
  268. mi_trust = trust_info,
  269. mi_trust_pkg = pkg_trust_req,
  270. -- And build the cached values
  271. mi_warn_fn = mkIfaceWarnCache warns,
  272. mi_fix_fn = mkIfaceFixCache fixities }
  273. }
  274. ; (new_iface, no_change_at_all)
  275. <- {-# SCC "versioninfo" #-}
  276. addFingerprints hsc_env maybe_old_fingerprint
  277. intermediate_iface decls
  278. -- Warn about orphans
  279. ; let warn_orphs = wopt Opt_WarnOrphans dflags
  280. warn_auto_orphs = wopt Opt_WarnAutoOrphans dflags
  281. orph_warnings --- Laziness means no work done unless -fwarn-orphans
  282. | warn_orphs || warn_auto_orphs = rule_warns `unionBags` inst_warns
  283. | otherwise = emptyBag
  284. errs_and_warns = (orph_warnings, emptyBag)
  285. unqual = mkPrintUnqualified dflags rdr_env
  286. inst_warns = listToBag [ instOrphWarn dflags unqual d
  287. | (d,i) <- insts `zip` iface_insts
  288. , isNothing (ifInstOrph i) ]
  289. rule_warns = listToBag [ ruleOrphWarn dflags unqual this_mod r
  290. | r <- iface_rules
  291. , isNothing (ifRuleOrph r)
  292. , if ifRuleAuto r then warn_auto_orphs
  293. else warn_orphs ]
  294. ; if errorsFound dflags errs_and_warns
  295. then return ( errs_and_warns, Nothing )
  296. else do {
  297. -- Debug printing
  298. ; dumpIfSet_dyn dflags Opt_D_dump_hi "FINAL INTERFACE"
  299. (pprModIface new_iface)
  300. -- bug #1617: on reload we weren't updating the PrintUnqualified
  301. -- correctly. This stems from the fact that the interface had
  302. -- not changed, so addFingerprints returns the old ModIface
  303. -- with the old GlobalRdrEnv (mi_globals).
  304. ; let final_iface = new_iface{ mi_globals = maybeGlobalRdrEnv rdr_env }
  305. ; return (errs_and_warns, Just (final_iface, no_change_at_all)) }}
  306. where
  307. cmp_rule = comparing ifRuleName
  308. -- Compare these lexicographically by OccName, *not* by unique,
  309. -- because the latter is not stable across compilations:
  310. cmp_inst = comparing (nameOccName . ifDFun)
  311. cmp_fam_inst = comparing (nameOccName . ifFamInstTcName)
  312. dflags = hsc_dflags hsc_env
  313. -- We only fill in mi_globals if the module was compiled to byte
  314. -- code. Otherwise, the compiler may not have retained all the
  315. -- top-level bindings and they won't be in the TypeEnv (see
  316. -- Desugar.addExportFlagsAndRules). The mi_globals field is used
  317. -- by GHCi to decide whether the module has its full top-level
  318. -- scope available. (#5534)
  319. maybeGlobalRdrEnv :: GlobalRdrEnv -> Maybe GlobalRdrEnv
  320. maybeGlobalRdrEnv rdr_env
  321. | targetRetainsAllBindings (hscTarget dflags) = Just rdr_env
  322. | otherwise = Nothing
  323. deliberatelyOmitted :: String -> a
  324. deliberatelyOmitted x = panic ("Deliberately omitted: " ++ x)
  325. ifFamInstTcName = ifFamInstFam
  326. flattenVectInfo (VectInfo { vectInfoVar = vVar
  327. , vectInfoTyCon = vTyCon
  328. , vectInfoScalarVars = vScalarVars
  329. , vectInfoScalarTyCons = vScalarTyCons
  330. }) =
  331. IfaceVectInfo
  332. { ifaceVectInfoVar = [Var.varName v | (v, _ ) <- varEnvElts vVar]
  333. , ifaceVectInfoTyCon = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t /= t_v]
  334. , ifaceVectInfoTyConReuse = [tyConName t | (t, t_v) <- nameEnvElts vTyCon, t == t_v]
  335. , ifaceVectInfoScalarVars = [Var.varName v | v <- varSetElems vScalarVars]
  336. , ifaceVectInfoScalarTyCons = nameSetToList vScalarTyCons
  337. }
  338. -----------------------------
  339. writeIfaceFile :: DynFlags -> ModLocation -> ModIface -> IO ()
  340. writeIfaceFile dflags location new_iface
  341. = do createDirectoryIfMissing True (takeDirectory hi_file_path)
  342. writeBinIface dflags hi_file_path new_iface
  343. where hi_file_path = ml_hi_file location
  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 _ -> ghcError (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 False
  973. case read_result of
  974. Failed err -> do
  975. traceIf (text "FYI: cannont 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. | dopt 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 -> IfaceDecl
  1251. -- We *do* tidy Axioms, because they are not (and cannot
  1252. -- conveniently be) built in tidy form
  1253. coAxiomToIfaceDecl ax
  1254. = IfaceAxiom { ifName = name
  1255. , ifTyVars = toIfaceTvBndrs tv_bndrs
  1256. , ifLHS = tidyToIfaceType env (coAxiomLHS ax)
  1257. , ifRHS = tidyToIfaceType env (coAxiomRHS ax) }
  1258. where
  1259. name = getOccName ax
  1260. (env, tv_bndrs) = tidyTyVarBndrs emptyTidyEnv (coAxiomTyVars ax)
  1261. -----------------
  1262. tyConToIfaceDecl :: TidyEnv -> TyCon -> IfaceDecl
  1263. -- We *do* tidy TyCons, because they are not (and cannot
  1264. -- conveniently be) built in tidy form
  1265. tyConToIfaceDecl env tycon
  1266. | Just clas <- tyConClass_maybe tycon
  1267. = classToIfaceDecl env clas
  1268. | Just syn_rhs <- synTyConRhs_maybe tycon
  1269. = IfaceSyn { ifName = getOccName tycon,
  1270. ifTyVars = toIfaceTvBndrs tyvars,
  1271. ifSynRhs = to_ifsyn_rhs syn_rhs,
  1272. ifSynKind = tidyToIfaceType env1 (synTyConResKind tycon) }
  1273. | isAlgTyCon tycon
  1274. = IfaceData { ifName = getOccName tycon,
  1275. ifCType = tyConCType tycon,
  1276. ifTyVars = toIfaceTvBndrs tyvars,
  1277. ifCtxt = tidyToIfaceContext env1 (tyConStupidTheta tycon),
  1278. ifCons = ifaceConDecls (algTyConRhs tycon),
  1279. ifRec = boolToRecFlag (isRecursiveTyCon tycon),
  1280. ifGadtSyntax = isGadtSyntaxTyCon tycon,
  1281. ifAxiom = fmap coAxiomName (tyConFamilyCoercion_maybe tycon) }
  1282. | isForeignTyCon tycon
  1283. = IfaceForeign { ifName = getOccName tycon,
  1284. ifExtName = tyConExtName tycon }
  1285. | otherwise = pprPanic "toIfaceDecl" (ppr tycon)
  1286. where
  1287. (env1, tyvars) = tidyTyVarBndrs env (tyConTyVars tycon)
  1288. to_ifsyn_rhs (SynFamilyTyCon a b) = SynFamilyTyCon a b
  1289. to_ifsyn_rhs (SynonymTyCon ty) = SynonymTyCon (tidyToIfaceType env1 ty)
  1290. ifaceConDecls (NewTyCon { data_con = con }) = IfNewTyCon (ifaceConDecl con)
  1291. ifaceConDecls (DataTyCon { data_cons = cons }) = IfDataTyCon (map ifaceConDecl cons)
  1292. ifaceConDecls (DataFamilyTyCon {}) = IfDataFamTyCon
  1293. ifaceConDecls (AbstractTyCon distinct) = IfAbstractTyCon distinct
  1294. -- The last case happens when a TyCon has been trimmed during tidying
  1295. -- Furthermore, tyThingToIfaceDecl is also used
  1296. -- in TcRnDriver for GHCi, when browsing a module, in which case the
  1297. -- AbstractTyCon case is perfectly sensible.
  1298. ifaceConDecl data_con
  1299. = IfCon { ifConOcc = getOccName (dataConName data_con),
  1300. ifConInfix = dataConIsInfix data_con,
  1301. ifConWrapper = isJust (dataConWrapId_maybe data_con),
  1302. ifConUnivTvs = toIfaceTvBndrs univ_tvs',
  1303. ifConExTvs = toIfaceTvBndrs ex_tvs',
  1304. ifConEqSpec = to_eq_spec eq_spec,
  1305. ifConCtxt = tidyToIfaceContext env3 theta,
  1306. ifConArgTys = map (tidyToIfaceType env3) arg_tys,
  1307. ifConFields = map getOccName
  1308. (dataConFieldLabels data_con),
  1309. ifConStricts = dataConStrictMarks data_con }
  1310. where
  1311. (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig data_con
  1312. (env2, univ_tvs') = tidyTyClTyVarBndrs env1 univ_tvs
  1313. (env3, ex_tvs') = tidyTyVarBndrs env2 ex_tvs
  1314. to_eq_spec spec = [ (getOccName (tidyTyVar env3 tv), tidyToIfaceType env3 ty)
  1315. | (tv,ty) <- spec]
  1316. classToIfaceDecl :: TidyEnv -> Class -> IfaceDecl
  1317. classToIfaceDecl env clas
  1318. = IfaceClass { ifCtxt = tidyToIfaceContext env1 sc_theta,
  1319. ifName = getOccName (classTyCon clas),
  1320. ifTyVars = toIfaceTvBndrs clas_tyvars',
  1321. ifFDs = map toIfaceFD clas_fds,
  1322. ifATs = map toIfaceAT clas_ats,
  1323. ifSigs = map toIfaceClassOp op_stuff,
  1324. ifRec = boolToRecFlag (isRecursiveTyCon tycon) }
  1325. where
  1326. (clas_tyvars, clas_fds, sc_theta, _, clas_ats, op_stuff)
  1327. = classExtraBigSig clas
  1328. tycon = classTyCon clas
  1329. (env1, clas_tyvars') = tidyTyVarBndrs env clas_tyvars
  1330. toIfaceAT :: ClassATItem -> IfaceAT
  1331. toIfaceAT (tc, defs)
  1332. = IfaceAT (tyConToIfaceDecl env1 tc) (map to_if_at_def defs)
  1333. where
  1334. to_if_at_def (ATD tvs pat_tys ty _loc)
  1335. = IfaceATD (toIfaceTvBndrs tvs')
  1336. (map (tidyToIfaceType env2) pat_tys)
  1337. (tidyToIfaceType env2 ty)
  1338. where
  1339. (env2, tvs') = tidyTyClTyVarBndrs env1 tvs
  1340. toIfaceClassOp (sel_id, def_meth)
  1341. = ASSERT(sel_tyvars == clas_tyvars)
  1342. IfaceClassOp (getOccName sel_id) (toDmSpec def_meth)
  1343. (tidyToIfaceType env1 op_ty)
  1344. where
  1345. -- Be careful when splitting the type, because of things
  1346. -- like class Foo a where
  1347. -- op :: (?x :: String) => a -> a
  1348. -- and class Baz a where
  1349. -- op :: (Ord a) => a -> a
  1350. (sel_tyvars, rho_ty) = splitForAllTys (idType sel_id)
  1351. op_ty = funResultTy rho_ty
  1352. toDmSpec NoDefMeth = NoDM
  1353. toDmSpec (GenDefMeth _) = GenericDM
  1354. toDmSpec (DefMeth _) = VanillaDM
  1355. toIfaceFD (tvs1, tvs2) = (map (getFS . tidyTyVar env1) tvs1,
  1356. map (getFS . tidyTyVar env1) tvs2)
  1357. --------------------------
  1358. tidyToIfaceType :: TidyEnv -> Type -> IfaceType
  1359. tidyToIfaceType env ty = toIfaceType (tidyType env ty)
  1360. tidyToIfaceContext :: TidyEnv -> ThetaType -> IfaceContext
  1361. tidyToIfaceContext env theta = map (tidyToIfaceType env) theta
  1362. tidyTyClTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
  1363. tidyTyClTyVarBndrs env tvs = mapAccumL tidyTyClTyVarBndr env tvs
  1364. tidyTyClTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
  1365. -- If the type variable "binder" is in scope, don't re-bind it
  1366. -- In a class decl, for example, the ATD binders mention
  1367. -- (amd must mention) the class tyvars
  1368. tidyTyClTyVarBndr env@(_, subst) tv
  1369. | Just tv' <- lookupVarEnv subst tv = (env, tv')
  1370. | otherwise = tidyTyVarBndr env tv
  1371. tidyTyVar :: TidyEnv -> TyVar -> TyVar
  1372. tidyTyVar (_, subst) tv = lookupVarEnv subst tv `orElse` tv
  1373. -- TcType.tidyTyVarOcc messes around with FlatSkols
  1374. getFS :: NamedThing a => a -> FastString
  1375. getFS x = occNameFS (getOccName x)
  1376. --------------------------
  1377. instanceToIfaceInst :: ClsInst -> IfaceClsInst
  1378. instanceToIfaceInst (ClsInst { is_dfun = dfun_id, is_flag = oflag,
  1379. is_cls = cls_name, is_tcs = mb_tcs })
  1380. = ASSERT( cls_name == className cls )
  1381. IfaceClsInst { ifDFun = dfun_name,
  1382. ifOFlag = oflag,
  1383. ifInstCls = cls_name,
  1384. ifInstTys = map do_rough mb_tcs,
  1385. ifInstOrph = orph }
  1386. where
  1387. do_rough Nothing = Nothing
  1388. do_rough (Just n) = Just (toIfaceTyCon_name n)
  1389. dfun_name = idName dfun_id
  1390. mod = ASSERT( isExternalName dfun_name ) nameModule dfun_name
  1391. is_local name = nameIsLocalOrFrom mod name
  1392. -- Compute orphanhood. See Note [Orphans] in IfaceSyn
  1393. (_, _, cls, tys) = tcSplitDFunTy (idType dfun_id)
  1394. -- Slightly awkward: we need the Class to get the fundeps
  1395. (tvs, fds) = classTvsFds cls
  1396. arg_names = [filterNameSet is_local (orphNamesOfType ty) | ty <- tys]
  1397. -- See Note [When exactly is an instance decl an orphan?] in IfaceSyn
  1398. orph | is_local cls_name = Just (nameOccName cls_name)
  1399. | all isJust mb_ns = ASSERT( not (null mb_ns) ) head mb_ns
  1400. | otherwise = Nothing
  1401. mb_ns :: [Maybe OccName] -- One for each fundep; a locally-defined name
  1402. -- that is not in the "determined" arguments
  1403. mb_ns | null fds = [choose_one arg_names]
  1404. | otherwise = map do_one fds
  1405. do_one (_ltvs, rtvs) = choose_one [ns | (tv,ns) <- tvs `zip` arg_names
  1406. , not (tv `elem` rtvs)]
  1407. choose_one :: [NameSet] -> Maybe OccName
  1408. choose_one nss = case nameSetToList (unionManyNameSets nss) of
  1409. [] -> Nothing
  1410. (n : _) -> Just (nameOccName n)
  1411. --------------------------
  1412. famInstToIfaceFamInst :: FamInst -> IfaceFamInst
  1413. famInstToIfaceFamInst (FamInst { fi_axiom = axiom,
  1414. fi_fam = fam,
  1415. fi_tcs = mb_tcs })
  1416. = IfaceFamInst { ifFamInstAxiom = coAxiomName axiom
  1417. , ifFamInstFam = fam
  1418. , ifFamInstTys = map do_rough mb_tcs
  1419. , ifFamInstOrph = orph }
  1420. where
  1421. do_rough Nothing = Nothing
  1422. do_rough (Just n) = Just (toIfaceTyCon_name n)
  1423. fam_decl = tyConName . fst $ coAxiomSplitLHS axiom
  1424. mod = ASSERT( isExternalName (coAxiomName axiom) )
  1425. nameModule (coAxiomName axiom)
  1426. is_local name = nameIsLocalOrFrom mod name
  1427. lhs_names = filterNameSet is_local (orphNamesOfType (coAxiomLHS axiom))
  1428. orph | is_local fam_decl
  1429. = Just (nameOccName fam_decl)
  1430. | not (isEmptyNameSet lhs_names)
  1431. = Just (nameOccName (head (nameSetToList lhs_names)))
  1432. | otherwise
  1433. = Nothing
  1434. --------------------------
  1435. toIfaceLetBndr :: Id -> IfaceLetBndr
  1436. toIfaceLetBndr id = IfLetBndr (occNameFS (getOccName id))
  1437. (toIfaceType (idType id))
  1438. (toIfaceIdInfo (idInfo id))
  1439. -- Put into the interface file any IdInfo that CoreTidy.tidyLetBndr
  1440. -- has left on the Id. See Note [IdInfo on nested let-bindings] in IfaceSyn
  1441. --------------------------
  1442. toIfaceIdDetails :: IdDetails -> IfaceIdDetails
  1443. toIfaceIdDetails VanillaId = IfVanillaId
  1444. toIfaceIdDetails (DFunId ns _) = IfDFunId ns
  1445. toIfaceIdDetails (RecSelId { sel_naughty = n
  1446. , sel_tycon = tc }) = IfRecSelId (toIfaceTyCon tc) n
  1447. toIfaceIdDetails other = pprTrace "toIfaceIdDetails" (ppr other)
  1448. IfVanillaId -- Unexpected
  1449. toIfaceIdInfo :: IdInfo -> IfaceIdInfo
  1450. toIfaceIdInfo id_info
  1451. = case catMaybes [arity_hsinfo, caf_hsinfo, strict_hsinfo,
  1452. inline_hsinfo, unfold_hsinfo] of
  1453. [] -> NoInfo
  1454. infos -> HasInfo infos
  1455. -- NB: strictness must appear in the list before unfolding
  1456. -- See TcIface.tcUnfolding
  1457. where
  1458. ------------ Arity --------------
  1459. arity_info = arityInfo id_info
  1460. arity_hsinfo | arity_info == 0 = Nothing
  1461. | otherwise = Just (HsArity arity_info)
  1462. ------------ Caf Info --------------
  1463. caf_info = cafInfo id_info
  1464. caf_hsinfo = case caf_info of
  1465. NoCafRefs -> Just HsNoCafRefs
  1466. _other -> Nothing
  1467. ------------ Strictness --------------
  1468. -- No point in explicitly exporting TopSig
  1469. strict_hsinfo = case strictnessInfo id_info of
  1470. Just sig | not (isTopSig sig) -> Just (HsStrictness sig)
  1471. _other -> Nothing
  1472. ------------ Unfolding --------------
  1473. unfold_hsinfo = toIfUnfolding loop_breaker (unfoldingInfo id_info)
  1474. loop_breaker = isStrongLoopBreaker (occInfo id_info)
  1475. ------------ Inline prag --------------
  1476. inline_prag = inlinePragInfo id_info
  1477. inline_hsinfo | isDefaultInlinePragma inline_prag = Nothing
  1478. | otherwise = Just (HsInline inline_prag)
  1479. --------------------------
  1480. toIfUnfolding :: Bool -> Unfolding -> Maybe IfaceInfoItem
  1481. toIfUnfolding lb (CoreUnfolding { uf_tmpl = rhs, uf_arity = arity
  1482. , uf_src = src, uf_guidance = guidance })
  1483. = Just $ HsUnfold lb $
  1484. case src of
  1485. InlineStable
  1486. -> case guidance of
  1487. UnfWhen unsat_ok boring_ok -> IfInlineRule arity unsat_ok boring_ok if_rhs
  1488. _other -> IfCoreUnfold True if_rhs
  1489. InlineWrapper w | isExternalName n -> IfExtWrapper arity n
  1490. | otherwise -> IfLclWrapper arity (getFS n)
  1491. where
  1492. n = idName w
  1493. InlineCompulsory -> IfCompulsory if_rhs
  1494. InlineRhs -> IfCoreUnfold False if_rhs
  1495. -- Yes, even if guidance is UnfNever, expose the unfolding
  1496. -- If we didn't want to expose the unfolding, TidyPgm would
  1497. -- have stuck in NoUnfolding. For supercompilation we want
  1498. -- to see that unfolding!
  1499. where
  1500. if_rhs = toIfaceExpr rhs
  1501. toIfUnfolding lb (DFunUnfolding _ar _con ops)
  1502. = Just (HsUnfold lb (IfDFunUnfold (map (fmap toIfaceExpr) ops)))
  1503. -- No need to serialise the data constructor;
  1504. -- we can recover it from the type of the dfun
  1505. toIfUnfolding _ _
  1506. = Nothing
  1507. --------------------------
  1508. coreRuleToIfaceRule :: Module -> CoreRule -> IfaceRule
  1509. coreRuleToIfaceRule _ (BuiltinRule { ru_fn = fn})
  1510. = pprTrace "toHsRule: builtin" (ppr fn) $
  1511. bogusIfaceRule fn
  1512. coreRuleToIfaceRule mod rule@(Rule { ru_name = name, ru_fn = fn,
  1513. ru_act = act, ru_bndrs = bndrs,
  1514. ru_args = args, ru_rhs = rhs,
  1515. ru_auto = auto })
  1516. = IfaceRule { ifRuleName = name, ifActivation = act,
  1517. ifRuleBndrs = map toIfaceBndr bndrs,
  1518. ifRuleHead = fn,
  1519. ifRuleArgs = map do_arg args,
  1520. ifRuleRhs = toIfaceExpr rhs,
  1521. ifRuleAuto = auto,
  1522. ifRuleOrph = orph }
  1523. where
  1524. -- For type args we must remove synonyms from the outermost
  1525. -- level. Reason: so that when we read it back in we'll
  1526. -- construct the same ru_rough field as we have right now;
  1527. -- see tcIfaceRule
  1528. do_arg (Type ty) = IfaceType (toIfaceType (deNoteType ty))
  1529. do_arg (Coercion co) = IfaceCo (coToIfaceType co)
  1530. do_arg arg = toIfaceExpr arg
  1531. -- Compute orphanhood. See Note [Orphans] in IfaceSyn
  1532. -- A rule is an orphan only if none of the variables
  1533. -- mentioned on its left-hand side are locally defined
  1534. lhs_names = nameSetToList (ruleLhsOrphNames rule)
  1535. orph = case filter (nameIsLocalOrFrom mod) lhs_names of
  1536. (n : _) -> Just (nameOccName n)
  1537. [] -> Nothing
  1538. bogusIfaceRule :: Name -> IfaceRule
  1539. bogusIfaceRule id_name
  1540. = IfaceRule { ifRuleName = fsLit "bogus", ifActivation = NeverActive,
  1541. ifRuleBndrs = [], ifRuleHead = id_name, ifRuleArgs = [],
  1542. ifRuleRhs = IfaceExt id_name, ifRuleOrph = Nothing, ifRuleAuto = True }
  1543. ---------------------
  1544. toIfaceExpr :: CoreExpr -> IfaceExpr
  1545. toIfaceExpr (Var v) = toIfaceVar v
  1546. toIfaceExpr (Lit l) = IfaceLit l
  1547. toIfaceExpr (Type ty) = IfaceType (toIfaceType ty)
  1548. toIfaceExpr (Coercion co) = IfaceCo (coToIfaceType co)
  1549. toIfaceExpr (Lam x b) = IfaceLam (toIfaceBndr x) (toIfaceExpr b)
  1550. toIfaceExpr (App f a) = toIfaceApp f [a]
  1551. toIfaceExpr (Case s x ty as)
  1552. | null as = IfaceECase (toIfaceExpr s) (toIfaceType ty)
  1553. | otherwise = IfaceCase (toIfaceExpr s) (getFS x) (map toIfaceAlt as)
  1554. toIfaceExpr (Let b e) = IfaceLet (toIfaceBind b) (toIfaceExpr e)
  1555. toIfaceExpr (Cast e co) = IfaceCast (toIfaceExpr e) (coToIfaceType co)
  1556. toIfaceExpr (Tick t e) = IfaceTick (toIfaceTickish t) (toIfaceExpr e)
  1557. ---------------------
  1558. toIfaceTickish :: Tickish Id -> IfaceTickish
  1559. toIfaceTickish (ProfNote cc tick push) = IfaceSCC cc tick push
  1560. toIfaceTickish (HpcTick modl ix) = IfaceHpcTick modl ix
  1561. toIfaceTickish _ = panic "toIfaceTickish"
  1562. ---------------------
  1563. toIfaceBind :: Bind Id -> IfaceBinding
  1564. toIfaceBind (NonRec b r) = IfaceNonRec (toIfaceLetBndr b) (toIfaceExpr r)
  1565. toIfaceBind (Rec prs) = IfaceRec [(toIfaceLetBndr b, toIfaceExpr r) | (b,r) <- prs]
  1566. ---------------------
  1567. toIfaceAlt :: (AltCon, [Var], CoreExpr)
  1568. -> (IfaceConAlt, [FastString], IfaceExpr)
  1569. toIfaceAlt (c,bs,r) = (toIfaceCon c, map getFS bs, toIfaceExpr r)
  1570. ---------------------
  1571. toIfaceCon :: AltCon -> IfaceConAlt
  1572. toIfaceCon (DataAlt dc) = IfaceDataAlt (getName dc)
  1573. toIfaceCon (LitAlt l) = IfaceLitAlt l
  1574. toIfaceCon DEFAULT = IfaceDefault
  1575. ---------------------
  1576. toIfaceApp :: Expr CoreBndr -> [Arg CoreBndr] -> IfaceExpr
  1577. toIfaceApp (App f a) as = toIfaceApp f (a:as)
  1578. toIfaceApp (Var v) as
  1579. = case isDataConWorkId_maybe v of
  1580. -- We convert the *worker* for tuples into IfaceTuples
  1581. Just dc | isTupleTyCon tc && saturated
  1582. -> IfaceTuple (tupleTyConSort tc) tup_args
  1583. where
  1584. val_args = dropWhile isTypeArg as
  1585. saturated = val_args `lengthIs` idArity v
  1586. tup_args = map toIfaceExpr val_args
  1587. tc = dataConTyCon dc
  1588. _ -> mkIfaceApps (toIfaceVar v) as
  1589. toIfaceApp e as = mkIfaceApps (toIfaceExpr e) as
  1590. mkIfaceApps :: IfaceExpr -> [CoreExpr] -> IfaceExpr
  1591. mkIfaceApps f as = foldl (\f a -> IfaceApp f (toIfaceExpr a)) f as
  1592. ---------------------
  1593. toIfaceVar :: Id -> IfaceExpr
  1594. toIfaceVar v
  1595. | Just fcall <- isFCallId_maybe v = IfaceFCall fcall (toIfaceType (idType v))
  1596. -- Foreign calls have special syntax
  1597. | isExternalName name = IfaceExt name
  1598. | otherwise = IfaceLcl (getFS name)
  1599. where name = idName v
  1600. \end{code}