ErrUtils: Add timings to compiler phases
[ghc.git] / compiler / main / GhcMake.hs
1 {-# LANGUAGE BangPatterns, CPP, NondecreasingIndentation, ScopedTypeVariables #-}
2 {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
3 -- NB: we specifically ignore deprecations. GHC 7.6 marks the .QSem module as
4 -- deprecated, although it became un-deprecated later. As a result, using 7.6
5 -- as your bootstrap compiler throws annoying warnings.
6
7 -- -----------------------------------------------------------------------------
8 --
9 -- (c) The University of Glasgow, 2011
10 --
11 -- This module implements multi-module compilation, and is used
12 -- by --make and GHCi.
13 --
14 -- -----------------------------------------------------------------------------
15 module GhcMake(
16 depanal,
17 load, LoadHowMuch(..),
18
19 topSortModuleGraph,
20
21 ms_home_srcimps, ms_home_imps,
22
23 noModError, cyclicModuleErr
24 ) where
25
26 #include "HsVersions.h"
27
28 #ifdef GHCI
29 import qualified Linker ( unload )
30 #endif
31
32 import DriverPhases
33 import DriverPipeline
34 import DynFlags
35 import ErrUtils
36 import Finder
37 import GhcMonad
38 import HeaderInfo
39 import HscTypes
40 import Module
41 import TcIface ( typecheckIface )
42 import TcRnMonad ( initIfaceCheck )
43
44 import Bag ( listToBag )
45 import BasicTypes
46 import Digraph
47 import Exception ( tryIO, gbracket, gfinally )
48 import FastString
49 import Maybes ( expectJust )
50 import Name
51 import MonadUtils ( allM, MonadIO )
52 import Outputable
53 import Panic
54 import SrcLoc
55 import StringBuffer
56 import SysTools
57 import UniqFM
58 import Util
59 import qualified GHC.LanguageExtensions as LangExt
60
61 import Data.Either ( rights, partitionEithers )
62 import qualified Data.Map as Map
63 import Data.Map (Map)
64 import qualified Data.Set as Set
65 import qualified FiniteMap as Map ( insertListWith )
66
67 import Control.Concurrent ( forkIOWithUnmask, killThread )
68 import qualified GHC.Conc as CC
69 import Control.Concurrent.MVar
70 import Control.Concurrent.QSem
71 import Control.Exception
72 import Control.Monad
73 import Data.IORef
74 import Data.List
75 import qualified Data.List as List
76 import Data.Maybe
77 import Data.Ord ( comparing )
78 import Data.Time
79 import System.Directory
80 import System.FilePath
81 import System.IO ( fixIO )
82 import System.IO.Error ( isDoesNotExistError )
83
84 import GHC.Conc ( getNumProcessors, getNumCapabilities, setNumCapabilities )
85
86 label_self :: String -> IO ()
87 label_self thread_name = do
88 self_tid <- CC.myThreadId
89 CC.labelThread self_tid thread_name
90
91 -- -----------------------------------------------------------------------------
92 -- Loading the program
93
94 -- | Perform a dependency analysis starting from the current targets
95 -- and update the session with the new module graph.
96 --
97 -- Dependency analysis entails parsing the @import@ directives and may
98 -- therefore require running certain preprocessors.
99 --
100 -- Note that each 'ModSummary' in the module graph caches its 'DynFlags'.
101 -- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the
102 -- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want
103 -- changes to the 'DynFlags' to take effect you need to call this function
104 -- again.
105 --
106 depanal :: GhcMonad m =>
107 [ModuleName] -- ^ excluded modules
108 -> Bool -- ^ allow duplicate roots
109 -> m ModuleGraph
110 depanal excluded_mods allow_dup_roots = do
111 hsc_env <- getSession
112 let
113 dflags = hsc_dflags hsc_env
114 targets = hsc_targets hsc_env
115 old_graph = hsc_mod_graph hsc_env
116
117 withTiming (pure dflags) (text "Chasing dependencies") (const ()) $ do
118 liftIO $ debugTraceMsg dflags 2 (hcat [
119 text "Chasing modules from: ",
120 hcat (punctuate comma (map pprTarget targets))])
121
122 mod_graphE <- liftIO $ downsweep hsc_env old_graph
123 excluded_mods allow_dup_roots
124 mod_graph <- reportImportErrors mod_graphE
125 modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph }
126 return mod_graph
127
128 -- | Describes which modules of the module graph need to be loaded.
129 data LoadHowMuch
130 = LoadAllTargets
131 -- ^ Load all targets and its dependencies.
132 | LoadUpTo ModuleName
133 -- ^ Load only the given module and its dependencies.
134 | LoadDependenciesOf ModuleName
135 -- ^ Load only the dependencies of the given module, but not the module
136 -- itself.
137
138 -- | Try to load the program. See 'LoadHowMuch' for the different modes.
139 --
140 -- This function implements the core of GHC's @--make@ mode. It preprocesses,
141 -- compiles and loads the specified modules, avoiding re-compilation wherever
142 -- possible. Depending on the target (see 'DynFlags.hscTarget') compiling
143 -- and loading may result in files being created on disk.
144 --
145 -- Calls the 'defaultWarnErrLogger' after each compiling each module, whether
146 -- successful or not.
147 --
148 -- Throw a 'SourceError' if errors are encountered before the actual
149 -- compilation starts (e.g., during dependency analysis). All other errors
150 -- are reported using the 'defaultWarnErrLogger'.
151 --
152 load :: GhcMonad m => LoadHowMuch -> m SuccessFlag
153 load how_much = do
154 mod_graph <- depanal [] False
155 guessOutputFile
156 hsc_env <- getSession
157
158 let hpt1 = hsc_HPT hsc_env
159 let dflags = hsc_dflags hsc_env
160
161 -- The "bad" boot modules are the ones for which we have
162 -- B.hs-boot in the module graph, but no B.hs
163 -- The downsweep should have ensured this does not happen
164 -- (see msDeps)
165 let all_home_mods = [ms_mod_name s
166 | s <- mod_graph, not (isBootSummary s)]
167 -- TODO: Figure out what the correct form of this assert is. It's violated
168 -- when you have HsBootMerge nodes in the graph: then you'll have hs-boot
169 -- files without corresponding hs files.
170 -- bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
171 -- not (ms_mod_name s `elem` all_home_mods)]
172 -- ASSERT( null bad_boot_mods ) return ()
173
174 -- check that the module given in HowMuch actually exists, otherwise
175 -- topSortModuleGraph will bomb later.
176 let checkHowMuch (LoadUpTo m) = checkMod m
177 checkHowMuch (LoadDependenciesOf m) = checkMod m
178 checkHowMuch _ = id
179
180 checkMod m and_then
181 | m `elem` all_home_mods = and_then
182 | otherwise = do
183 liftIO $ errorMsg dflags (text "no such module:" <+>
184 quotes (ppr m))
185 return Failed
186
187 checkHowMuch how_much $ do
188
189 -- mg2_with_srcimps drops the hi-boot nodes, returning a
190 -- graph with cycles. Among other things, it is used for
191 -- backing out partially complete cycles following a failed
192 -- upsweep, and for removing from hpt all the modules
193 -- not in strict downwards closure, during calls to compile.
194 let mg2_with_srcimps :: [SCC ModSummary]
195 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
196
197 -- If we can determine that any of the {-# SOURCE #-} imports
198 -- are definitely unnecessary, then emit a warning.
199 warnUnnecessarySourceImports mg2_with_srcimps
200
201 let
202 -- check the stability property for each module.
203 stable_mods@(stable_obj,stable_bco)
204 = checkStability hpt1 mg2_with_srcimps all_home_mods
205
206 -- prune bits of the HPT which are definitely redundant now,
207 -- to save space.
208 pruned_hpt = pruneHomePackageTable hpt1
209 (flattenSCCs mg2_with_srcimps)
210 stable_mods
211
212 _ <- liftIO $ evaluate pruned_hpt
213
214 -- before we unload anything, make sure we don't leave an old
215 -- interactive context around pointing to dead bindings. Also,
216 -- write the pruned HPT to allow the old HPT to be GC'd.
217 setSession $ discardIC $ hsc_env { hsc_HPT = pruned_hpt }
218
219 liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
220 text "Stable BCO:" <+> ppr stable_bco)
221
222 -- Unload any modules which are going to be re-linked this time around.
223 let stable_linkables = [ linkable
224 | m <- stable_obj++stable_bco,
225 Just hmi <- [lookupUFM pruned_hpt m],
226 Just linkable <- [hm_linkable hmi] ]
227 liftIO $ unload hsc_env stable_linkables
228
229 -- We could at this point detect cycles which aren't broken by
230 -- a source-import, and complain immediately, but it seems better
231 -- to let upsweep_mods do this, so at least some useful work gets
232 -- done before the upsweep is abandoned.
233 --hPutStrLn stderr "after tsort:\n"
234 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
235
236 -- Now do the upsweep, calling compile for each module in
237 -- turn. Final result is version 3 of everything.
238
239 -- Topologically sort the module graph, this time including hi-boot
240 -- nodes, and possibly just including the portion of the graph
241 -- reachable from the module specified in the 2nd argument to load.
242 -- This graph should be cycle-free.
243 -- If we're restricting the upsweep to a portion of the graph, we
244 -- also want to retain everything that is still stable.
245 let full_mg :: [SCC ModSummary]
246 full_mg = topSortModuleGraph False mod_graph Nothing
247
248 maybe_top_mod = case how_much of
249 LoadUpTo m -> Just m
250 LoadDependenciesOf m -> Just m
251 _ -> Nothing
252
253 partial_mg0 :: [SCC ModSummary]
254 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
255
256 -- LoadDependenciesOf m: we want the upsweep to stop just
257 -- short of the specified module (unless the specified module
258 -- is stable).
259 partial_mg
260 | LoadDependenciesOf _mod <- how_much
261 = ASSERT( case last partial_mg0 of
262 AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
263 List.init partial_mg0
264 | otherwise
265 = partial_mg0
266
267 stable_mg =
268 [ AcyclicSCC ms
269 | AcyclicSCC ms <- full_mg,
270 ms_mod_name ms `elem` stable_obj++stable_bco ]
271
272 -- the modules from partial_mg that are not also stable
273 -- NB. also keep cycles, we need to emit an error message later
274 unstable_mg = filter not_stable partial_mg
275 where not_stable (CyclicSCC _) = True
276 not_stable (AcyclicSCC ms)
277 = ms_mod_name ms `notElem` stable_obj++stable_bco
278
279 -- Load all the stable modules first, before attempting to load
280 -- an unstable module (#7231).
281 mg = stable_mg ++ unstable_mg
282
283 -- clean up between compilations
284 let cleanup hsc_env = intermediateCleanTempFiles (hsc_dflags hsc_env)
285 (flattenSCCs mg2_with_srcimps)
286 hsc_env
287
288 liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
289 2 (ppr mg))
290
291 n_jobs <- case parMakeCount dflags of
292 Nothing -> liftIO getNumProcessors
293 Just n -> return n
294 let upsweep_fn | n_jobs > 1 = parUpsweep n_jobs
295 | otherwise = upsweep
296
297 setSession hsc_env{ hsc_HPT = emptyHomePackageTable }
298 (upsweep_ok, modsUpswept)
299 <- upsweep_fn pruned_hpt stable_mods cleanup mg
300
301 -- Make modsDone be the summaries for each home module now
302 -- available; this should equal the domain of hpt3.
303 -- Get in in a roughly top .. bottom order (hence reverse).
304
305 let modsDone = reverse modsUpswept
306
307 -- Try and do linking in some form, depending on whether the
308 -- upsweep was completely or only partially successful.
309
310 if succeeded upsweep_ok
311
312 then
313 -- Easy; just relink it all.
314 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.")
315
316 -- Clean up after ourselves
317 hsc_env1 <- getSession
318 liftIO $ intermediateCleanTempFiles dflags modsDone hsc_env1
319
320 -- Issue a warning for the confusing case where the user
321 -- said '-o foo' but we're not going to do any linking.
322 -- We attempt linking if either (a) one of the modules is
323 -- called Main, or (b) the user said -no-hs-main, indicating
324 -- that main() is going to come from somewhere else.
325 --
326 let ofile = outputFile dflags
327 let no_hs_main = gopt Opt_NoHsMain dflags
328 let
329 main_mod = mainModIs dflags
330 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
331 do_linking = a_root_is_Main || no_hs_main || ghcLink dflags == LinkDynLib || ghcLink dflags == LinkStaticLib
332
333 -- link everything together
334 linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
335
336 if ghcLink dflags == LinkBinary && isJust ofile && not do_linking
337 then do
338 liftIO $ errorMsg dflags $ text
339 ("output was redirected with -o, " ++
340 "but no output will be generated\n" ++
341 "because there is no " ++
342 moduleNameString (moduleName main_mod) ++ " module.")
343 -- This should be an error, not a warning (#10895).
344 loadFinish Failed linkresult
345 else
346 loadFinish Succeeded linkresult
347
348 else
349 -- Tricky. We need to back out the effects of compiling any
350 -- half-done cycles, both so as to clean up the top level envs
351 -- and to avoid telling the interactive linker to link them.
352 do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.")
353
354 let modsDone_names
355 = map ms_mod modsDone
356 let mods_to_zap_names
357 = findPartiallyCompletedCycles modsDone_names
358 mg2_with_srcimps
359 let mods_to_keep
360 = filter ((`notElem` mods_to_zap_names).ms_mod)
361 modsDone
362
363 hsc_env1 <- getSession
364 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
365 (hsc_HPT hsc_env1)
366
367 -- Clean up after ourselves
368 liftIO $ intermediateCleanTempFiles dflags mods_to_keep hsc_env1
369
370 -- there should be no Nothings where linkables should be, now
371 let just_linkables =
372 isNoLink (ghcLink dflags)
373 || all (isJust.hm_linkable)
374 (filter ((== HsSrcFile).mi_hsc_src.hm_iface)
375 (eltsUFM hpt4))
376 ASSERT( just_linkables ) do
377
378 -- Link everything together
379 linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4
380
381 modifySession $ \hsc_env -> hsc_env{ hsc_HPT = hpt4 }
382 loadFinish Failed linkresult
383
384
385 -- | Finish up after a load.
386 loadFinish :: GhcMonad m => SuccessFlag -> SuccessFlag -> m SuccessFlag
387
388 -- If the link failed, unload everything and return.
389 loadFinish _all_ok Failed
390 = do hsc_env <- getSession
391 liftIO $ unload hsc_env []
392 modifySession discardProg
393 return Failed
394
395 -- Empty the interactive context and set the module context to the topmost
396 -- newly loaded module, or the Prelude if none were loaded.
397 loadFinish all_ok Succeeded
398 = do modifySession discardIC
399 return all_ok
400
401
402 -- | Forget the current program, but retain the persistent info in HscEnv
403 discardProg :: HscEnv -> HscEnv
404 discardProg hsc_env
405 = discardIC $ hsc_env { hsc_mod_graph = emptyMG
406 , hsc_HPT = emptyHomePackageTable }
407
408 -- | Discard the contents of the InteractiveContext, but keep the DynFlags.
409 -- It will also keep ic_int_print and ic_monad if their names are from
410 -- external packages.
411 discardIC :: HscEnv -> HscEnv
412 discardIC hsc_env
413 = hsc_env { hsc_IC = empty_ic { ic_int_print = new_ic_int_print
414 , ic_monad = new_ic_monad } }
415 where
416 -- Force the new values for ic_int_print and ic_monad to avoid leaking old_ic
417 !new_ic_int_print = keep_external_name ic_int_print
418 !new_ic_monad = keep_external_name ic_monad
419 dflags = ic_dflags old_ic
420 old_ic = hsc_IC hsc_env
421 empty_ic = emptyInteractiveContext dflags
422 keep_external_name ic_name
423 | nameIsFromExternalPackage this_pkg old_name = old_name
424 | otherwise = ic_name empty_ic
425 where
426 this_pkg = thisPackage dflags
427 old_name = ic_name old_ic
428
429 intermediateCleanTempFiles :: DynFlags -> [ModSummary] -> HscEnv -> IO ()
430 intermediateCleanTempFiles dflags summaries hsc_env
431 = do notIntermediate <- readIORef (filesToNotIntermediateClean dflags)
432 cleanTempFilesExcept dflags (notIntermediate ++ except)
433 where
434 except =
435 -- Save preprocessed files. The preprocessed file *might* be
436 -- the same as the source file, but that doesn't do any
437 -- harm.
438 map ms_hspp_file summaries ++
439 -- Save object files for loaded modules. The point of this
440 -- is that we might have generated and compiled a stub C
441 -- file, and in the case of GHCi the object file will be a
442 -- temporary file which we must not remove because we need
443 -- to load/link it later.
444 hptObjs (hsc_HPT hsc_env)
445
446 -- | If there is no -o option, guess the name of target executable
447 -- by using top-level source file name as a base.
448 guessOutputFile :: GhcMonad m => m ()
449 guessOutputFile = modifySession $ \env ->
450 let dflags = hsc_dflags env
451 -- Force mod_graph to avoid leaking env
452 !mod_graph = hsc_mod_graph env
453 mainModuleSrcPath :: Maybe String
454 mainModuleSrcPath = do
455 let isMain = (== mainModIs dflags) . ms_mod
456 [ms] <- return (filter isMain mod_graph)
457 ml_hs_file (ms_location ms)
458 name = fmap dropExtension mainModuleSrcPath
459
460 name_exe = do
461 #if defined(mingw32_HOST_OS)
462 -- we must add the .exe extention unconditionally here, otherwise
463 -- when name has an extension of its own, the .exe extension will
464 -- not be added by DriverPipeline.exeFileName. See #2248
465 name' <- fmap (<.> "exe") name
466 #else
467 name' <- name
468 #endif
469 mainModuleSrcPath' <- mainModuleSrcPath
470 -- #9930: don't clobber input files (unless they ask for it)
471 if name' == mainModuleSrcPath'
472 then throwGhcException . UsageError $
473 "default output name would overwrite the input file; " ++
474 "must specify -o explicitly"
475 else Just name'
476 in
477 case outputFile dflags of
478 Just _ -> env
479 Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
480
481 -- -----------------------------------------------------------------------------
482 --
483 -- | Prune the HomePackageTable
484 --
485 -- Before doing an upsweep, we can throw away:
486 --
487 -- - For non-stable modules:
488 -- - all ModDetails, all linked code
489 -- - all unlinked code that is out of date with respect to
490 -- the source file
491 --
492 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
493 -- space at the end of the upsweep, because the topmost ModDetails of the
494 -- old HPT holds on to the entire type environment from the previous
495 -- compilation.
496 pruneHomePackageTable :: HomePackageTable
497 -> [ModSummary]
498 -> ([ModuleName],[ModuleName])
499 -> HomePackageTable
500 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
501 = mapUFM prune hpt
502 where prune hmi
503 | is_stable modl = hmi'
504 | otherwise = hmi'{ hm_details = emptyModDetails }
505 where
506 modl = moduleName (mi_module (hm_iface hmi))
507 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
508 = hmi{ hm_linkable = Nothing }
509 | otherwise
510 = hmi
511 where ms = expectJust "prune" (lookupUFM ms_map modl)
512
513 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
514
515 is_stable m = m `elem` stable_obj || m `elem` stable_bco
516
517 -- -----------------------------------------------------------------------------
518 --
519 -- | Return (names of) all those in modsDone who are part of a cycle as defined
520 -- by theGraph.
521 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
522 findPartiallyCompletedCycles modsDone theGraph
523 = chew theGraph
524 where
525 chew [] = []
526 chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting.
527 chew ((CyclicSCC vs):rest)
528 = let names_in_this_cycle = nub (map ms_mod vs)
529 mods_in_this_cycle
530 = nub ([done | done <- modsDone,
531 done `elem` names_in_this_cycle])
532 chewed_rest = chew rest
533 in
534 if notNull mods_in_this_cycle
535 && length mods_in_this_cycle < length names_in_this_cycle
536 then mods_in_this_cycle ++ chewed_rest
537 else chewed_rest
538
539
540 -- ---------------------------------------------------------------------------
541 --
542 -- | Unloading
543 unload :: HscEnv -> [Linkable] -> IO ()
544 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
545 = case ghcLink (hsc_dflags hsc_env) of
546 #ifdef GHCI
547 LinkInMemory -> Linker.unload hsc_env stable_linkables
548 #else
549 LinkInMemory -> panic "unload: no interpreter"
550 -- urgh. avoid warnings:
551 hsc_env stable_linkables
552 #endif
553 _other -> return ()
554
555 -- -----------------------------------------------------------------------------
556 {- |
557
558 Stability tells us which modules definitely do not need to be recompiled.
559 There are two main reasons for having stability:
560
561 - avoid doing a complete upsweep of the module graph in GHCi when
562 modules near the bottom of the tree have not changed.
563
564 - to tell GHCi when it can load object code: we can only load object code
565 for a module when we also load object code fo all of the imports of the
566 module. So we need to know that we will definitely not be recompiling
567 any of these modules, and we can use the object code.
568
569 The stability check is as follows. Both stableObject and
570 stableBCO are used during the upsweep phase later.
571
572 @
573 stable m = stableObject m || stableBCO m
574
575 stableObject m =
576 all stableObject (imports m)
577 && old linkable does not exist, or is == on-disk .o
578 && date(on-disk .o) > date(.hs)
579
580 stableBCO m =
581 all stable (imports m)
582 && date(BCO) > date(.hs)
583 @
584
585 These properties embody the following ideas:
586
587 - if a module is stable, then:
588
589 - if it has been compiled in a previous pass (present in HPT)
590 then it does not need to be compiled or re-linked.
591
592 - if it has not been compiled in a previous pass,
593 then we only need to read its .hi file from disk and
594 link it to produce a 'ModDetails'.
595
596 - if a modules is not stable, we will definitely be at least
597 re-linking, and possibly re-compiling it during the 'upsweep'.
598 All non-stable modules can (and should) therefore be unlinked
599 before the 'upsweep'.
600
601 - Note that objects are only considered stable if they only depend
602 on other objects. We can't link object code against byte code.
603 -}
604 checkStability
605 :: HomePackageTable -- HPT from last compilation
606 -> [SCC ModSummary] -- current module graph (cyclic)
607 -> [ModuleName] -- all home modules
608 -> ([ModuleName], -- stableObject
609 [ModuleName]) -- stableBCO
610
611 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
612 where
613 checkSCC (stable_obj, stable_bco) scc0
614 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
615 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
616 | otherwise = (stable_obj, stable_bco)
617 where
618 scc = flattenSCC scc0
619 scc_mods = map ms_mod_name scc
620 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
621
622 scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc))
623 -- all imports outside the current SCC, but in the home pkg
624
625 stable_obj_imps = map (`elem` stable_obj) scc_allimps
626 stable_bco_imps = map (`elem` stable_bco) scc_allimps
627
628 stableObjects =
629 and stable_obj_imps
630 && all object_ok scc
631
632 stableBCOs =
633 and (zipWith (||) stable_obj_imps stable_bco_imps)
634 && all bco_ok scc
635
636 object_ok ms
637 | gopt Opt_ForceRecomp (ms_hspp_opts ms) = False
638 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
639 && same_as_prev t
640 | otherwise = False
641 where
642 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
643 Just hmi | Just l <- hm_linkable hmi
644 -> isObjectLinkable l && t == linkableTime l
645 _other -> True
646 -- why '>=' rather than '>' above? If the filesystem stores
647 -- times to the nearset second, we may occasionally find that
648 -- the object & source have the same modification time,
649 -- especially if the source was automatically generated
650 -- and compiled. Using >= is slightly unsafe, but it matches
651 -- make's behaviour.
652 --
653 -- But see #5527, where someone ran into this and it caused
654 -- a problem.
655
656 bco_ok ms
657 | gopt Opt_ForceRecomp (ms_hspp_opts ms) = False
658 | otherwise = case lookupUFM hpt (ms_mod_name ms) of
659 Just hmi | Just l <- hm_linkable hmi ->
660 not (isObjectLinkable l) &&
661 linkableTime l >= ms_hs_date ms
662 _other -> False
663
664 {- Parallel Upsweep
665 -
666 - The parallel upsweep attempts to concurrently compile the modules in the
667 - compilation graph using multiple Haskell threads.
668 -
669 - The Algorithm
670 -
671 - A Haskell thread is spawned for each module in the module graph, waiting for
672 - its direct dependencies to finish building before it itself begins to build.
673 -
674 - Each module is associated with an initially empty MVar that stores the
675 - result of that particular module's compile. If the compile succeeded, then
676 - the HscEnv (synchronized by an MVar) is updated with the fresh HMI of that
677 - module, and the module's HMI is deleted from the old HPT (synchronized by an
678 - IORef) to save space.
679 -
680 - Instead of immediately outputting messages to the standard handles, all
681 - compilation output is deferred to a per-module TQueue. A QSem is used to
682 - limit the number of workers that are compiling simultaneously.
683 -
684 - Meanwhile, the main thread sequentially loops over all the modules in the
685 - module graph, outputting the messages stored in each module's TQueue.
686 -}
687
688 -- | Each module is given a unique 'LogQueue' to redirect compilation messages
689 -- to. A 'Nothing' value contains the result of compilation, and denotes the
690 -- end of the message queue.
691 data LogQueue = LogQueue !(IORef [Maybe (WarnReason, Severity, SrcSpan, PprStyle, MsgDoc)])
692 !(MVar ())
693
694 -- | The graph of modules to compile and their corresponding result 'MVar' and
695 -- 'LogQueue'.
696 type CompilationGraph = [(ModSummary, MVar SuccessFlag, LogQueue)]
697
698 -- | Build a 'CompilationGraph' out of a list of strongly-connected modules,
699 -- also returning the first, if any, encountered module cycle.
700 buildCompGraph :: [SCC ModSummary] -> IO (CompilationGraph, Maybe [ModSummary])
701 buildCompGraph [] = return ([], Nothing)
702 buildCompGraph (scc:sccs) = case scc of
703 AcyclicSCC ms -> do
704 mvar <- newEmptyMVar
705 log_queue <- do
706 ref <- newIORef []
707 sem <- newEmptyMVar
708 return (LogQueue ref sem)
709 (rest,cycle) <- buildCompGraph sccs
710 return ((ms,mvar,log_queue):rest, cycle)
711 CyclicSCC mss -> return ([], Just mss)
712
713 -- A Module and whether it is a boot module.
714 type BuildModule = (Module, IsBoot)
715
716 -- | 'Bool' indicating if a module is a boot module or not. We need to treat
717 -- boot modules specially when building compilation graphs, since they break
718 -- cycles. Regular source files and signature files are treated equivalently.
719 data IsBoot = IsBoot | NotBoot
720 deriving (Ord, Eq, Show, Read)
721
722 -- | Tests if an 'HscSource' is a boot file, primarily for constructing
723 -- elements of 'BuildModule'.
724 hscSourceToIsBoot :: HscSource -> IsBoot
725 hscSourceToIsBoot HsBootFile = IsBoot
726 hscSourceToIsBoot _ = NotBoot
727
728 mkBuildModule :: ModSummary -> BuildModule
729 mkBuildModule ms = (ms_mod ms, if isBootSummary ms then IsBoot else NotBoot)
730
731 -- | The entry point to the parallel upsweep.
732 --
733 -- See also the simpler, sequential 'upsweep'.
734 parUpsweep
735 :: GhcMonad m
736 => Int
737 -- ^ The number of workers we wish to run in parallel
738 -> HomePackageTable
739 -> ([ModuleName],[ModuleName])
740 -> (HscEnv -> IO ())
741 -> [SCC ModSummary]
742 -> m (SuccessFlag,
743 [ModSummary])
744 parUpsweep n_jobs old_hpt stable_mods cleanup sccs = do
745 hsc_env <- getSession
746 let dflags = hsc_dflags hsc_env
747
748 -- The bits of shared state we'll be using:
749
750 -- The global HscEnv is updated with the module's HMI when a module
751 -- successfully compiles.
752 hsc_env_var <- liftIO $ newMVar hsc_env
753
754 -- The old HPT is used for recompilation checking in upsweep_mod. When a
755 -- module successfully gets compiled, its HMI is pruned from the old HPT.
756 old_hpt_var <- liftIO $ newIORef old_hpt
757
758 -- What we use to limit parallelism with.
759 par_sem <- liftIO $ newQSem n_jobs
760
761
762 let updNumCapabilities = liftIO $ do
763 n_capabilities <- getNumCapabilities
764 unless (n_capabilities /= 1) $ setNumCapabilities n_jobs
765 return n_capabilities
766 -- Reset the number of capabilities once the upsweep ends.
767 let resetNumCapabilities orig_n = liftIO $ setNumCapabilities orig_n
768
769 gbracket updNumCapabilities resetNumCapabilities $ \_ -> do
770
771 -- Sync the global session with the latest HscEnv once the upsweep ends.
772 let finallySyncSession io = io `gfinally` do
773 hsc_env <- liftIO $ readMVar hsc_env_var
774 setSession hsc_env
775
776 finallySyncSession $ do
777
778 -- Build the compilation graph out of the list of SCCs. Module cycles are
779 -- handled at the very end, after some useful work gets done. Note that
780 -- this list is topologically sorted (by virtue of 'sccs' being sorted so).
781 (comp_graph,cycle) <- liftIO $ buildCompGraph sccs
782 let comp_graph_w_idx = zip comp_graph [1..]
783
784 -- The list of all loops in the compilation graph.
785 -- NB: For convenience, the last module of each loop (aka the module that
786 -- finishes the loop) is prepended to the beginning of the loop.
787 let comp_graph_loops = go (map fstOf3 (reverse comp_graph))
788 where
789 go [] = []
790 go (ms:mss) | Just loop <- getModLoop ms (ms:mss)
791 = map mkBuildModule (ms:loop) : go mss
792 | otherwise
793 = go mss
794
795 -- Build a Map out of the compilation graph with which we can efficiently
796 -- look up the result MVar associated with a particular home module.
797 let home_mod_map :: Map BuildModule (MVar SuccessFlag, Int)
798 home_mod_map =
799 Map.fromList [ (mkBuildModule ms, (mvar, idx))
800 | ((ms,mvar,_),idx) <- comp_graph_w_idx ]
801
802
803 liftIO $ label_self "main --make thread"
804 -- For each module in the module graph, spawn a worker thread that will
805 -- compile this module.
806 let { spawnWorkers = forM comp_graph_w_idx $ \((mod,!mvar,!log_queue),!mod_idx) ->
807 forkIOWithUnmask $ \unmask -> do
808 liftIO $ label_self $ unwords
809 [ "worker --make thread"
810 , "for module"
811 , show (moduleNameString (ms_mod_name mod))
812 , "number"
813 , show mod_idx
814 ]
815 -- Replace the default log_action with one that writes each
816 -- message to the module's log_queue. The main thread will
817 -- deal with synchronously printing these messages.
818 --
819 -- Use a local filesToClean var so that we can clean up
820 -- intermediate files in a timely fashion (as soon as
821 -- compilation for that module is finished) without having to
822 -- worry about accidentally deleting a simultaneous compile's
823 -- important files.
824 lcl_files_to_clean <- newIORef []
825 let lcl_dflags = dflags { log_action = parLogAction log_queue
826 , filesToClean = lcl_files_to_clean }
827
828 -- Unmask asynchronous exceptions and perform the thread-local
829 -- work to compile the module (see parUpsweep_one).
830 m_res <- try $ unmask $ prettyPrintGhcErrors lcl_dflags $
831 parUpsweep_one mod home_mod_map comp_graph_loops
832 lcl_dflags cleanup
833 par_sem hsc_env_var old_hpt_var
834 stable_mods mod_idx (length sccs)
835
836 res <- case m_res of
837 Right flag -> return flag
838 Left exc -> do
839 -- Don't print ThreadKilled exceptions: they are used
840 -- to kill the worker thread in the event of a user
841 -- interrupt, and the user doesn't have to be informed
842 -- about that.
843 when (fromException exc /= Just ThreadKilled)
844 (errorMsg lcl_dflags (text (show exc)))
845 return Failed
846
847 -- Populate the result MVar.
848 putMVar mvar res
849
850 -- Write the end marker to the message queue, telling the main
851 -- thread that it can stop waiting for messages from this
852 -- particular compile.
853 writeLogQueue log_queue Nothing
854
855 -- Add the remaining files that weren't cleaned up to the
856 -- global filesToClean ref, for cleanup later.
857 files_kept <- readIORef (filesToClean lcl_dflags)
858 addFilesToClean dflags files_kept
859
860
861 -- Kill all the workers, masking interrupts (since killThread is
862 -- interruptible). XXX: This is not ideal.
863 ; killWorkers = uninterruptibleMask_ . mapM_ killThread }
864
865
866 -- Spawn the workers, making sure to kill them later. Collect the results
867 -- of each compile.
868 results <- liftIO $ bracket spawnWorkers killWorkers $ \_ ->
869 -- Loop over each module in the compilation graph in order, printing
870 -- each message from its log_queue.
871 forM comp_graph $ \(mod,mvar,log_queue) -> do
872 printLogs dflags log_queue
873 result <- readMVar mvar
874 if succeeded result then return (Just mod) else return Nothing
875
876
877 -- Collect and return the ModSummaries of all the successful compiles.
878 -- NB: Reverse this list to maintain output parity with the sequential upsweep.
879 let ok_results = reverse (catMaybes results)
880
881 -- Handle any cycle in the original compilation graph and return the result
882 -- of the upsweep.
883 case cycle of
884 Just mss -> do
885 liftIO $ fatalErrorMsg dflags (cyclicModuleErr mss)
886 return (Failed,ok_results)
887 Nothing -> do
888 let success_flag = successIf (all isJust results)
889 return (success_flag,ok_results)
890
891 where
892 writeLogQueue :: LogQueue -> Maybe (WarnReason,Severity,SrcSpan,PprStyle,MsgDoc) -> IO ()
893 writeLogQueue (LogQueue ref sem) msg = do
894 atomicModifyIORef' ref $ \msgs -> (msg:msgs,())
895 _ <- tryPutMVar sem ()
896 return ()
897
898 -- The log_action callback that is used to synchronize messages from a
899 -- worker thread.
900 parLogAction :: LogQueue -> LogAction
901 parLogAction log_queue _dflags !reason !severity !srcSpan !style !msg = do
902 writeLogQueue log_queue (Just (reason,severity,srcSpan,style,msg))
903
904 -- Print each message from the log_queue using the log_action from the
905 -- session's DynFlags.
906 printLogs :: DynFlags -> LogQueue -> IO ()
907 printLogs !dflags (LogQueue ref sem) = read_msgs
908 where read_msgs = do
909 takeMVar sem
910 msgs <- atomicModifyIORef' ref $ \xs -> ([], reverse xs)
911 print_loop msgs
912
913 print_loop [] = read_msgs
914 print_loop (x:xs) = case x of
915 Just (reason,severity,srcSpan,style,msg) -> do
916 log_action dflags dflags reason severity srcSpan style msg
917 print_loop xs
918 -- Exit the loop once we encounter the end marker.
919 Nothing -> return ()
920
921 -- The interruptible subset of the worker threads' work.
922 parUpsweep_one
923 :: ModSummary
924 -- ^ The module we wish to compile
925 -> Map BuildModule (MVar SuccessFlag, Int)
926 -- ^ The map of home modules and their result MVar
927 -> [[BuildModule]]
928 -- ^ The list of all module loops within the compilation graph.
929 -> DynFlags
930 -- ^ The thread-local DynFlags
931 -> (HscEnv -> IO ())
932 -- ^ The callback for cleaning up intermediate files
933 -> QSem
934 -- ^ The semaphore for limiting the number of simultaneous compiles
935 -> MVar HscEnv
936 -- ^ The MVar that synchronizes updates to the global HscEnv
937 -> IORef HomePackageTable
938 -- ^ The old HPT
939 -> ([ModuleName],[ModuleName])
940 -- ^ Lists of stable objects and BCOs
941 -> Int
942 -- ^ The index of this module
943 -> Int
944 -- ^ The total number of modules
945 -> IO SuccessFlag
946 -- ^ The result of this compile
947 parUpsweep_one mod home_mod_map comp_graph_loops lcl_dflags cleanup par_sem
948 hsc_env_var old_hpt_var stable_mods mod_index num_mods = do
949
950 let this_build_mod = mkBuildModule mod
951
952 let home_imps = map unLoc $ ms_home_imps mod
953 let home_src_imps = map unLoc $ ms_home_srcimps mod
954
955 -- All the textual imports of this module.
956 let textual_deps = Set.fromList $ mapFst (mkModule (thisPackage lcl_dflags)) $
957 zip home_imps (repeat NotBoot) ++
958 zip home_src_imps (repeat IsBoot)
959
960 -- Dealing with module loops
961 -- ~~~~~~~~~~~~~~~~~~~~~~~~~
962 --
963 -- Not only do we have to deal with explicit textual dependencies, we also
964 -- have to deal with implicit dependencies introduced by import cycles that
965 -- are broken by an hs-boot file. We have to ensure that:
966 --
967 -- 1. A module that breaks a loop must depend on all the modules in the
968 -- loop (transitively or otherwise). This is normally always fulfilled
969 -- by the module's textual dependencies except in degenerate loops,
970 -- e.g.:
971 --
972 -- A.hs imports B.hs-boot
973 -- B.hs doesn't import A.hs
974 -- C.hs imports A.hs, B.hs
975 --
976 -- In this scenario, getModLoop will detect the module loop [A,B] but
977 -- the loop finisher B doesn't depend on A. So we have to explicitly add
978 -- A in as a dependency of B when we are compiling B.
979 --
980 -- 2. A module that depends on a module in an external loop can't proceed
981 -- until the entire loop is re-typechecked.
982 --
983 -- These two invariants have to be maintained to correctly build a
984 -- compilation graph with one or more loops.
985
986
987 -- The loop that this module will finish. After this module successfully
988 -- compiles, this loop is going to get re-typechecked.
989 let finish_loop = listToMaybe
990 [ tail loop | loop <- comp_graph_loops
991 , head loop == this_build_mod ]
992
993 -- If this module finishes a loop then it must depend on all the other
994 -- modules in that loop because the entire module loop is going to be
995 -- re-typechecked once this module gets compiled. These extra dependencies
996 -- are this module's "internal" loop dependencies, because this module is
997 -- inside the loop in question.
998 let int_loop_deps = Set.fromList $
999 case finish_loop of
1000 Nothing -> []
1001 Just loop -> filter (/= this_build_mod) loop
1002
1003 -- If this module depends on a module within a loop then it must wait for
1004 -- that loop to get re-typechecked, i.e. it must wait on the module that
1005 -- finishes that loop. These extra dependencies are this module's
1006 -- "external" loop dependencies, because this module is outside of the
1007 -- loop(s) in question.
1008 let ext_loop_deps = Set.fromList
1009 [ head loop | loop <- comp_graph_loops
1010 , any (`Set.member` textual_deps) loop
1011 , this_build_mod `notElem` loop ]
1012
1013
1014 let all_deps = foldl1 Set.union [textual_deps, int_loop_deps, ext_loop_deps]
1015
1016 -- All of the module's home-module dependencies.
1017 let home_deps_with_idx =
1018 [ home_dep | dep <- Set.toList all_deps
1019 , Just home_dep <- [Map.lookup dep home_mod_map] ]
1020
1021 -- Sort the list of dependencies in reverse-topological order. This way, by
1022 -- the time we get woken up by the result of an earlier dependency,
1023 -- subsequent dependencies are more likely to have finished. This step
1024 -- effectively reduces the number of MVars that each thread blocks on.
1025 let home_deps = map fst $ sortBy (flip (comparing snd)) home_deps_with_idx
1026
1027 -- Wait for the all the module's dependencies to finish building.
1028 deps_ok <- allM (fmap succeeded . readMVar) home_deps
1029
1030 -- We can't build this module if any of its dependencies failed to build.
1031 if not deps_ok
1032 then return Failed
1033 else do
1034 -- Any hsc_env at this point is OK to use since we only really require
1035 -- that the HPT contains the HMIs of our dependencies.
1036 hsc_env <- readMVar hsc_env_var
1037 old_hpt <- readIORef old_hpt_var
1038
1039 let logger err = printBagOfErrors lcl_dflags (srcErrorMessages err)
1040
1041 -- Limit the number of parallel compiles.
1042 let withSem sem = bracket_ (waitQSem sem) (signalQSem sem)
1043 mb_mod_info <- withSem par_sem $
1044 handleSourceError (\err -> do logger err; return Nothing) $ do
1045 -- Have the ModSummary and HscEnv point to our local log_action
1046 -- and filesToClean var.
1047 let lcl_mod = localize_mod mod
1048 let lcl_hsc_env = localize_hsc_env hsc_env
1049
1050 -- Compile the module.
1051 mod_info <- upsweep_mod lcl_hsc_env old_hpt stable_mods lcl_mod
1052 mod_index num_mods
1053 return (Just mod_info)
1054
1055 case mb_mod_info of
1056 Nothing -> return Failed
1057 Just mod_info -> do
1058 let this_mod = ms_mod_name mod
1059
1060 -- Prune the old HPT unless this is an hs-boot module.
1061 unless (isBootSummary mod) $
1062 atomicModifyIORef' old_hpt_var $ \old_hpt ->
1063 (delFromUFM old_hpt this_mod, ())
1064
1065 -- Update and fetch the global HscEnv.
1066 lcl_hsc_env' <- modifyMVar hsc_env_var $ \hsc_env -> do
1067 let hsc_env' = hsc_env { hsc_HPT = addToUFM (hsc_HPT hsc_env)
1068 this_mod mod_info }
1069 -- If this module is a loop finisher, now is the time to
1070 -- re-typecheck the loop.
1071 hsc_env'' <- case finish_loop of
1072 Nothing -> return hsc_env'
1073 Just loop -> typecheckLoop lcl_dflags hsc_env' $
1074 map (moduleName . fst) loop
1075 return (hsc_env'', localize_hsc_env hsc_env'')
1076
1077 -- Clean up any intermediate files.
1078 cleanup lcl_hsc_env'
1079 return Succeeded
1080
1081 where
1082 localize_mod mod
1083 = mod { ms_hspp_opts = (ms_hspp_opts mod)
1084 { log_action = log_action lcl_dflags
1085 , filesToClean = filesToClean lcl_dflags } }
1086
1087 localize_hsc_env hsc_env
1088 = hsc_env { hsc_dflags = (hsc_dflags hsc_env)
1089 { log_action = log_action lcl_dflags
1090 , filesToClean = filesToClean lcl_dflags } }
1091
1092 -- -----------------------------------------------------------------------------
1093 --
1094 -- | The upsweep
1095 --
1096 -- This is where we compile each module in the module graph, in a pass
1097 -- from the bottom to the top of the graph.
1098 --
1099 -- There better had not be any cyclic groups here -- we check for them.
1100 upsweep
1101 :: GhcMonad m
1102 => HomePackageTable -- ^ HPT from last time round (pruned)
1103 -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability)
1104 -> (HscEnv -> IO ()) -- ^ How to clean up unwanted tmp files
1105 -> [SCC ModSummary] -- ^ Mods to do (the worklist)
1106 -> m (SuccessFlag,
1107 [ModSummary])
1108 -- ^ Returns:
1109 --
1110 -- 1. A flag whether the complete upsweep was successful.
1111 -- 2. The 'HscEnv' in the monad has an updated HPT
1112 -- 3. A list of modules which succeeded loading.
1113
1114 upsweep old_hpt stable_mods cleanup sccs = do
1115 (res, done) <- upsweep' old_hpt [] sccs 1 (length sccs)
1116 return (res, reverse done)
1117 where
1118
1119 upsweep' _old_hpt done
1120 [] _ _
1121 = return (Succeeded, done)
1122
1123 upsweep' _old_hpt done
1124 (CyclicSCC ms:_) _ _
1125 = do dflags <- getSessionDynFlags
1126 liftIO $ fatalErrorMsg dflags (cyclicModuleErr ms)
1127 return (Failed, done)
1128
1129 upsweep' old_hpt done
1130 (AcyclicSCC mod:mods) mod_index nmods
1131 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1132 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1133 -- (moduleEnvElts (hsc_HPT hsc_env)))
1134 let logger _mod = defaultWarnErrLogger
1135
1136 hsc_env <- getSession
1137
1138 -- Remove unwanted tmp files between compilations
1139 liftIO (cleanup hsc_env)
1140
1141 mb_mod_info
1142 <- handleSourceError
1143 (\err -> do logger mod (Just err); return Nothing) $ do
1144 mod_info <- liftIO $ upsweep_mod hsc_env old_hpt stable_mods
1145 mod mod_index nmods
1146 logger mod Nothing -- log warnings
1147 return (Just mod_info)
1148
1149 case mb_mod_info of
1150 Nothing -> return (Failed, done)
1151 Just mod_info -> do
1152 let this_mod = ms_mod_name mod
1153
1154 -- Add new info to hsc_env
1155 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1156 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1157
1158 -- Space-saving: delete the old HPT entry
1159 -- for mod BUT if mod is a hs-boot
1160 -- node, don't delete it. For the
1161 -- interface, the HPT entry is probaby for the
1162 -- main Haskell source file. Deleting it
1163 -- would force the real module to be recompiled
1164 -- every time.
1165 old_hpt1 | isBootSummary mod = old_hpt
1166 | otherwise = delFromUFM old_hpt this_mod
1167
1168 done' = mod:done
1169
1170 -- fixup our HomePackageTable after we've finished compiling
1171 -- a mutually-recursive loop. See reTypecheckLoop, below.
1172 hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done'
1173 setSession hsc_env2
1174
1175 upsweep' old_hpt1 done' mods (mod_index+1) nmods
1176
1177 maybeGetIfaceDate :: DynFlags -> ModLocation -> IO (Maybe UTCTime)
1178 maybeGetIfaceDate dflags location
1179 | writeInterfaceOnlyMode dflags
1180 -- Minor optimization: it should be harmless to check the hi file location
1181 -- always, but it's better to avoid hitting the filesystem if possible.
1182 = modificationTimeIfExists (ml_hi_file location)
1183 | otherwise
1184 = return Nothing
1185
1186 -- | Compile a single module. Always produce a Linkable for it if
1187 -- successful. If no compilation happened, return the old Linkable.
1188 upsweep_mod :: HscEnv
1189 -> HomePackageTable
1190 -> ([ModuleName],[ModuleName])
1191 -> ModSummary
1192 -> Int -- index of module
1193 -> Int -- total number of modules
1194 -> IO HomeModInfo
1195 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1196 = let
1197 this_mod_name = ms_mod_name summary
1198 this_mod = ms_mod summary
1199 mb_obj_date = ms_obj_date summary
1200 mb_if_date = ms_iface_date summary
1201 obj_fn = ml_obj_file (ms_location summary)
1202 hs_date = ms_hs_date summary
1203
1204 is_stable_obj = this_mod_name `elem` stable_obj
1205 is_stable_bco = this_mod_name `elem` stable_bco
1206
1207 old_hmi = lookupUFM old_hpt this_mod_name
1208
1209 -- We're using the dflags for this module now, obtained by
1210 -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1211 dflags = ms_hspp_opts summary
1212 prevailing_target = hscTarget (hsc_dflags hsc_env)
1213 local_target = hscTarget dflags
1214
1215 -- If OPTIONS_GHC contains -fasm or -fllvm, be careful that
1216 -- we don't do anything dodgy: these should only work to change
1217 -- from -fllvm to -fasm and vice-versa, otherwise we could
1218 -- end up trying to link object code to byte code.
1219 target = if prevailing_target /= local_target
1220 && (not (isObjectTarget prevailing_target)
1221 || not (isObjectTarget local_target))
1222 then prevailing_target
1223 else local_target
1224
1225 -- store the corrected hscTarget into the summary
1226 summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1227
1228 -- The old interface is ok if
1229 -- a) we're compiling a source file, and the old HPT
1230 -- entry is for a source file
1231 -- b) we're compiling a hs-boot file
1232 -- Case (b) allows an hs-boot file to get the interface of its
1233 -- real source file on the second iteration of the compilation
1234 -- manager, but that does no harm. Otherwise the hs-boot file
1235 -- will always be recompiled
1236
1237 mb_old_iface
1238 = case old_hmi of
1239 Nothing -> Nothing
1240 Just hm_info | isBootSummary summary -> Just iface
1241 | not (mi_boot iface) -> Just iface
1242 | otherwise -> Nothing
1243 where
1244 iface = hm_iface hm_info
1245
1246 compile_it :: Maybe Linkable -> SourceModified -> IO HomeModInfo
1247 compile_it mb_linkable src_modified =
1248 compileOne hsc_env summary' mod_index nmods
1249 mb_old_iface mb_linkable src_modified
1250
1251 compile_it_discard_iface :: Maybe Linkable -> SourceModified
1252 -> IO HomeModInfo
1253 compile_it_discard_iface mb_linkable src_modified =
1254 compileOne hsc_env summary' mod_index nmods
1255 Nothing mb_linkable src_modified
1256
1257 -- With the HscNothing target we create empty linkables to avoid
1258 -- recompilation. We have to detect these to recompile anyway if
1259 -- the target changed since the last compile.
1260 is_fake_linkable
1261 | Just hmi <- old_hmi, Just l <- hm_linkable hmi =
1262 null (linkableUnlinked l)
1263 | otherwise =
1264 -- we have no linkable, so it cannot be fake
1265 False
1266
1267 implies False _ = True
1268 implies True x = x
1269
1270 in
1271 case () of
1272 _
1273 -- Regardless of whether we're generating object code or
1274 -- byte code, we can always use an existing object file
1275 -- if it is *stable* (see checkStability).
1276 | is_stable_obj, Just hmi <- old_hmi -> do
1277 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1278 (text "skipping stable obj mod:" <+> ppr this_mod_name)
1279 return hmi
1280 -- object is stable, and we have an entry in the
1281 -- old HPT: nothing to do
1282
1283 | is_stable_obj, isNothing old_hmi -> do
1284 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1285 (text "compiling stable on-disk mod:" <+> ppr this_mod_name)
1286 linkable <- liftIO $ findObjectLinkable this_mod obj_fn
1287 (expectJust "upsweep1" mb_obj_date)
1288 compile_it (Just linkable) SourceUnmodifiedAndStable
1289 -- object is stable, but we need to load the interface
1290 -- off disk to make a HMI.
1291
1292 | not (isObjectTarget target), is_stable_bco,
1293 (target /= HscNothing) `implies` not is_fake_linkable ->
1294 ASSERT(isJust old_hmi) -- must be in the old_hpt
1295 let Just hmi = old_hmi in do
1296 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1297 (text "skipping stable BCO mod:" <+> ppr this_mod_name)
1298 return hmi
1299 -- BCO is stable: nothing to do
1300
1301 | not (isObjectTarget target),
1302 Just hmi <- old_hmi,
1303 Just l <- hm_linkable hmi,
1304 not (isObjectLinkable l),
1305 (target /= HscNothing) `implies` not is_fake_linkable,
1306 linkableTime l >= ms_hs_date summary -> do
1307 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1308 (text "compiling non-stable BCO mod:" <+> ppr this_mod_name)
1309 compile_it (Just l) SourceUnmodified
1310 -- we have an old BCO that is up to date with respect
1311 -- to the source: do a recompilation check as normal.
1312
1313 -- When generating object code, if there's an up-to-date
1314 -- object file on the disk, then we can use it.
1315 -- However, if the object file is new (compared to any
1316 -- linkable we had from a previous compilation), then we
1317 -- must discard any in-memory interface, because this
1318 -- means the user has compiled the source file
1319 -- separately and generated a new interface, that we must
1320 -- read from the disk.
1321 --
1322 | isObjectTarget target,
1323 Just obj_date <- mb_obj_date,
1324 obj_date >= hs_date -> do
1325 case old_hmi of
1326 Just hmi
1327 | Just l <- hm_linkable hmi,
1328 isObjectLinkable l && linkableTime l == obj_date -> do
1329 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1330 (text "compiling mod with new on-disk obj:" <+> ppr this_mod_name)
1331 compile_it (Just l) SourceUnmodified
1332 _otherwise -> do
1333 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1334 (text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name)
1335 linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date
1336 compile_it_discard_iface (Just linkable) SourceUnmodified
1337
1338 -- See Note [Recompilation checking when typechecking only]
1339 | writeInterfaceOnlyMode dflags,
1340 Just if_date <- mb_if_date,
1341 if_date >= hs_date -> do
1342 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1343 (text "skipping tc'd mod:" <+> ppr this_mod_name)
1344 compile_it Nothing SourceUnmodified
1345
1346 _otherwise -> do
1347 liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5
1348 (text "compiling mod:" <+> ppr this_mod_name)
1349 compile_it Nothing SourceModified
1350
1351 -- Note [Recompilation checking when typechecking only]
1352 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1353 -- If we are compiling with -fno-code -fwrite-interface, there won't
1354 -- be any object code that we can compare against, nor should there
1355 -- be: we're *just* generating interface files. In this case, we
1356 -- want to check if the interface file is new, in lieu of the object
1357 -- file. See also Trac #9243.
1358
1359
1360 -- Filter modules in the HPT
1361 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1362 retainInTopLevelEnvs keep_these hpt
1363 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1364 | mod <- keep_these
1365 , let mb_mod_info = lookupUFM hpt mod
1366 , isJust mb_mod_info ]
1367
1368 -- ---------------------------------------------------------------------------
1369 -- Typecheck module loops
1370 {-
1371 See bug #930. This code fixes a long-standing bug in --make. The
1372 problem is that when compiling the modules *inside* a loop, a data
1373 type that is only defined at the top of the loop looks opaque; but
1374 after the loop is done, the structure of the data type becomes
1375 apparent.
1376
1377 The difficulty is then that two different bits of code have
1378 different notions of what the data type looks like.
1379
1380 The idea is that after we compile a module which also has an .hs-boot
1381 file, we re-generate the ModDetails for each of the modules that
1382 depends on the .hs-boot file, so that everyone points to the proper
1383 TyCons, Ids etc. defined by the real module, not the boot module.
1384 Fortunately re-generating a ModDetails from a ModIface is easy: the
1385 function TcIface.typecheckIface does exactly that.
1386
1387 Picking the modules to re-typecheck is slightly tricky. Starting from
1388 the module graph consisting of the modules that have already been
1389 compiled, we reverse the edges (so they point from the imported module
1390 to the importing module), and depth-first-search from the .hs-boot
1391 node. This gives us all the modules that depend transitively on the
1392 .hs-boot module, and those are exactly the modules that we need to
1393 re-typecheck.
1394
1395 Following this fix, GHC can compile itself with --make -O2.
1396 -}
1397
1398 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1399 reTypecheckLoop hsc_env ms graph
1400 | Just loop <- getModLoop ms graph
1401 , let non_boot = filter (not.isBootSummary) loop
1402 = typecheckLoop (hsc_dflags hsc_env) hsc_env (map ms_mod_name non_boot)
1403 | otherwise
1404 = return hsc_env
1405
1406 getModLoop :: ModSummary -> ModuleGraph -> Maybe [ModSummary]
1407 getModLoop ms graph
1408 | not (isBootSummary ms)
1409 , any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1410 , let mss = reachableBackwards (ms_mod_name ms) graph
1411 = Just mss
1412 | otherwise
1413 = Nothing
1414 where
1415 this_mod = ms_mod ms
1416
1417 typecheckLoop :: DynFlags -> HscEnv -> [ModuleName] -> IO HscEnv
1418 typecheckLoop dflags hsc_env mods = do
1419 debugTraceMsg dflags 2 $
1420 text "Re-typechecking loop: " <> ppr mods
1421 new_hpt <-
1422 fixIO $ \new_hpt -> do
1423 let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1424 mds <- initIfaceCheck new_hsc_env $
1425 mapM (typecheckIface . hm_iface) hmis
1426 let new_hpt = addListToUFM old_hpt
1427 (zip mods [ hmi{ hm_details = details }
1428 | (hmi,details) <- zip hmis mds ])
1429 return new_hpt
1430 return hsc_env{ hsc_HPT = new_hpt }
1431 where
1432 old_hpt = hsc_HPT hsc_env
1433 hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1434
1435 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1436 reachableBackwards mod summaries
1437 = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ]
1438 where -- the rest just sets up the graph:
1439 (graph, lookup_node) = moduleGraphNodes False summaries
1440 root = expectJust "reachableBackwards" (lookup_node HsBootFile mod)
1441
1442 -- ---------------------------------------------------------------------------
1443 --
1444 -- | Topological sort of the module graph
1445 topSortModuleGraph
1446 :: Bool
1447 -- ^ Drop hi-boot nodes? (see below)
1448 -> [ModSummary]
1449 -> Maybe ModuleName
1450 -- ^ Root module name. If @Nothing@, use the full graph.
1451 -> [SCC ModSummary]
1452 -- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1453 -- The resulting list of strongly-connected-components is in topologically
1454 -- sorted order, starting with the module(s) at the bottom of the
1455 -- dependency graph (ie compile them first) and ending with the ones at
1456 -- the top.
1457 --
1458 -- Drop hi-boot nodes (first boolean arg)?
1459 --
1460 -- - @False@: treat the hi-boot summaries as nodes of the graph,
1461 -- so the graph must be acyclic
1462 --
1463 -- - @True@: eliminate the hi-boot nodes, and instead pretend
1464 -- the a source-import of Foo is an import of Foo
1465 -- The resulting graph has no hi-boot nodes, but can be cyclic
1466
1467 topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod
1468 = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph
1469 where
1470 (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries
1471
1472 initial_graph = case mb_root_mod of
1473 Nothing -> graph
1474 Just root_mod ->
1475 -- restrict the graph to just those modules reachable from
1476 -- the specified module. We do this by building a graph with
1477 -- the full set of nodes, and determining the reachable set from
1478 -- the specified node.
1479 let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node
1480 | otherwise = throwGhcException (ProgramError "module does not exist")
1481 in graphFromEdgedVertices (seq root (reachableG graph root))
1482
1483 type SummaryNode = (ModSummary, Int, [Int])
1484
1485 summaryNodeKey :: SummaryNode -> Int
1486 summaryNodeKey (_, k, _) = k
1487
1488 summaryNodeSummary :: SummaryNode -> ModSummary
1489 summaryNodeSummary (s, _, _) = s
1490
1491 moduleGraphNodes :: Bool -> [ModSummary]
1492 -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode)
1493 moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node)
1494 where
1495 numbered_summaries = zip summaries [1..]
1496
1497 lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode
1498 lookup_node hs_src mod = Map.lookup (mod, hscSourceToIsBoot hs_src) node_map
1499
1500 lookup_key :: HscSource -> ModuleName -> Maybe Int
1501 lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod)
1502
1503 node_map :: NodeMap SummaryNode
1504 node_map = Map.fromList [ ((moduleName (ms_mod s),
1505 hscSourceToIsBoot (ms_hsc_src s)), node)
1506 | node@(s, _, _) <- nodes ]
1507
1508 -- We use integers as the keys for the SCC algorithm
1509 nodes :: [SummaryNode]
1510 nodes = [ (s, key, out_keys)
1511 | (s, key) <- numbered_summaries
1512 -- Drop the hi-boot ones if told to do so
1513 , not (isBootSummary s && drop_hs_boot_nodes)
1514 , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++
1515 out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++
1516 (-- see [boot-edges] below
1517 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1518 then []
1519 else case lookup_key HsBootFile (ms_mod_name s) of
1520 Nothing -> []
1521 Just k -> [k]) ]
1522
1523 -- [boot-edges] if this is a .hs and there is an equivalent
1524 -- .hs-boot, add a link from the former to the latter. This
1525 -- has the effect of detecting bogus cases where the .hs-boot
1526 -- depends on the .hs, by introducing a cycle. Additionally,
1527 -- it ensures that we will always process the .hs-boot before
1528 -- the .hs, and so the HomePackageTable will always have the
1529 -- most up to date information.
1530
1531 -- Drop hs-boot nodes by using HsSrcFile as the key
1532 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1533 | otherwise = HsBootFile
1534
1535 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1536 out_edge_keys hi_boot ms = mapMaybe (lookup_key hi_boot) ms
1537 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1538 -- IsBoot; else NotBoot
1539
1540 -- The nodes of the graph are keyed by (mod, is boot?) pairs
1541 -- NB: hsig files show up as *normal* nodes (not boot!), since they don't
1542 -- participate in cycles (for now)
1543 type NodeKey = (ModuleName, IsBoot)
1544 type NodeMap a = Map.Map NodeKey a
1545
1546 msKey :: ModSummary -> NodeKey
1547 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot })
1548 = (moduleName mod, hscSourceToIsBoot boot)
1549
1550 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1551 mkNodeMap summaries = Map.fromList [ (msKey s, s) | s <- summaries]
1552
1553 nodeMapElts :: NodeMap a -> [a]
1554 nodeMapElts = Map.elems
1555
1556 -- | If there are {-# SOURCE #-} imports between strongly connected
1557 -- components in the topological sort, then those imports can
1558 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1559 -- were necessary, then the edge would be part of a cycle.
1560 warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m ()
1561 warnUnnecessarySourceImports sccs = do
1562 dflags <- getDynFlags
1563 when (wopt Opt_WarnUnusedImports dflags)
1564 (logWarnings (listToBag (concatMap (check dflags . flattenSCC) sccs)))
1565 where check dflags ms =
1566 let mods_in_this_cycle = map ms_mod_name ms in
1567 [ warn dflags i | m <- ms, i <- ms_home_srcimps m,
1568 unLoc i `notElem` mods_in_this_cycle ]
1569
1570 warn :: DynFlags -> Located ModuleName -> WarnMsg
1571 warn dflags (L loc mod) =
1572 mkPlainErrMsg dflags loc
1573 (text "Warning: {-# SOURCE #-} unnecessary in import of "
1574 <+> quotes (ppr mod))
1575
1576
1577 reportImportErrors :: MonadIO m => [Either ErrMsg b] -> m [b]
1578 reportImportErrors xs | null errs = return oks
1579 | otherwise = throwManyErrors errs
1580 where (errs, oks) = partitionEithers xs
1581
1582 throwManyErrors :: MonadIO m => [ErrMsg] -> m ab
1583 throwManyErrors errs = liftIO $ throwIO $ mkSrcErr $ listToBag errs
1584
1585
1586 -----------------------------------------------------------------------------
1587 --
1588 -- | Downsweep (dependency analysis)
1589 --
1590 -- Chase downwards from the specified root set, returning summaries
1591 -- for all home modules encountered. Only follow source-import
1592 -- links.
1593 --
1594 -- We pass in the previous collection of summaries, which is used as a
1595 -- cache to avoid recalculating a module summary if the source is
1596 -- unchanged.
1597 --
1598 -- The returned list of [ModSummary] nodes has one node for each home-package
1599 -- module, plus one for any hs-boot files. The imports of these nodes
1600 -- are all there, including the imports of non-home-package modules.
1601 downsweep :: HscEnv
1602 -> [ModSummary] -- Old summaries
1603 -> [ModuleName] -- Ignore dependencies on these; treat
1604 -- them as if they were package modules
1605 -> Bool -- True <=> allow multiple targets to have
1606 -- the same module name; this is
1607 -- very useful for ghc -M
1608 -> IO [Either ErrMsg ModSummary]
1609 -- The elts of [ModSummary] all have distinct
1610 -- (Modules, IsBoot) identifiers, unless the Bool is true
1611 -- in which case there can be repeats
1612 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1613 = do
1614 rootSummaries <- mapM getRootSummary roots
1615 rootSummariesOk <- reportImportErrors rootSummaries
1616 let root_map = mkRootMap rootSummariesOk
1617 checkDuplicates root_map
1618 summs <- loop (concatMap calcDeps rootSummariesOk) root_map
1619 return summs
1620 where
1621 -- When we're compiling a signature file, we have an implicit
1622 -- dependency on what-ever the signature's implementation is.
1623 -- (But not when we're type checking!)
1624 calcDeps summ
1625 | HsigFile <- ms_hsc_src summ
1626 , Just m <- getSigOf (hsc_dflags hsc_env) (moduleName (ms_mod summ))
1627 , moduleUnitId m == thisPackage (hsc_dflags hsc_env)
1628 = (noLoc (moduleName m), NotBoot) : msDeps summ
1629 | otherwise = msDeps summ
1630
1631 dflags = hsc_dflags hsc_env
1632 roots = hsc_targets hsc_env
1633
1634 old_summary_map :: NodeMap ModSummary
1635 old_summary_map = mkNodeMap old_summaries
1636
1637 getRootSummary :: Target -> IO (Either ErrMsg ModSummary)
1638 getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf)
1639 = do exists <- liftIO $ doesFileExist file
1640 if exists
1641 then Right `fmap` summariseFile hsc_env old_summaries file mb_phase
1642 obj_allowed maybe_buf
1643 else return $ Left $ mkPlainErrMsg dflags noSrcSpan $
1644 text "can't find file:" <+> text file
1645 getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf)
1646 = do maybe_summary <- summariseModule hsc_env old_summary_map NotBoot
1647 (L rootLoc modl) obj_allowed
1648 maybe_buf excl_mods
1649 case maybe_summary of
1650 Nothing -> return $ Left $ packageModErr dflags modl
1651 Just s -> return s
1652
1653 rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1654
1655 -- In a root module, the filename is allowed to diverge from the module
1656 -- name, so we have to check that there aren't multiple root files
1657 -- defining the same module (otherwise the duplicates will be silently
1658 -- ignored, leading to confusing behaviour).
1659 checkDuplicates :: NodeMap [Either ErrMsg ModSummary] -> IO ()
1660 checkDuplicates root_map
1661 | allow_dup_roots = return ()
1662 | null dup_roots = return ()
1663 | otherwise = liftIO $ multiRootsErr dflags (head dup_roots)
1664 where
1665 dup_roots :: [[ModSummary]] -- Each at least of length 2
1666 dup_roots = filterOut isSingleton $ map rights $ nodeMapElts root_map
1667
1668 loop :: [(Located ModuleName,IsBoot)]
1669 -- Work list: process these modules
1670 -> NodeMap [Either ErrMsg ModSummary]
1671 -- Visited set; the range is a list because
1672 -- the roots can have the same module names
1673 -- if allow_dup_roots is True
1674 -> IO [Either ErrMsg ModSummary]
1675 -- The result includes the worklist, except
1676 -- for those mentioned in the visited set
1677 loop [] done = return (concat (nodeMapElts done))
1678 loop ((wanted_mod, is_boot) : ss) done
1679 | Just summs <- Map.lookup key done
1680 = if isSingleton summs then
1681 loop ss done
1682 else
1683 do { multiRootsErr dflags (rights summs); return [] }
1684 | otherwise
1685 = do mb_s <- summariseModule hsc_env old_summary_map
1686 is_boot wanted_mod True
1687 Nothing excl_mods
1688 case mb_s of
1689 Nothing -> loop ss done
1690 Just (Left e) -> loop ss (Map.insert key [Left e] done)
1691 Just (Right s)-> loop (calcDeps s ++ ss)
1692 (Map.insert key [Right s] done)
1693 where
1694 key = (unLoc wanted_mod, is_boot)
1695
1696 mkRootMap :: [ModSummary] -> NodeMap [Either ErrMsg ModSummary]
1697 mkRootMap summaries = Map.insertListWith (flip (++))
1698 [ (msKey s, [Right s]) | s <- summaries ]
1699 Map.empty
1700
1701 -- | Returns the dependencies of the ModSummary s.
1702 -- A wrinkle is that for a {-# SOURCE #-} import we return
1703 -- *both* the hs-boot file
1704 -- *and* the source file
1705 -- as "dependencies". That ensures that the list of all relevant
1706 -- modules always contains B.hs if it contains B.hs-boot.
1707 -- Remember, this pass isn't doing the topological sort. It's
1708 -- just gathering the list of all relevant ModSummaries
1709 msDeps :: ModSummary -> [(Located ModuleName, IsBoot)]
1710 msDeps s =
1711 concat [ [(m,IsBoot), (m,NotBoot)] | m <- ms_home_srcimps s ]
1712 ++ [ (m,NotBoot) | m <- ms_home_imps s ]
1713
1714 home_imps :: [(Maybe FastString, Located ModuleName)] -> [Located ModuleName]
1715 home_imps imps = [ lmodname | (mb_pkg, lmodname) <- imps,
1716 isLocal mb_pkg ]
1717 where isLocal Nothing = True
1718 isLocal (Just pkg) | pkg == fsLit "this" = True -- "this" is special
1719 isLocal _ = False
1720
1721 ms_home_allimps :: ModSummary -> [ModuleName]
1722 ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms)
1723
1724 -- | Like 'ms_home_imps', but for SOURCE imports.
1725 ms_home_srcimps :: ModSummary -> [Located ModuleName]
1726 ms_home_srcimps = home_imps . ms_srcimps
1727
1728 -- | All of the (possibly) home module imports from a
1729 -- 'ModSummary'; that is to say, each of these module names
1730 -- could be a home import if an appropriately named file
1731 -- existed. (This is in contrast to package qualified
1732 -- imports, which are guaranteed not to be home imports.)
1733 ms_home_imps :: ModSummary -> [Located ModuleName]
1734 ms_home_imps = home_imps . ms_imps
1735
1736 -----------------------------------------------------------------------------
1737 -- Summarising modules
1738
1739 -- We have two types of summarisation:
1740 --
1741 -- * Summarise a file. This is used for the root module(s) passed to
1742 -- cmLoadModules. The file is read, and used to determine the root
1743 -- module name. The module name may differ from the filename.
1744 --
1745 -- * Summarise a module. We are given a module name, and must provide
1746 -- a summary. The finder is used to locate the file in which the module
1747 -- resides.
1748
1749 summariseFile
1750 :: HscEnv
1751 -> [ModSummary] -- old summaries
1752 -> FilePath -- source file name
1753 -> Maybe Phase -- start phase
1754 -> Bool -- object code allowed?
1755 -> Maybe (StringBuffer,UTCTime)
1756 -> IO ModSummary
1757
1758 summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf
1759 -- we can use a cached summary if one is available and the
1760 -- source file hasn't changed, But we have to look up the summary
1761 -- by source file, rather than module name as we do in summarise.
1762 | Just old_summary <- findSummaryBySourceFile old_summaries file
1763 = do
1764 let location = ms_location old_summary
1765 dflags = hsc_dflags hsc_env
1766
1767 src_timestamp <- get_src_timestamp
1768 -- The file exists; we checked in getRootSummary above.
1769 -- If it gets removed subsequently, then this
1770 -- getModificationUTCTime may fail, but that's the right
1771 -- behaviour.
1772
1773 -- return the cached summary if the source didn't change
1774 if ms_hs_date old_summary == src_timestamp &&
1775 not (gopt Opt_ForceRecomp (hsc_dflags hsc_env))
1776 then do -- update the object-file timestamp
1777 obj_timestamp <-
1778 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1779 || obj_allowed -- bug #1205
1780 then liftIO $ getObjTimestamp location NotBoot
1781 else return Nothing
1782 hi_timestamp <- maybeGetIfaceDate dflags location
1783 return old_summary{ ms_obj_date = obj_timestamp
1784 , ms_iface_date = hi_timestamp }
1785 else
1786 new_summary src_timestamp
1787
1788 | otherwise
1789 = do src_timestamp <- get_src_timestamp
1790 new_summary src_timestamp
1791 where
1792 get_src_timestamp = case maybe_buf of
1793 Just (_,t) -> return t
1794 Nothing -> liftIO $ getModificationUTCTime file
1795 -- getMofificationUTCTime may fail
1796
1797 new_summary src_timestamp = do
1798 let dflags = hsc_dflags hsc_env
1799
1800 let hsc_src = if isHaskellSigFilename file then HsigFile else HsSrcFile
1801
1802 (dflags', hspp_fn, buf)
1803 <- preprocessFile hsc_env file mb_phase maybe_buf
1804
1805 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1806
1807 -- Make a ModLocation for this file
1808 location <- liftIO $ mkHomeModLocation dflags mod_name file
1809
1810 -- Tell the Finder cache where it is, so that subsequent calls
1811 -- to findModule will find it, even if it's not on any search path
1812 mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location
1813
1814 -- when the user asks to load a source file by name, we only
1815 -- use an object file if -fobject-code is on. See #1205.
1816 obj_timestamp <-
1817 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1818 || obj_allowed -- bug #1205
1819 then liftIO $ modificationTimeIfExists (ml_obj_file location)
1820 else return Nothing
1821
1822 hi_timestamp <- maybeGetIfaceDate dflags location
1823
1824 return (ModSummary { ms_mod = mod, ms_hsc_src = hsc_src,
1825 ms_location = location,
1826 ms_hspp_file = hspp_fn,
1827 ms_hspp_opts = dflags',
1828 ms_hspp_buf = Just buf,
1829 ms_srcimps = srcimps, ms_textual_imps = the_imps,
1830 ms_hs_date = src_timestamp,
1831 ms_iface_date = hi_timestamp,
1832 ms_obj_date = obj_timestamp })
1833
1834 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1835 findSummaryBySourceFile summaries file
1836 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1837 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1838 [] -> Nothing
1839 (x:_) -> Just x
1840
1841 -- Summarise a module, and pick up source and timestamp.
1842 summariseModule
1843 :: HscEnv
1844 -> NodeMap ModSummary -- Map of old summaries
1845 -> IsBoot -- IsBoot <=> a {-# SOURCE #-} import
1846 -> Located ModuleName -- Imported module to be summarised
1847 -> Bool -- object code allowed?
1848 -> Maybe (StringBuffer, UTCTime)
1849 -> [ModuleName] -- Modules to exclude
1850 -> IO (Maybe (Either ErrMsg ModSummary)) -- Its new summary
1851
1852 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod)
1853 obj_allowed maybe_buf excl_mods
1854 | wanted_mod `elem` excl_mods
1855 = return Nothing
1856
1857 | Just old_summary <- Map.lookup (wanted_mod, is_boot) old_summary_map
1858 = do -- Find its new timestamp; all the
1859 -- ModSummaries in the old map have valid ml_hs_files
1860 let location = ms_location old_summary
1861 src_fn = expectJust "summariseModule" (ml_hs_file location)
1862
1863 -- check the modification time on the source file, and
1864 -- return the cached summary if it hasn't changed. If the
1865 -- file has disappeared, we need to call the Finder again.
1866 case maybe_buf of
1867 Just (_,t) -> check_timestamp old_summary location src_fn t
1868 Nothing -> do
1869 m <- tryIO (getModificationUTCTime src_fn)
1870 case m of
1871 Right t -> check_timestamp old_summary location src_fn t
1872 Left e | isDoesNotExistError e -> find_it
1873 | otherwise -> ioError e
1874
1875 | otherwise = find_it
1876 where
1877 dflags = hsc_dflags hsc_env
1878
1879 check_timestamp old_summary location src_fn src_timestamp
1880 | ms_hs_date old_summary == src_timestamp &&
1881 not (gopt Opt_ForceRecomp dflags) = do
1882 -- update the object-file timestamp
1883 obj_timestamp <-
1884 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1885 || obj_allowed -- bug #1205
1886 then getObjTimestamp location is_boot
1887 else return Nothing
1888 hi_timestamp <- maybeGetIfaceDate dflags location
1889 return (Just (Right old_summary{ ms_obj_date = obj_timestamp
1890 , ms_iface_date = hi_timestamp}))
1891 | otherwise =
1892 -- source changed: re-summarise.
1893 new_summary location (ms_mod old_summary) src_fn src_timestamp
1894
1895 find_it = do
1896 -- Don't use the Finder's cache this time. If the module was
1897 -- previously a package module, it may have now appeared on the
1898 -- search path, so we want to consider it to be a home module. If
1899 -- the module was previously a home module, it may have moved.
1900 uncacheModule hsc_env wanted_mod
1901 found <- findImportedModule hsc_env wanted_mod Nothing
1902 case found of
1903 Found location mod
1904 | isJust (ml_hs_file location) ->
1905 -- Home package
1906 just_found location mod
1907
1908 _ -> return Nothing
1909 -- Not found
1910 -- (If it is TRULY not found at all, we'll
1911 -- error when we actually try to compile)
1912
1913 just_found location mod = do
1914 -- Adjust location to point to the hs-boot source file,
1915 -- hi file, object file, when is_boot says so
1916 let location' | IsBoot <- is_boot = addBootSuffixLocn location
1917 | otherwise = location
1918 src_fn = expectJust "summarise2" (ml_hs_file location')
1919
1920 -- Check that it exists
1921 -- It might have been deleted since the Finder last found it
1922 maybe_t <- modificationTimeIfExists src_fn
1923 case maybe_t of
1924 Nothing -> return $ Just $ Left $ noHsFileErr dflags loc src_fn
1925 Just t -> new_summary location' mod src_fn t
1926
1927
1928 new_summary location mod src_fn src_timestamp
1929 = do
1930 -- Preprocess the source file and get its imports
1931 -- The dflags' contains the OPTIONS pragmas
1932 (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
1933 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1934
1935 -- NB: Despite the fact that is_boot is a top-level parameter, we
1936 -- don't actually know coming into this function what the HscSource
1937 -- of the module in question is. This is because we may be processing
1938 -- this module because another module in the graph imported it: in this
1939 -- case, we know if it's a boot or not because of the {-# SOURCE #-}
1940 -- annotation, but we don't know if it's a signature or a regular
1941 -- module until we actually look it up on the filesystem.
1942 let hsc_src = case is_boot of
1943 IsBoot -> HsBootFile
1944 _ | isHaskellSigFilename src_fn -> HsigFile
1945 | otherwise -> HsSrcFile
1946
1947 when (mod_name /= wanted_mod) $
1948 throwOneError $ mkPlainErrMsg dflags' mod_loc $
1949 text "File name does not match module name:"
1950 $$ text "Saw:" <+> quotes (ppr mod_name)
1951 $$ text "Expected:" <+> quotes (ppr wanted_mod)
1952
1953 -- Find the object timestamp, and return the summary
1954 obj_timestamp <-
1955 if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1956 || obj_allowed -- bug #1205
1957 then getObjTimestamp location is_boot
1958 else return Nothing
1959
1960 hi_timestamp <- maybeGetIfaceDate dflags location
1961
1962 return (Just (Right (ModSummary { ms_mod = mod,
1963 ms_hsc_src = hsc_src,
1964 ms_location = location,
1965 ms_hspp_file = hspp_fn,
1966 ms_hspp_opts = dflags',
1967 ms_hspp_buf = Just buf,
1968 ms_srcimps = srcimps,
1969 ms_textual_imps = the_imps,
1970 ms_hs_date = src_timestamp,
1971 ms_iface_date = hi_timestamp,
1972 ms_obj_date = obj_timestamp })))
1973
1974
1975 getObjTimestamp :: ModLocation -> IsBoot -> IO (Maybe UTCTime)
1976 getObjTimestamp location is_boot
1977 = if is_boot == IsBoot then return Nothing
1978 else modificationTimeIfExists (ml_obj_file location)
1979
1980
1981 preprocessFile :: HscEnv
1982 -> FilePath
1983 -> Maybe Phase -- ^ Starting phase
1984 -> Maybe (StringBuffer,UTCTime)
1985 -> IO (DynFlags, FilePath, StringBuffer)
1986 preprocessFile hsc_env src_fn mb_phase Nothing
1987 = do
1988 (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
1989 buf <- hGetStringBuffer hspp_fn
1990 return (dflags', hspp_fn, buf)
1991
1992 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
1993 = do
1994 let dflags = hsc_dflags hsc_env
1995 let local_opts = getOptions dflags buf src_fn
1996
1997 (dflags', leftovers, warns)
1998 <- parseDynamicFilePragma dflags local_opts
1999 checkProcessArgsResult dflags leftovers
2000 handleFlagWarnings dflags' warns
2001
2002 let needs_preprocessing
2003 | Just (Unlit _) <- mb_phase = True
2004 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
2005 -- note: local_opts is only required if there's no Unlit phase
2006 | xopt LangExt.Cpp dflags' = True
2007 | gopt Opt_Pp dflags' = True
2008 | otherwise = False
2009
2010 when needs_preprocessing $
2011 throwGhcExceptionIO (ProgramError "buffer needs preprocesing; interactive check disabled")
2012
2013 return (dflags', src_fn, buf)
2014
2015
2016 -----------------------------------------------------------------------------
2017 -- Error messages
2018 -----------------------------------------------------------------------------
2019
2020 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> ErrMsg
2021 -- ToDo: we don't have a proper line number for this error
2022 noModError dflags loc wanted_mod err
2023 = mkPlainErrMsg dflags loc $ cannotFindModule dflags wanted_mod err
2024
2025 noHsFileErr :: DynFlags -> SrcSpan -> String -> ErrMsg
2026 noHsFileErr dflags loc path
2027 = mkPlainErrMsg dflags loc $ text "Can't find" <+> text path
2028
2029 packageModErr :: DynFlags -> ModuleName -> ErrMsg
2030 packageModErr dflags mod
2031 = mkPlainErrMsg dflags noSrcSpan $
2032 text "module" <+> quotes (ppr mod) <+> text "is a package module"
2033
2034 multiRootsErr :: DynFlags -> [ModSummary] -> IO ()
2035 multiRootsErr _ [] = panic "multiRootsErr"
2036 multiRootsErr dflags summs@(summ1:_)
2037 = throwOneError $ mkPlainErrMsg dflags noSrcSpan $
2038 text "module" <+> quotes (ppr mod) <+>
2039 text "is defined in multiple files:" <+>
2040 sep (map text files)
2041 where
2042 mod = ms_mod summ1
2043 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2044
2045 cyclicModuleErr :: [ModSummary] -> SDoc
2046 -- From a strongly connected component we find
2047 -- a single cycle to report
2048 cyclicModuleErr mss
2049 = ASSERT( not (null mss) )
2050 case findCycle graph of
2051 Nothing -> text "Unexpected non-cycle" <+> ppr mss
2052 Just path -> vcat [ text "Module imports form a cycle:"
2053 , nest 2 (show_path path) ]
2054 where
2055 graph :: [Node NodeKey ModSummary]
2056 graph = [(ms, msKey ms, get_deps ms) | ms <- mss]
2057
2058 get_deps :: ModSummary -> [NodeKey]
2059 get_deps ms = ([ (unLoc m, IsBoot) | m <- ms_home_srcimps ms ] ++
2060 [ (unLoc m, NotBoot) | m <- ms_home_imps ms ])
2061
2062 show_path [] = panic "show_path"
2063 show_path [m] = text "module" <+> ppr_ms m
2064 <+> text "imports itself"
2065 show_path (m1:m2:ms) = vcat ( nest 7 (text "module" <+> ppr_ms m1)
2066 : nest 6 (text "imports" <+> ppr_ms m2)
2067 : go ms )
2068 where
2069 go [] = [text "which imports" <+> ppr_ms m1]
2070 go (m:ms) = (text "which imports" <+> ppr_ms m) : go ms
2071
2072
2073 ppr_ms :: ModSummary -> SDoc
2074 ppr_ms ms = quotes (ppr (moduleName (ms_mod ms))) <+>
2075 (parens (text (msHsFilePath ms)))