PageRenderTime 144ms CodeModel.GetById 25ms RepoModel.GetById 3ms app.codeStats 1ms

/compiler/main/GhcMake.hs

https://bitbucket.org/carter/ghc
Haskell | 1484 lines | 853 code | 203 blank | 428 comment | 61 complexity | a491f7261d78293d0eaedade82871b2b MD5 | raw file
  1. {-# LANGUAGE ScopedTypeVariables #-}
  2. -- -----------------------------------------------------------------------------
  3. --
  4. -- (c) The University of Glasgow, 2011
  5. --
  6. -- This module implements multi-module compilation, and is used
  7. -- by --make and GHCi.
  8. --
  9. -- -----------------------------------------------------------------------------
  10. module GhcMake(
  11. depanal,
  12. load, LoadHowMuch(..),
  13. topSortModuleGraph,
  14. noModError, cyclicModuleErr
  15. ) where
  16. #include "HsVersions.h"
  17. #ifdef GHCI
  18. import qualified Linker ( unload )
  19. #endif
  20. import DriverPhases
  21. import DriverPipeline
  22. import DynFlags
  23. import ErrUtils
  24. import Finder
  25. import GhcMonad
  26. import HeaderInfo
  27. import HsSyn
  28. import HscTypes
  29. import Module
  30. import RdrName ( RdrName )
  31. import TcIface ( typecheckIface )
  32. import TcRnMonad ( initIfaceCheck )
  33. import Bag ( listToBag )
  34. import BasicTypes
  35. import Digraph
  36. import Exception ( evaluate, tryIO )
  37. import FastString
  38. import Maybes ( expectJust, mapCatMaybes )
  39. import Outputable
  40. import Panic
  41. import SrcLoc
  42. import StringBuffer
  43. import SysTools
  44. import UniqFM
  45. import Util
  46. import qualified Data.Map as Map
  47. import qualified FiniteMap as Map ( insertListWith )
  48. import Control.Monad
  49. import Data.List
  50. import qualified Data.List as List
  51. import Data.Maybe
  52. import Data.Time
  53. import System.Directory
  54. import System.FilePath
  55. import System.IO ( fixIO )
  56. import System.IO.Error ( isDoesNotExistError )
  57. -- -----------------------------------------------------------------------------
  58. -- Loading the program
  59. -- | Perform a dependency analysis starting from the current targets
  60. -- and update the session with the new module graph.
  61. --
  62. -- Dependency analysis entails parsing the @import@ directives and may
  63. -- therefore require running certain preprocessors.
  64. --
  65. -- Note that each 'ModSummary' in the module graph caches its 'DynFlags'.
  66. -- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the
  67. -- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want to
  68. -- changes to the 'DynFlags' to take effect you need to call this function
  69. -- again.
  70. --
  71. depanal :: GhcMonad m =>
  72. [ModuleName] -- ^ excluded modules
  73. -> Bool -- ^ allow duplicate roots
  74. -> m ModuleGraph
  75. depanal excluded_mods allow_dup_roots = do
  76. hsc_env <- getSession
  77. let
  78. dflags = hsc_dflags hsc_env
  79. targets = hsc_targets hsc_env
  80. old_graph = hsc_mod_graph hsc_env
  81. liftIO $ showPass dflags "Chasing dependencies"
  82. liftIO $ debugTraceMsg dflags 2 (hcat [
  83. text "Chasing modules from: ",
  84. hcat (punctuate comma (map pprTarget targets))])
  85. mod_graph <- liftIO $ downsweep hsc_env old_graph excluded_mods allow_dup_roots
  86. modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
  87. return mod_graph
  88. -- | Describes which modules of the module graph need to be loaded.
  89. data LoadHowMuch
  90. = LoadAllTargets
  91. -- ^ Load all targets and its dependencies.
  92. | LoadUpTo ModuleName
  93. -- ^ Load only the given module and its dependencies.
  94. | LoadDependenciesOf ModuleName
  95. -- ^ Load only the dependencies of the given module, but not the module
  96. -- itself.
  97. -- | Try to load the program. See 'LoadHowMuch' for the different modes.
  98. --
  99. -- This function implements the core of GHC's @--make@ mode. It preprocesses,
  100. -- compiles and loads the specified modules, avoiding re-compilation wherever
  101. -- possible. Depending on the target (see 'DynFlags.hscTarget') compilating
  102. -- and loading may result in files being created on disk.
  103. --
  104. -- Calls the 'reportModuleCompilationResult' callback after each compiling
  105. -- each module, whether successful or not.
  106. --
  107. -- Throw a 'SourceError' if errors are encountered before the actual
  108. -- compilation starts (e.g., during dependency analysis). All other errors
  109. -- are reported using the callback.
  110. --
  111. load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
  112. load how_much = do
  113. mod_graph <- depanal [] False
  114. guessOutputFile
  115. hsc_env <- getSession
  116. let hpt1 = hsc_HPT hsc_env
  117. let dflags = hsc_dflags hsc_env
  118. -- The "bad" boot modules are the ones for which we have
  119. -- B.hs-boot in the module graph, but no B.hs
  120. -- The downsweep should have ensured this does not happen
  121. -- (see msDeps)
  122. let all_home_mods = [ms_mod_name s
  123. | s <- mod_graph, not (isBootSummary s)]
  124. bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
  125. not (ms_mod_name s `elem` all_home_mods)]
  126. ASSERT( null bad_boot_mods ) return ()
  127. -- check that the module given in HowMuch actually exists, otherwise
  128. -- topSortModuleGraph will bomb later.
  129. let checkHowMuch (LoadUpTo m) = checkMod m
  130. checkHowMuch (LoadDependenciesOf m) = checkMod m
  131. checkHowMuch _ = id
  132. checkMod m and_then
  133. | m `elem` all_home_mods = and_then
  134. | otherwise = do
  135. liftIO $ errorMsg dflags (text "no such module:" <+>
  136. quotes (ppr m))
  137. return Failed
  138. checkHowMuch how_much $ do
  139. -- mg2_with_srcimps drops the hi-boot nodes, returning a
  140. -- graph with cycles. Among other things, it is used for
  141. -- backing out partially complete cycles following a failed
  142. -- upsweep, and for removing from hpt all the modules
  143. -- not in strict downwards closure, during calls to compile.
  144. let mg2_with_srcimps :: [SCC ModSummary]
  145. mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
  146. -- If we can determine that any of the {-# SOURCE #-} imports
  147. -- are definitely unnecessary, then emit a warning.
  148. warnUnnecessarySourceImports mg2_with_srcimps
  149. let
  150. -- check the stability property for each module.
  151. stable_mods@(stable_obj,stable_bco)
  152. = checkStability hpt1 mg2_with_srcimps all_home_mods
  153. -- prune bits of the HPT which are definitely redundant now,
  154. -- to save space.
  155. pruned_hpt = pruneHomePackageTable hpt1
  156. (flattenSCCs mg2_with_srcimps)
  157. stable_mods
  158. _ <- liftIO $ evaluate pruned_hpt
  159. -- before we unload anything, make sure we don't leave an old
  160. -- interactive context around pointing to dead bindings. Also,
  161. -- write the pruned HPT to allow the old HPT to be GC'd.
  162. modifySession $ \_ -> discardIC $ hsc_env { hsc_HPT = pruned_hpt }
  163. liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
  164. text "Stable BCO:" <+> ppr stable_bco)
  165. -- Unload any modules which are going to be re-linked this time around.
  166. let stable_linkables = [ linkable
  167. | m <- stable_obj++stable_bco,
  168. Just hmi <- [lookupUFM pruned_hpt m],
  169. Just linkable <- [hm_linkable hmi] ]
  170. liftIO $ unload hsc_env stable_linkables
  171. -- We could at this point detect cycles which aren't broken by
  172. -- a source-import, and complain immediately, but it seems better
  173. -- to let upsweep_mods do this, so at least some useful work gets
  174. -- done before the upsweep is abandoned.
  175. --hPutStrLn stderr "after tsort:\n"
  176. --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
  177. -- Now do the upsweep, calling compile for each module in
  178. -- turn. Final result is version 3 of everything.
  179. -- Topologically sort the module graph, this time including hi-boot
  180. -- nodes, and possibly just including the portion of the graph
  181. -- reachable from the module specified in the 2nd argument to load.
  182. -- This graph should be cycle-free.
  183. -- If we're restricting the upsweep to a portion of the graph, we
  184. -- also want to retain everything that is still stable.
  185. let full_mg :: [SCC ModSummary]
  186. full_mg = topSortModuleGraph False mod_graph Nothing
  187. maybe_top_mod = case how_much of
  188. LoadUpTo m -> Just m
  189. LoadDependenciesOf m -> Just m
  190. _ -> Nothing
  191. partial_mg0 :: [SCC ModSummary]
  192. partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
  193. -- LoadDependenciesOf m: we want the upsweep to stop just
  194. -- short of the specified module (unless the specified module
  195. -- is stable).
  196. partial_mg
  197. | LoadDependenciesOf _mod <- how_much
  198. = ASSERT( case last partial_mg0 of
  199. AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
  200. List.init partial_mg0
  201. | otherwise
  202. = partial_mg0
  203. stable_mg =
  204. [ AcyclicSCC ms
  205. | AcyclicSCC ms <- full_mg,
  206. ms_mod_name ms `elem` stable_obj++stable_bco,
  207. ms_mod_name ms `notElem` [ ms_mod_name ms' |
  208. AcyclicSCC ms' <- partial_mg ] ]
  209. mg = stable_mg ++ partial_mg
  210. -- clean up between compilations
  211. let cleanup hsc_env = intermediateCleanTempFiles dflags
  212. (flattenSCCs mg2_with_srcimps)
  213. hsc_env
  214. liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
  215. 2 (ppr mg))
  216. setSession hsc_env{ hsc_HPT = emptyHomePackageTable }
  217. (upsweep_ok, modsUpswept)
  218. <- upsweep pruned_hpt stable_mods cleanup mg
  219. -- Make modsDone be the summaries for each home module now
  220. -- available; this should equal the domain of hpt3.
  221. -- Get in in a roughly top .. bottom order (hence reverse).
  222. let modsDone = reverse modsUpswept
  223. -- Try and do linking in some form, depending on whether the
  224. -- upsweep was completely or only partially successful.
  225. if succeeded upsweep_ok
  226. then
  227. -- Easy; just relink it all.
  228. do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
  229. -- Clean up after ourselves
  230. hsc_env1 <- getSession
  231. liftIO $ intermediateCleanTempFiles dflags modsDone hsc_env1
  232. -- Issue a warning for the confusing case where the user
  233. -- said '-o foo' but we're not going to do any linking.
  234. -- We attempt linking if either (a) one of the modules is
  235. -- called Main, or (b) the user said -no-hs-main, indicating
  236. -- that main() is going to come from somewhere else.
  237. --
  238. let ofile = outputFile dflags
  239. let no_hs_main = dopt Opt_NoHsMain dflags
  240. let
  241. main_mod = mainModIs dflags
  242. a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
  243. do_linking = a_root_is_Main || no_hs_main || ghcLink dflags == LinkDynLib
  244. when (ghcLink dflags == LinkBinary
  245. && isJust ofile && not do_linking) $
  246. liftIO $ debugTraceMsg dflags 1 $
  247. text ("Warning: output was redirected with -o, " ++
  248. "but no output will be generated\n" ++
  249. "because there is no " ++
  250. moduleNameString (moduleName main_mod) ++ " module.")
  251. -- link everything together
  252. linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
  253. loadFinish Succeeded linkresult
  254. else
  255. -- Tricky. We need to back out the effects of compiling any
  256. -- half-done cycles, both so as to clean up the top level envs
  257. -- and to avoid telling the interactive linker to link them.
  258. do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
  259. let modsDone_names
  260. = map ms_mod modsDone
  261. let mods_to_zap_names
  262. = findPartiallyCompletedCycles modsDone_names
  263. mg2_with_srcimps
  264. let mods_to_keep
  265. = filter ((`notElem` mods_to_zap_names).ms_mod)
  266. modsDone
  267. hsc_env1 <- getSession
  268. let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
  269. (hsc_HPT hsc_env1)
  270. -- Clean up after ourselves
  271. liftIO $ intermediateCleanTempFiles dflags mods_to_keep hsc_env1
  272. -- there should be no Nothings where linkables should be, now
  273. ASSERT(all (isJust.hm_linkable)
  274. (eltsUFM (hsc_HPT hsc_env))) do
  275. -- Link everything together
  276. linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
  277. modifySession $ \hsc_env -> hsc_env{ hsc_HPT = hpt4 }
  278. loadFinish Failed linkresult
  279. -- | Finish up after a load.
  280. loadFinish :: GhcMonad m => SuccessFlag -> SuccessFlag -> m SuccessFlag
  281. -- If the link failed, unload everything and return.
  282. loadFinish _all_ok Failed
  283. = do hsc_env <- getSession
  284. liftIO $ unload hsc_env []
  285. modifySession discardProg
  286. return Failed
  287. -- Empty the interactive context and set the module context to the topmost
  288. -- newly loaded module, or the Prelude if none were loaded.
  289. loadFinish all_ok Succeeded
  290. = do modifySession discardIC
  291. return all_ok
  292. -- | Forget the current program, but retain the persistent info in HscEnv
  293. discardProg :: HscEnv -> HscEnv
  294. discardProg hsc_env
  295. = discardIC $ hsc_env { hsc_mod_graph = emptyMG
  296. , hsc_HPT = emptyHomePackageTable }
  297. -- | Discard the contents of the InteractiveContext, but keep the DynFlags
  298. discardIC :: HscEnv -> HscEnv
  299. discardIC hsc_env
  300. = hsc_env { hsc_IC = emptyInteractiveContext (ic_dflags (hsc_IC hsc_env)) }
  301. intermediateCleanTempFiles :: DynFlags -> [ModSummary] -> HscEnv -> IO ()
  302. intermediateCleanTempFiles dflags summaries hsc_env
  303. = cleanTempFilesExcept dflags except
  304. where
  305. except =
  306. -- Save preprocessed files. The preprocessed file *might* be
  307. -- the same as the source file, but that doesn't do any
  308. -- harm.
  309. map ms_hspp_file summaries ++
  310. -- Save object files for loaded modules. The point of this
  311. -- is that we might have generated and compiled a stub C
  312. -- file, and in the case of GHCi the object file will be a
  313. -- temporary file which we must not remove because we need
  314. -- to load/link it later.
  315. hptObjs (hsc_HPT hsc_env)
  316. -- | If there is no -o option, guess the name of target executable
  317. -- by using top-level source file name as a base.
  318. guessOutputFile :: GhcMonad m => m ()
  319. guessOutputFile = modifySession $ \env ->
  320. let dflags = hsc_dflags env
  321. mod_graph = hsc_mod_graph env
  322. mainModuleSrcPath :: Maybe String
  323. mainModuleSrcPath = do
  324. let isMain = (== mainModIs dflags) . ms_mod
  325. [ms] <- return (filter isMain mod_graph)
  326. ml_hs_file (ms_location ms)
  327. name = fmap dropExtension mainModuleSrcPath
  328. #if defined(mingw32_HOST_OS)
  329. -- we must add the .exe extention unconditionally here, otherwise
  330. -- when name has an extension of its own, the .exe extension will
  331. -- not be added by DriverPipeline.exeFileName. See #2248
  332. name_exe = fmap (<.> "exe") name
  333. #else
  334. name_exe = name
  335. #endif
  336. in
  337. case outputFile dflags of
  338. Just _ -> env
  339. Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
  340. -- -----------------------------------------------------------------------------
  341. --
  342. -- | Prune the HomePackageTable
  343. --
  344. -- Before doing an upsweep, we can throw away:
  345. --
  346. -- - For non-stable modules:
  347. -- - all ModDetails, all linked code
  348. -- - all unlinked code that is out of date with respect to
  349. -- the source file
  350. --
  351. -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
  352. -- space at the end of the upsweep, because the topmost ModDetails of the
  353. -- old HPT holds on to the entire type environment from the previous
  354. -- compilation.
  355. pruneHomePackageTable :: HomePackageTable
  356. -> [ModSummary]
  357. -> ([ModuleName],[ModuleName])
  358. -> HomePackageTable
  359. pruneHomePackageTable hpt summ (stable_obj, stable_bco)
  360. = mapUFM prune hpt
  361. where prune hmi
  362. | is_stable modl = hmi'
  363. | otherwise = hmi'{ hm_details = emptyModDetails }
  364. where
  365. modl = moduleName (mi_module (hm_iface hmi))
  366. hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
  367. = hmi{ hm_linkable = Nothing }
  368. | otherwise
  369. = hmi
  370. where ms = expectJust "prune" (lookupUFM ms_map modl)
  371. ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
  372. is_stable m = m `elem` stable_obj || m `elem` stable_bco
  373. -- -----------------------------------------------------------------------------
  374. --
  375. -- | Return (names of) all those in modsDone who are part of a cycle as defined
  376. -- by theGraph.
  377. findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
  378. findPartiallyCompletedCycles modsDone theGraph
  379. = chew theGraph
  380. where
  381. chew [] = []
  382. chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
  383. chew ((CyclicSCC vs):rest)
  384. = let names_in_this_cycle = nub (map ms_mod vs)
  385. mods_in_this_cycle
  386. = nub ([done | done <- modsDone,
  387. done `elem` names_in_this_cycle])
  388. chewed_rest = chew rest
  389. in
  390. if notNull mods_in_this_cycle
  391. && length mods_in_this_cycle < length names_in_this_cycle
  392. then mods_in_this_cycle ++ chewed_rest
  393. else chewed_rest
  394. -- ---------------------------------------------------------------------------
  395. --
  396. -- | Unloading
  397. unload :: HscEnv -> [Linkable] -> IO ()
  398. unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
  399. = case ghcLink (hsc_dflags hsc_env) of
  400. #ifdef GHCI
  401. LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
  402. #else
  403. LinkInMemory -> panic "unload: no interpreter"
  404. -- urgh. avoid warnings:
  405. hsc_env stable_linkables
  406. #endif
  407. _other -> return ()
  408. -- -----------------------------------------------------------------------------
  409. {- |
  410. Stability tells us which modules definitely do not need to be recompiled.
  411. There are two main reasons for having stability:
  412. - avoid doing a complete upsweep of the module graph in GHCi when
  413. modules near the bottom of the tree have not changed.
  414. - to tell GHCi when it can load object code: we can only load object code
  415. for a module when we also load object code fo all of the imports of the
  416. module. So we need to know that we will definitely not be recompiling
  417. any of these modules, and we can use the object code.
  418. The stability check is as follows. Both stableObject and
  419. stableBCO are used during the upsweep phase later.
  420. @
  421. stable m = stableObject m || stableBCO m
  422. stableObject m =
  423. all stableObject (imports m)
  424. && old linkable does not exist, or is == on-disk .o
  425. && date(on-disk .o) > date(.hs)
  426. stableBCO m =
  427. all stable (imports m)
  428. && date(BCO) > date(.hs)
  429. @
  430. These properties embody the following ideas:
  431. - if a module is stable, then:
  432. - if it has been compiled in a previous pass (present in HPT)
  433. then it does not need to be compiled or re-linked.
  434. - if it has not been compiled in a previous pass,
  435. then we only need to read its .hi file from disk and
  436. link it to produce a 'ModDetails'.
  437. - if a modules is not stable, we will definitely be at least
  438. re-linking, and possibly re-compiling it during the 'upsweep'.
  439. All non-stable modules can (and should) therefore be unlinked
  440. before the 'upsweep'.
  441. - Note that objects are only considered stable if they only depend
  442. on other objects. We can't link object code against byte code.
  443. -}
  444. checkStability
  445. :: HomePackageTable -- HPT from last compilation
  446. -> [SCC ModSummary] -- current module graph (cyclic)
  447. -> [ModuleName] -- all home modules
  448. -> ([ModuleName], -- stableObject
  449. [ModuleName]) -- stableBCO
  450. checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
  451. where
  452. checkSCC (stable_obj, stable_bco) scc0
  453. | stableObjects = (scc_mods ++ stable_obj, stable_bco)
  454. | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
  455. | otherwise = (stable_obj, stable_bco)
  456. where
  457. scc = flattenSCC scc0
  458. scc_mods = map ms_mod_name scc
  459. home_module m = m `elem` all_home_mods && m `notElem` scc_mods
  460. scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc))
  461. -- all imports outside the current SCC, but in the home pkg
  462. stable_obj_imps = map (`elem` stable_obj) scc_allimps
  463. stable_bco_imps = map (`elem` stable_bco) scc_allimps
  464. stableObjects =
  465. and stable_obj_imps
  466. && all object_ok scc
  467. stableBCOs =
  468. and (zipWith (||) stable_obj_imps stable_bco_imps)
  469. && all bco_ok scc
  470. object_ok ms
  471. | dopt Opt_ForceRecomp (ms_hspp_opts ms) = False
  472. | Just t <- ms_obj_date ms = t >= ms_hs_date ms
  473. && same_as_prev t
  474. | otherwise = False
  475. where
  476. same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
  477. Just hmi | Just l <- hm_linkable hmi
  478. -> isObjectLinkable l && t == linkableTime l
  479. _other -> True
  480. -- why '>=' rather than '>' above? If the filesystem stores
  481. -- times to the nearset second, we may occasionally find that
  482. -- the object & source have the same modification time,
  483. -- especially if the source was automatically generated
  484. -- and compiled. Using >= is slightly unsafe, but it matches
  485. -- make's behaviour.
  486. --
  487. -- But see #5527, where someone ran into this and it caused
  488. -- a problem.
  489. bco_ok ms
  490. | dopt Opt_ForceRecomp (ms_hspp_opts ms) = False
  491. | otherwise = case lookupUFM hpt (ms_mod_name ms) of
  492. Just hmi | Just l <- hm_linkable hmi ->
  493. not (isObjectLinkable l) &&
  494. linkableTime l >= ms_hs_date ms
  495. _other -> False
  496. -- -----------------------------------------------------------------------------
  497. --
  498. -- | The upsweep
  499. --
  500. -- This is where we compile each module in the module graph, in a pass
  501. -- from the bottom to the top of the graph.
  502. --
  503. -- There better had not be any cyclic groups here -- we check for them.
  504. upsweep
  505. :: GhcMonad m
  506. => HomePackageTable -- ^ HPT from last time round (pruned)
  507. -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
  508. -> (HscEnv -> IO ()) -- ^ How to clean up unwanted tmp files
  509. -> [SCC ModSummary] -- ^ Mods to do (the worklist)
  510. -> m (SuccessFlag,
  511. [ModSummary])
  512. -- ^ Returns:
  513. --
  514. -- 1. A flag whether the complete upsweep was successful.
  515. -- 2. The 'HscEnv' in the monad has an updated HPT
  516. -- 3. A list of modules which succeeded loading.
  517. upsweep old_hpt stable_mods cleanup sccs = do
  518. (res, done) <- upsweep' old_hpt [] sccs 1 (length sccs)
  519. return (res, reverse done)
  520. where
  521. upsweep' _old_hpt done
  522. [] _ _
  523. = return (Succeeded, done)
  524. upsweep' _old_hpt done
  525. (CyclicSCC ms:_) _ _
  526. = do dflags <- getSessionDynFlags
  527. liftIO $ fatalErrorMsg dflags (cyclicModuleErr ms)
  528. return (Failed, done)
  529. upsweep' old_hpt done
  530. (AcyclicSCC mod:mods) mod_index nmods
  531. = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
  532. -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
  533. -- (moduleEnvElts (hsc_HPT hsc_env)))
  534. let logger _mod = defaultWarnErrLogger
  535. hsc_env <- getSession
  536. -- Remove unwanted tmp files between compilations
  537. liftIO (cleanup hsc_env)
  538. mb_mod_info
  539. <- handleSourceError
  540. (\err -> do logger mod (Just err); return Nothing) $ do
  541. mod_info <- liftIO $ upsweep_mod hsc_env old_hpt stable_mods
  542. mod mod_index nmods
  543. logger mod Nothing -- log warnings
  544. return (Just mod_info)
  545. case mb_mod_info of
  546. Nothing -> return (Failed, done)
  547. Just mod_info -> do
  548. let this_mod = ms_mod_name mod
  549. -- Add new info to hsc_env
  550. hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
  551. hsc_env1 = hsc_env { hsc_HPT = hpt1 }
  552. -- Space-saving: delete the old HPT entry
  553. -- for mod BUT if mod is a hs-boot
  554. -- node, don't delete it. For the
  555. -- interface, the HPT entry is probaby for the
  556. -- main Haskell source file. Deleting it
  557. -- would force the real module to be recompiled
  558. -- every time.
  559. old_hpt1 | isBootSummary mod = old_hpt
  560. | otherwise = delFromUFM old_hpt this_mod
  561. done' = mod:done
  562. -- fixup our HomePackageTable after we've finished compiling
  563. -- a mutually-recursive loop. See reTypecheckLoop, below.
  564. hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
  565. setSession hsc_env2
  566. upsweep' old_hpt1 done' mods (mod_index+1) nmods
  567. -- | Compile a single module. Always produce a Linkable for it if
  568. -- successful. If no compilation happened, return the old Linkable.
  569. upsweep_mod :: HscEnv
  570. -> HomePackageTable
  571. -> ([ModuleName],[ModuleName])
  572. -> ModSummary
  573. -> Int -- index of module
  574. -> Int -- total number of modules
  575. -> IO HomeModInfo
  576. upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
  577. = let
  578. this_mod_name = ms_mod_name summary
  579. this_mod = ms_mod summary
  580. mb_obj_date = ms_obj_date summary
  581. obj_fn = ml_obj_file (ms_location summary)
  582. hs_date = ms_hs_date summary
  583. is_stable_obj = this_mod_name `elem` stable_obj
  584. is_stable_bco = this_mod_name `elem` stable_bco
  585. old_hmi = lookupUFM old_hpt this_mod_name
  586. -- We're using the dflags for this module now, obtained by
  587. -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
  588. dflags = ms_hspp_opts summary
  589. prevailing_target = hscTarget (hsc_dflags hsc_env)
  590. local_target = hscTarget dflags
  591. -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
  592. -- we don't do anything dodgy: these should only work to change
  593. -- from -fvia-C to -fasm and vice-versa, otherwise we could
  594. -- end up trying to link object code to byte code.
  595. target = if prevailing_target /= local_target
  596. && (not (isObjectTarget prevailing_target)
  597. || not (isObjectTarget local_target))
  598. then prevailing_target
  599. else local_target
  600. -- store the corrected hscTarget into the summary
  601. summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
  602. -- The old interface is ok if
  603. -- a) we're compiling a source file, and the old HPT
  604. -- entry is for a source file
  605. -- b) we're compiling a hs-boot file
  606. -- Case (b) allows an hs-boot file to get the interface of its
  607. -- real source file on the second iteration of the compilation
  608. -- manager, but that does no harm. Otherwise the hs-boot file
  609. -- will always be recompiled
  610. mb_old_iface
  611. = case old_hmi of
  612. Nothing -> Nothing
  613. Just hm_info | isBootSummary summary -> Just iface
  614. | not (mi_boot iface) -> Just iface
  615. | otherwise -> Nothing
  616. where
  617. iface = hm_iface hm_info
  618. compile_it :: Maybe Linkable -> SourceModified -> IO HomeModInfo
  619. compile_it mb_linkable src_modified =
  620. compile hsc_env summary' mod_index nmods
  621. mb_old_iface mb_linkable src_modified
  622. compile_it_discard_iface :: Maybe Linkable -> SourceModified
  623. -> IO HomeModInfo
  624. compile_it_discard_iface mb_linkable src_modified =
  625. compile hsc_env summary' mod_index nmods
  626. Nothing mb_linkable src_modified
  627. -- With the HscNothing target we create empty linkables to avoid
  628. -- recompilation. We have to detect these to recompile anyway if
  629. -- the target changed since the last compile.
  630. is_fake_linkable
  631. | Just hmi <- old_hmi, Just l <- hm_linkable hmi =
  632. null (linkableUnlinked l)
  633. | otherwise =
  634. -- we have no linkable, so it cannot be fake
  635. False
  636. implies False _ = True
  637. implies True x = x
  638. in
  639. case () of
  640. _
  641. -- Regardless of whether we're generating object code or
  642. -- byte code, we can always use an existing object file
  643. -- if it is *stable* (see checkStability).
  644. | is_stable_obj, Just hmi <- old_hmi -> do
  645. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  646. (text "skipping stable obj mod:" <+> ppr this_mod_name)
  647. return hmi
  648. -- object is stable, and we have an entry in the
  649. -- old HPT: nothing to do
  650. | is_stable_obj, isNothing old_hmi -> do
  651. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  652. (text "compiling stable on-disk mod:" <+> ppr this_mod_name)
  653. linkable <- liftIO $ findObjectLinkable this_mod obj_fn
  654. (expectJust "upsweep1" mb_obj_date)
  655. compile_it (Just linkable) SourceUnmodifiedAndStable
  656. -- object is stable, but we need to load the interface
  657. -- off disk to make a HMI.
  658. | not (isObjectTarget target), is_stable_bco,
  659. (target /= HscNothing) `implies` not is_fake_linkable ->
  660. ASSERT(isJust old_hmi) -- must be in the old_hpt
  661. let Just hmi = old_hmi in do
  662. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  663. (text "skipping stable BCO mod:" <+> ppr this_mod_name)
  664. return hmi
  665. -- BCO is stable: nothing to do
  666. | not (isObjectTarget target),
  667. Just hmi <- old_hmi,
  668. Just l <- hm_linkable hmi,
  669. not (isObjectLinkable l),
  670. (target /= HscNothing) `implies` not is_fake_linkable,
  671. linkableTime l >= ms_hs_date summary -> do
  672. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  673. (text "compiling non-stable BCO mod:" <+> ppr this_mod_name)
  674. compile_it (Just l) SourceUnmodified
  675. -- we have an old BCO that is up to date with respect
  676. -- to the source: do a recompilation check as normal.
  677. -- When generating object code, if there's an up-to-date
  678. -- object file on the disk, then we can use it.
  679. -- However, if the object file is new (compared to any
  680. -- linkable we had from a previous compilation), then we
  681. -- must discard any in-memory interface, because this
  682. -- means the user has compiled the source file
  683. -- separately and generated a new interface, that we must
  684. -- read from the disk.
  685. --
  686. | isObjectTarget target,
  687. Just obj_date <- mb_obj_date,
  688. obj_date >= hs_date -> do
  689. case old_hmi of
  690. Just hmi
  691. | Just l <- hm_linkable hmi,
  692. isObjectLinkable l && linkableTime l == obj_date -> do
  693. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  694. (text "compiling mod with new on-disk obj:" <+> ppr this_mod_name)
  695. compile_it (Just l) SourceUnmodified
  696. _otherwise -> do
  697. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  698. (text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name)
  699. linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
  700. compile_it_discard_iface (Just linkable) SourceUnmodified
  701. _otherwise -> do
  702. liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
  703. (text "compiling mod:" <+> ppr this_mod_name)
  704. compile_it Nothing SourceModified
  705. -- Filter modules in the HPT
  706. retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
  707. retainInTopLevelEnvs keep_these hpt
  708. = listToUFM [ (mod, expectJust "retain" mb_mod_info)
  709. | mod <- keep_these
  710. , let mb_mod_info = lookupUFM hpt mod
  711. , isJust mb_mod_info ]
  712. -- ---------------------------------------------------------------------------
  713. -- Typecheck module loops
  714. {-
  715. See bug #930. This code fixes a long-standing bug in --make. The
  716. problem is that when compiling the modules *inside* a loop, a data
  717. type that is only defined at the top of the loop looks opaque; but
  718. after the loop is done, the structure of the data type becomes
  719. apparent.
  720. The difficulty is then that two different bits of code have
  721. different notions of what the data type looks like.
  722. The idea is that after we compile a module which also has an .hs-boot
  723. file, we re-generate the ModDetails for each of the modules that
  724. depends on the .hs-boot file, so that everyone points to the proper
  725. TyCons, Ids etc. defined by the real module, not the boot module.
  726. Fortunately re-generating a ModDetails from a ModIface is easy: the
  727. function TcIface.typecheckIface does exactly that.
  728. Picking the modules to re-typecheck is slightly tricky. Starting from
  729. the module graph consisting of the modules that have already been
  730. compiled, we reverse the edges (so they point from the imported module
  731. to the importing module), and depth-first-search from the .hs-boot
  732. node. This gives us all the modules that depend transitively on the
  733. .hs-boot module, and those are exactly the modules that we need to
  734. re-typecheck.
  735. Following this fix, GHC can compile itself with --make -O2.
  736. -}
  737. reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
  738. reTypecheckLoop hsc_env ms graph
  739. | not (isBootSummary ms) &&
  740. any (\m -> ms_mod m == this_mod && isBootSummary m) graph
  741. = do
  742. let mss = reachableBackwards (ms_mod_name ms) graph
  743. non_boot = filter (not.isBootSummary) mss
  744. debugTraceMsg (hsc_dflags hsc_env) 2 $
  745. text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
  746. typecheckLoop hsc_env (map ms_mod_name non_boot)
  747. | otherwise
  748. = return hsc_env
  749. where
  750. this_mod = ms_mod ms
  751. typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
  752. typecheckLoop hsc_env mods = do
  753. new_hpt <-
  754. fixIO $ \new_hpt -> do
  755. let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
  756. mds <- initIfaceCheck new_hsc_env $
  757. mapM (typecheckIface . hm_iface) hmis
  758. let new_hpt = addListToUFM old_hpt
  759. (zip mods [ hmi{ hm_details = details }
  760. | (hmi,details) <- zip hmis mds ])
  761. return new_hpt
  762. return hsc_env{ hsc_HPT = new_hpt }
  763. where
  764. old_hpt = hsc_HPT hsc_env
  765. hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
  766. reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
  767. reachableBackwards mod summaries
  768. = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
  769. where -- the rest just sets up the graph:
  770. (graph, lookup_node) = moduleGraphNodes False summaries
  771. root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
  772. -- ---------------------------------------------------------------------------
  773. --
  774. -- | Topological sort of the module graph
  775. topSortModuleGraph
  776. :: Bool
  777. -- ^ Drop hi-boot nodes? (see below)
  778. -> [ModSummary]
  779. -> Maybe ModuleName
  780. -- ^ Root module name. If @Nothing@, use the full graph.
  781. -> [SCC ModSummary]
  782. -- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
  783. -- The resulting list of strongly-connected-components is in topologically
  784. -- sorted order, starting with the module(s) at the bottom of the
  785. -- dependency graph (ie compile them first) and ending with the ones at
  786. -- the top.
  787. --
  788. -- Drop hi-boot nodes (first boolean arg)?
  789. --
  790. -- - @False@: treat the hi-boot summaries as nodes of the graph,
  791. -- so the graph must be acyclic
  792. --
  793. -- - @True@: eliminate the hi-boot nodes, and instead pretend
  794. -- the a source-import of Foo is an import of Foo
  795. -- The resulting graph has no hi-boot nodes, but can be cyclic
  796. topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
  797. = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
  798. where
  799. (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
  800. initial_graph = case mb_root_mod of
  801. Nothing -> graph
  802. Just root_mod ->
  803. -- restrict the graph to just those modules reachable from
  804. -- the specified module. We do this by building a graph with
  805. -- the full set of nodes, and determining the reachable set from
  806. -- the specified node.
  807. let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
  808. | otherwise = ghcError (ProgramError "module does not exist")
  809. in graphFromEdgedVertices (seq root (reachableG graph root))
  810. type SummaryNode = (ModSummary, Int, [Int])
  811. summaryNodeKey :: SummaryNode -> Int
  812. summaryNodeKey (_, k, _) = k
  813. summaryNodeSummary :: SummaryNode -> ModSummary
  814. summaryNodeSummary (s, _, _) = s
  815. moduleGraphNodes :: Bool -> [ModSummary]
  816. -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
  817. moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
  818. where
  819. numbered_summaries = zip summaries [1..]
  820. lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
  821. lookup_node hs_src mod = Map.lookup (mod, hs_src) node_map
  822. lookup_key :: HscSource -> ModuleName -> Maybe Int
  823. lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
  824. node_map :: NodeMap SummaryNode
  825. node_map = Map.fromList [ ((moduleName (ms_mod s), ms_hsc_src s), node)
  826. | node@(s, _, _) <- nodes ]
  827. -- We use integers as the keys for the SCC algorithm
  828. nodes :: [SummaryNode]
  829. nodes = [ (s, key, out_keys)
  830. | (s, key) <- numbered_summaries
  831. -- Drop the hi-boot ones if told to do so
  832. , not (isBootSummary s && drop_hs_boot_nodes)
  833. , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++
  834. out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++
  835. (-- see [boot-edges] below
  836. if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
  837. then []
  838. else case lookup_key HsBootFile (ms_mod_name s) of
  839. Nothing -> []
  840. Just k -> [k]) ]
  841. -- [boot-edges] if this is a .hs and there is an equivalent
  842. -- .hs-boot, add a link from the former to the latter. This
  843. -- has the effect of detecting bogus cases where the .hs-boot
  844. -- depends on the .hs, by introducing a cycle. Additionally,
  845. -- it ensures that we will always process the .hs-boot before
  846. -- the .hs, and so the HomePackageTable will always have the
  847. -- most up to date information.
  848. -- Drop hs-boot nodes by using HsSrcFile as the key
  849. hs_boot_key | drop_hs_boot_nodes = HsSrcFile
  850. | otherwise = HsBootFile
  851. out_edge_keys :: HscSource -> [ModuleName] -> [Int]
  852. out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
  853. -- If we want keep_hi_boot_nodes, then we do lookup_key with
  854. -- the IsBootInterface parameter True; else False
  855. type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
  856. type NodeMap a = Map.Map NodeKey a -- keyed by (mod, src_file_type) pairs
  857. msKey :: ModSummary -> NodeKey
  858. msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
  859. mkNodeMap :: [ModSummary] -> NodeMap ModSummary
  860. mkNodeMap summaries = Map.fromList [ (msKey s, s) | s <- summaries]
  861. nodeMapElts :: NodeMap a -> [a]
  862. nodeMapElts = Map.elems
  863. -- | If there are {-# SOURCE #-} imports between strongly connected
  864. -- components in the topological sort, then those imports can
  865. -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
  866. -- were necessary, then the edge would be part of a cycle.
  867. warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m ()
  868. warnUnnecessarySourceImports sccs = do
  869. dflags <- getDynFlags
  870. logWarnings (listToBag (concatMap (check dflags . flattenSCC) sccs))
  871. where check dflags ms =
  872. let mods_in_this_cycle = map ms_mod_name ms in
  873. [ warn dflags i | m <- ms, i <- ms_home_srcimps m,
  874. unLoc i `notElem` mods_in_this_cycle ]
  875. warn :: DynFlags -> Located ModuleName -> WarnMsg
  876. warn dflags (L loc mod) =
  877. mkPlainErrMsg dflags loc
  878. (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
  879. <+> quotes (ppr mod))
  880. -----------------------------------------------------------------------------
  881. --
  882. -- | Downsweep (dependency analysis)
  883. --
  884. -- Chase downwards from the specified root set, returning summaries
  885. -- for all home modules encountered. Only follow source-import
  886. -- links.
  887. --
  888. -- We pass in the previous collection of summaries, which is used as a
  889. -- cache to avoid recalculating a module summary if the source is
  890. -- unchanged.
  891. --
  892. -- The returned list of [ModSummary] nodes has one node for each home-package
  893. -- module, plus one for any hs-boot files. The imports of these nodes
  894. -- are all there, including the imports of non-home-package modules.
  895. downsweep :: HscEnv
  896. -> [ModSummary] -- Old summaries
  897. -> [ModuleName] -- Ignore dependencies on these; treat
  898. -- them as if they were package modules
  899. -> Bool -- True <=> allow multiple targets to have
  900. -- the same module name; this is
  901. -- very useful for ghc -M
  902. -> IO [ModSummary]
  903. -- The elts of [ModSummary] all have distinct
  904. -- (Modules, IsBoot) identifiers, unless the Bool is true
  905. -- in which case there can be repeats
  906. downsweep hsc_env old_summaries excl_mods allow_dup_roots
  907. = do
  908. rootSummaries <- mapM getRootSummary roots
  909. let root_map = mkRootMap rootSummaries
  910. checkDuplicates root_map
  911. summs <- loop (concatMap msDeps rootSummaries) root_map
  912. return summs
  913. where
  914. dflags = hsc_dflags hsc_env
  915. roots = hsc_targets hsc_env
  916. old_summary_map :: NodeMap ModSummary
  917. old_summary_map = mkNodeMap old_summaries
  918. getRootSummary :: Target -> IO ModSummary
  919. getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
  920. = do exists <- liftIO $ doesFileExist file
  921. if exists
  922. then summariseFile hsc_env old_summaries file mb_phase
  923. obj_allowed maybe_buf
  924. else throwOneError $ mkPlainErrMsg dflags noSrcSpan $
  925. text "can't find file:" <+> text file
  926. getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
  927. = do maybe_summary <- summariseModule hsc_env old_summary_map False
  928. (L rootLoc modl) obj_allowed
  929. maybe_buf excl_mods
  930. case maybe_summary of
  931. Nothing -> packageModErr dflags modl
  932. Just s -> return s
  933. rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
  934. -- In a root module, the filename is allowed to diverge from the module
  935. -- name, so we have to check that there aren't multiple root files
  936. -- defining the same module (otherwise the duplicates will be silently
  937. -- ignored, leading to confusing behaviour).
  938. checkDuplicates :: NodeMap [ModSummary] -> IO ()
  939. checkDuplicates root_map
  940. | allow_dup_roots = return ()
  941. | null dup_roots = return ()
  942. | otherwise = liftIO $ multiRootsErr dflags (head dup_roots)
  943. where
  944. dup_roots :: [[ModSummary]] -- Each at least of length 2
  945. dup_roots = filterOut isSingleton (nodeMapElts root_map)
  946. loop :: [(Located ModuleName,IsBootInterface)]
  947. -- Work list: process these modules
  948. -> NodeMap [ModSummary]
  949. -- Visited set; the range is a list because
  950. -- the roots can have the same module names
  951. -- if allow_dup_roots is True
  952. -> IO [ModSummary]
  953. -- The result includes the worklist, except
  954. -- for those mentioned in the visited set
  955. loop [] done = return (concat (nodeMapElts done))
  956. loop ((wanted_mod, is_boot) : ss) done
  957. | Just summs <- Map.lookup key done
  958. = if isSingleton summs then
  959. loop ss done
  960. else
  961. do { multiRootsErr dflags summs; return [] }
  962. | otherwise
  963. = do mb_s <- summariseModule hsc_env old_summary_map
  964. is_boot wanted_mod True
  965. Nothing excl_mods
  966. case mb_s of
  967. Nothing -> loop ss done
  968. Just s -> loop (msDeps s ++ ss) (Map.insert key [s] done)
  969. where
  970. key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
  971. mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
  972. mkRootMap summaries = Map.insertListWith (flip (++))
  973. [ (msKey s, [s]) | s <- summaries ]
  974. Map.empty
  975. -- | Returns the dependencies of the ModSummary s.
  976. -- A wrinkle is that for a {-# SOURCE #-} import we return
  977. -- *both* the hs-boot file
  978. -- *and* the source file
  979. -- as "dependencies". That ensures that the list of all relevant
  980. -- modules always contains B.hs if it contains B.hs-boot.
  981. -- Remember, this pass isn't doing the topological sort. It's
  982. -- just gathering the list of all relevant ModSummaries
  983. msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
  984. msDeps s =
  985. concat [ [(m,True), (m,False)] | m <- ms_home_srcimps s ]
  986. ++ [ (m,False) | m <- ms_home_imps s ]
  987. home_imps :: [Located (ImportDecl RdrName)] -> [Located ModuleName]
  988. home_imps imps = [ ideclName i | L _ i <- imps, isLocal (ideclPkgQual i) ]
  989. where isLocal Nothing = True
  990. isLocal (Just pkg) | pkg == fsLit "this" = True -- "this" is special
  991. isLocal _ = False
  992. ms_home_allimps :: ModSummary -> [ModuleName]
  993. ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms)
  994. ms_home_srcimps :: ModSummary -> [Located ModuleName]
  995. ms_home_srcimps = home_imps . ms_srcimps
  996. ms_home_imps :: ModSummary -> [Located ModuleName]
  997. ms_home_imps = home_imps . ms_imps
  998. -----------------------------------------------------------------------------
  999. -- Summarising modules
  1000. -- We have two types of summarisation:
  1001. --
  1002. -- * Summarise a file. This is used for the root module(s) passed to
  1003. -- cmLoadModules. The file is read, and used to determine the root
  1004. -- module name. The module name may differ from the filename.
  1005. --
  1006. -- * Summarise a module. We are given a module name, and must provide
  1007. -- a summary. The finder is used to locate the file in which the module
  1008. -- resides.
  1009. summariseFile
  1010. :: HscEnv
  1011. -> [ModSummary] -- old summaries
  1012. -> FilePath -- source file name
  1013. -> Maybe Phase -- start phase
  1014. -> Bool -- object code allowed?
  1015. -> Maybe (StringBuffer,UTCTime)
  1016. -> IO ModSummary
  1017. summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
  1018. -- we can use a cached summary if one is available and the
  1019. -- source file hasn't changed, But we have to look up the summary
  1020. -- by source file, rather than module name as we do in summarise.
  1021. | Just old_summary <- findSummaryBySourceFile old_summaries file
  1022. = do
  1023. let location = ms_location old_summary
  1024. src_timestamp <- get_src_timestamp
  1025. -- The file exists; we checked in getRootSummary above.
  1026. -- If it gets removed subsequently, then this
  1027. -- getModificationUTCTime may fail, but that's the right
  1028. -- behaviour.
  1029. -- return the cached summary if the source didn't change
  1030. if ms_hs_date old_summary == src_timestamp
  1031. then do -- update the object-file timestamp
  1032. obj_timestamp <-
  1033. if isObjectTarget (hscTarget (hsc_dflags hsc_env))
  1034. || obj_allowed -- bug #1205
  1035. then liftIO $ getObjTimestamp location False
  1036. else return Nothing
  1037. return old_summary{ ms_obj_date = obj_timestamp }
  1038. else
  1039. new_summary src_timestamp
  1040. | otherwise
  1041. = do src_timestamp <- get_src_timestamp
  1042. new_summary src_timestamp
  1043. where
  1044. get_src_timestamp = case maybe_buf of
  1045. Just (_,t) -> return t
  1046. Nothing -> liftIO $ getModificationUTCTime file
  1047. -- getMofificationUTCTime may fail
  1048. new_summary src_timestamp = do
  1049. let dflags = hsc_dflags hsc_env
  1050. (dflags', hspp_fn, buf)
  1051. <- preprocessFile hsc_env file mb_phase maybe_buf
  1052. (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
  1053. -- Make a ModLocation for this file
  1054. location <- liftIO $ mkHomeModLocation dflags mod_name file
  1055. -- Tell the Finder cache where it is, so that subsequent calls
  1056. -- to findModule will find it, even if it's not on any search path
  1057. mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
  1058. -- when the user asks to load a source file by name, we only
  1059. -- use an object file if -fobject-code is on. See #1205.
  1060. obj_timestamp <-
  1061. if isObjectTarget (hscTarget (hsc_dflags hsc_env))
  1062. || obj_allowed -- bug #1205
  1063. then liftIO $ modificationTimeIfExists (ml_obj_file location)
  1064. else return Nothing
  1065. return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
  1066. ms_location = location,
  1067. ms_hspp_file = hspp_fn,
  1068. ms_hspp_opts = dflags',
  1069. ms_hspp_buf = Just buf,
  1070. ms_srcimps = srcimps, ms_textual_imps = the_imps,
  1071. ms_hs_date = src_timestamp,
  1072. ms_obj_date = obj_timestamp })
  1073. findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
  1074. findSummaryBySourceFile summaries file
  1075. = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
  1076. expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
  1077. [] -> Nothing
  1078. (x:_) -> Just x
  1079. -- Summarise a module, and pick up source and timestamp.
  1080. summariseModule
  1081. :: HscEnv
  1082. -> NodeMap ModSummary -- Map of old summaries
  1083. -> IsBootInterface -- True <=> a {-# SOURCE #-} import
  1084. -> Located ModuleName -- Imported module to be summarised
  1085. -> Bool -- object code allowed?
  1086. -> Maybe (StringBuffer, UTCTime)
  1087. -> [ModuleName] -- Modules to exclude
  1088. -> IO (Maybe ModSummary) -- Its new summary
  1089. summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
  1090. obj_allowed maybe_buf excl_mods
  1091. | wanted_mod `elem` excl_mods
  1092. = return Nothing
  1093. | Just old_summary <- Map.lookup (wanted_mod, hsc_src) old_summary_map
  1094. = do -- Find its new timestamp; all the
  1095. -- ModSummaries in the old map have valid ml_hs_files
  1096. let location = ms_location old_summary
  1097. src_fn = expectJust "summariseModule" (ml_hs_file location)
  1098. -- check the modification time on the source file, and
  1099. -- return the cached summary if it hasn't changed. If the
  1100. -- file has disappeared, we need to call the Finder again.
  1101. case maybe_buf of
  1102. Just (_,t) -> check_timestamp old_summary location src_fn t
  1103. Nothing -> do
  1104. m <- tryIO (getModificationUTCTime src_fn)
  1105. case m of
  1106. Right t -> check_timestamp old_summary location src_fn t
  1107. Left e | isDoesNotExistError e -> find_it
  1108. | otherwise -> ioError e
  1109. | otherwise = find_it
  1110. where
  1111. dflags = hsc_dflags hsc_env
  1112. hsc_src = if is_boot then HsBootFile else HsSrcFile
  1113. check_timestamp old_summary location src_fn src_timestamp
  1114. | ms_hs_date old_summary == src_timestamp = do
  1115. -- update the object-file timestamp
  1116. obj_timestamp <-
  1117. if isObjectTarget (hscTarget (hsc_dflags hsc_env))
  1118. || obj_allowed -- bug #1205
  1119. then getObjTimestamp location is_boot
  1120. else return Nothing
  1121. return (Just old_summary{ ms_obj_date = obj_timestamp })
  1122. | otherwise =
  1123. -- source changed: re-summarise.
  1124. new_summary location (ms_mod old_summary) src_fn src_timestamp
  1125. find_it = do
  1126. -- Don't use the Finder's cache this time. If the module was
  1127. -- previously a package module, it may have now appeared on the
  1128. -- search path, so we want to consider it to be a home module. If
  1129. -- the module was previously a home module, it may have moved.
  1130. uncacheModule hsc_env wanted_mod
  1131. found <- findImportedModule hsc_env wanted_mod Nothing
  1132. case found of
  1133. Found location mod
  1134. | isJust (ml_hs_file location) ->
  1135. -- Home package
  1136. just_found location mod
  1137. | otherwise ->
  1138. -- Drop external-pkg
  1139. ASSERT(modulePackageId mod /= thisPackage dflags)
  1140. return Nothing
  1141. err -> noModError dflags loc wanted_mod err
  1142. -- Not found
  1143. just_found location mod = do
  1144. -- Adjust location to point to the hs-boot source file,
  1145. -- hi file, object file, when is_boot says so
  1146. let location' | is_boot = addBootSuffixLocn location
  1147. | otherwise = location
  1148. src_fn = expectJust "summarise2" (ml_hs_file location')
  1149. -- Check that it exists
  1150. -- It might have been deleted since the Finder last found it
  1151. maybe_t <- modificationTimeIfExists src_fn
  1152. case maybe_t of
  1153. Nothing -> noHsFileErr dflags loc src_fn
  1154. Just t -> new_summary location' mod src_fn t
  1155. new_summary location mod src_fn src_timestamp
  1156. = do
  1157. -- Preprocess the source file and get its imports
  1158. -- The dflags' contains the OPTIONS pragmas
  1159. (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
  1160. (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
  1161. when (mod_name /= wanted_mod) $
  1162. throwOneError $ mkPlainErrMsg dflags' mod_loc $
  1163. text "File name does not match module name:"
  1164. $$ text "Saw:" <+> quotes (ppr mod_name)
  1165. $$ text "Expected:" <+> quotes (ppr wanted_mod)
  1166. -- Find the object timestamp, and return the summary
  1167. obj_timestamp <-
  1168. if isObjectTarget (hscTarget (hsc_dflags hsc_env))
  1169. || obj_allowed -- bug #1205
  1170. then getObjTimestamp location is_boot
  1171. else return Nothing
  1172. return (Just (ModSummary { ms_mod = mod,
  1173. ms_hsc_src = hsc_src,
  1174. ms_location = location,
  1175. ms_hspp_file = hspp_fn,
  1176. ms_hspp_opts = dflags',
  1177. ms_hspp_buf = Just buf,
  1178. ms_srcimps = srcimps,
  1179. ms_textual_imps = the_imps,
  1180. ms_hs_date = src_timestamp,
  1181. ms_obj_date = obj_timestamp }))
  1182. getObjTimestamp :: ModLocation -> Bool -> IO (Maybe UTCTime)
  1183. getObjTimestamp location is_boot
  1184. = if is_boot then return Nothing
  1185. else modificationTimeIfExists (ml_obj_file location)
  1186. preprocessFile :: HscEnv
  1187. -> FilePath
  1188. -> Maybe Phase -- ^ Starting phase
  1189. -> Maybe (StringBuffer,UTCTime)
  1190. -> IO (DynFlags, FilePath, StringBuffer)
  1191. preprocessFile hsc_env src_fn mb_phase Nothing
  1192. = do
  1193. (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
  1194. buf <- hGetStringBuffer hspp_fn
  1195. return (dflags', hspp_fn, buf)
  1196. preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
  1197. = do
  1198. let dflags = hsc_dflags hsc_env
  1199. let local_opts = getOptions dflags buf src_fn
  1200. (dflags', leftovers, warns)
  1201. <- parseDynamicFilePragma dflags local_opts
  1202. checkProcessArgsResult dflags leftovers
  1203. handleFlagWarnings dflags' warns
  1204. let needs_preprocessing
  1205. | Just (Unlit _) <- mb_phase = True
  1206. | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
  1207. -- note: local_opts is only required if there's no Unlit phase
  1208. | xopt Opt_Cpp dflags' = True
  1209. | dopt Opt_Pp dflags' = True
  1210. | otherwise = False
  1211. when needs_preprocessing $
  1212. ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
  1213. return (dflags', src_fn, buf)
  1214. -----------------------------------------------------------------------------
  1215. -- Error messages
  1216. -----------------------------------------------------------------------------
  1217. noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
  1218. -- ToDo: we don't have a proper line number for this error
  1219. noModError dflags loc wanted_mod err
  1220. = throwOneError $ mkPlainErrMsg dflags loc $ cannotFindModule dflags wanted_mod err
  1221. noHsFileErr :: DynFlags -> SrcSpan -> String -> IO a
  1222. noHsFileErr dflags loc path
  1223. = throwOneError $ mkPlainErrMsg dflags loc $ text "Can't find" <+> text path
  1224. packageModErr :: DynFlags -> ModuleName -> IO a
  1225. packageModErr dflags mod
  1226. = throwOneError $ mkPlainErrMsg dflags noSrcSpan $
  1227. text "module" <+> quotes (ppr mod) <+> text "is a package module"
  1228. multiRootsErr :: DynFlags -> [ModSummary] -> IO ()
  1229. multiRootsErr _ [] = panic "multiRootsErr"
  1230. multiRootsErr dflags summs@(summ1:_)
  1231. = throwOneError $ mkPlainErrMsg dflags noSrcSpan $
  1232. text "module" <+> quotes (ppr mod) <+>
  1233. text "is defined in multiple files:" <+>
  1234. sep (map text files)
  1235. where
  1236. mod = ms_mod summ1
  1237. files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
  1238. cyclicModuleErr :: [ModSummary] -> SDoc
  1239. -- From a strongly connected component we find
  1240. -- a single cycle to report
  1241. cyclicModuleErr mss
  1242. = ASSERT( not (null mss) )
  1243. case findCycle graph of
  1244. Nothing -> ptext (sLit "Unexpected non-cycle") <+> ppr mss
  1245. Just path -> vcat [ ptext (sLit "Module imports form a cycle:")
  1246. , nest 2 (show_path path) ]
  1247. where
  1248. graph :: [Node NodeKey ModSummary]
  1249. graph = [(ms, msKey ms, get_deps ms) | ms <- mss]
  1250. get_deps :: ModSummary -> [NodeKey]
  1251. get_deps ms = ([ (unLoc m, HsBootFile) | m <- ms_home_srcimps ms ] ++
  1252. [ (unLoc m, HsSrcFile) | m <- ms_home_imps ms ])
  1253. show_path [] = panic "show_path"
  1254. show_path [m] = ptext (sLit "module") <+> ppr_ms m
  1255. <+> ptext (sLit "imports itself")
  1256. show_path (m1:m2:ms) = vcat ( nest 7 (ptext (sLit "module") <+> ppr_ms m1)
  1257. : nest 6 (ptext (sLit "imports") <+> ppr_ms m2)
  1258. : go ms )
  1259. where
  1260. go [] = [ptext (sLit "which imports") <+> ppr_ms m1]
  1261. go (m:ms) = (ptext (sLit "which imports") <+> ppr_ms m) : go ms
  1262. ppr_ms :: ModSummary -> SDoc
  1263. ppr_ms ms = quotes (ppr (moduleName (ms_mod ms))) <+>
  1264. (parens (text (msHsFilePath ms)))