1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
17 -- * Flags and settings
18 DynFlags(..), DynFlag(..), GhcMode(..), HscTarget(..), dopt,
26 Target(..), TargetId(..),
33 -- * Loading\/compiling the program
35 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
37 workingDirectoryChanged,
38 checkModule, CheckedModule(..),
39 TypecheckedSource, ParsedSource, RenamedSource,
41 -- * Inspecting the module structure of the program
42 ModuleGraph, ModSummary(..),
47 -- * Inspecting modules
52 modInfoPrintUnqualified,
56 -- * Interactive evaluation
57 getBindings, getPrintUnqual,
59 setContext, getContext,
62 getInfo, GetInfoResult,
73 -- * Abstract syntax elements
76 Module, mkModule, pprModule,
83 isImplicitId, isDeadBinder,
84 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
86 isPrimOpId, isFCallId,
87 isDataConWorkId, idDataCon,
88 isBottomingId, isDictonaryId,
90 -- ** Type constructors
92 isClassTyCon, isSynTyCon, isNewTyCon,
94 -- ** Data constructors
99 classSCTheta, classTvsFds,
101 -- ** Types and Kinds
109 module HsSyn, -- ToDo: remove extraneous bits
112 GhcException(..), showGhcException,
122 * inline bits of HscMain here to simplify layering: hscGetInfo,
124 * we need to expose DynFlags, so should parseDynamicFlags really be
125 part of this interface?
126 * what StaticFlags should we expose, if any?
129 #include "HsVersions.h"
132 import qualified Linker
133 import Linker ( HValue, extendLinkEnv )
134 import NameEnv ( lookupNameEnv )
135 import TcRnDriver ( mkExportEnv, getModuleContents, tcRnLookupRdrName )
136 import RdrName ( plusGlobalRdrEnv )
137 import HscMain ( hscGetInfo, GetInfoResult, hscParseIdentifier,
138 hscStmt, hscTcExpr, hscKcType )
139 import Type ( tidyType )
140 import VarEnv ( emptyTidyEnv )
141 import GHC.Exts ( unsafeCoerce# )
142 import IfaceSyn ( IfaceDecl )
145 import Packages ( initPackages )
146 import NameSet ( NameSet, nameSetToList )
147 import RdrName ( GlobalRdrEnv )
149 import Type ( Kind, Type, dropForAlls )
150 import Id ( Id, idType, isImplicitId, isDeadBinder,
151 isSpecPragmaId, isExportedId, isLocalId, isGlobalId,
153 isPrimOpId, isFCallId,
154 isDataConWorkId, idDataCon,
156 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon )
157 import Class ( Class, classSCTheta, classTvsFds )
158 import DataCon ( DataCon )
159 import InstEnv ( Instance )
160 import Name ( Name, getName, nameModule_maybe )
161 import RdrName ( RdrName, gre_name, globalRdrEnvElts )
162 import NameEnv ( nameEnvElts )
163 import SrcLoc ( Located(..), mkSrcLoc, srcLocSpan )
164 import DriverPipeline
165 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
166 import GetImports ( getImports )
167 import Packages ( isHomePackage )
169 import HscMain ( newHscEnv, hscFileCheck, HscResult(..) )
173 import SysTools ( initSysTools, cleanTempFiles )
178 import ErrUtils ( showPass, Messages, putMsg, debugTraceMsg )
179 import qualified ErrUtils
181 import StringBuffer ( StringBuffer, hGetStringBuffer )
183 import SysTools ( cleanTempFilesExcept )
184 import BasicTypes ( SuccessFlag(..), succeeded, failed )
185 import Maybes ( orElse, expectJust, mapCatMaybes )
186 import TcType ( tcSplitSigmaTy, isDictTy )
187 import Bag ( unitBag, emptyBag )
188 import FastString ( mkFastString )
190 import Directory ( getModificationTime, doesFileExist )
191 import Maybe ( isJust, isNothing, fromJust, fromMaybe, catMaybes )
192 import Maybes ( expectJust )
193 import List ( partition, nub )
194 import qualified List
195 import Monad ( unless, when, foldM )
196 import System ( exitWith, ExitCode(..) )
197 import Time ( ClockTime )
198 import EXCEPTION as Exception hiding (handle)
201 import Prelude hiding (init)
203 -- -----------------------------------------------------------------------------
204 -- Exception handlers
206 -- | Install some default exception handlers and run the inner computation.
207 -- Unless you want to handle exceptions yourself, you should wrap this around
208 -- the top level of your program. The default handlers output the error
209 -- message(s) to stderr and exit cleanly.
210 defaultErrorHandler :: IO a -> IO a
211 defaultErrorHandler inner =
212 -- top-level exception handler: any unrecognised exception is a compiler bug.
213 handle (\exception -> do
216 -- an IO exception probably isn't our fault, so don't panic
217 IOException _ -> putMsg (show exception)
218 AsyncException StackOverflow ->
219 putMsg "stack overflow: use +RTS -K<size> to increase it"
220 _other -> putMsg (show (Panic (show exception)))
221 exitWith (ExitFailure 1)
224 -- all error messages are propagated as exceptions
225 handleDyn (\dyn -> do
228 PhaseFailed _ code -> exitWith code
229 Interrupted -> exitWith (ExitFailure 1)
230 _ -> do putMsg (show (dyn :: GhcException))
231 exitWith (ExitFailure 1)
235 -- | Install a default cleanup handler to remove temporary files
236 -- deposited by a GHC run. This is seperate from
237 -- 'defaultErrorHandler', because you might want to override the error
238 -- handling, but still get the ordinary cleanup behaviour.
239 defaultCleanupHandler :: DynFlags -> IO a -> IO a
240 defaultCleanupHandler dflags inner =
241 -- make sure we clean up after ourselves
242 later (unless (dopt Opt_KeepTmpFiles dflags) $
243 cleanTempFiles dflags)
244 -- exceptions will be blocked while we clean the temporary files,
245 -- so there shouldn't be any difficulty if we receive further
250 -- | Initialises GHC. This must be done /once/ only. Takes the
251 -- command-line arguments. All command-line arguments which aren't
252 -- understood by GHC will be returned.
254 init :: [String] -> IO [String]
257 installSignalHandlers
259 -- Grab the -B option if there is one
260 let (minusB_args, argv1) = partition (prefixMatch "-B") args
261 dflags0 <- initSysTools minusB_args defaultDynFlags
262 writeIORef v_initDynFlags dflags0
264 -- Parse the static flags
265 argv2 <- parseStaticFlags argv1
268 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
269 -- stores the DynFlags between the call to init and subsequent
270 -- calls to newSession.
272 -- | Starts a new session. A session consists of a set of loaded
273 -- modules, a set of options (DynFlags), and an interactive context.
274 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
276 newSession :: GhcMode -> IO Session
278 dflags0 <- readIORef v_initDynFlags
279 dflags <- initDynFlags dflags0
280 env <- newHscEnv dflags{ ghcMode=mode }
284 -- tmp: this breaks the abstraction, but required because DriverMkDepend
285 -- needs to call the Finder. ToDo: untangle this.
286 sessionHscEnv :: Session -> IO HscEnv
287 sessionHscEnv (Session ref) = readIORef ref
289 withSession :: Session -> (HscEnv -> IO a) -> IO a
290 withSession (Session ref) f = do h <- readIORef ref; f h
292 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
293 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
295 -- -----------------------------------------------------------------------------
298 -- | Grabs the DynFlags from the Session
299 getSessionDynFlags :: Session -> IO DynFlags
300 getSessionDynFlags s = withSession s (return . hsc_dflags)
302 -- | Updates the DynFlags in a Session
303 setSessionDynFlags :: Session -> DynFlags -> IO ()
304 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
306 -- | Messages during compilation (eg. warnings and progress messages)
307 -- are reported using this callback. By default, these messages are
308 -- printed to stderr.
309 setMsgHandler :: (String -> IO ()) -> IO ()
310 setMsgHandler = ErrUtils.setMsgHandler
312 -- -----------------------------------------------------------------------------
315 -- ToDo: think about relative vs. absolute file paths. And what
316 -- happens when the current directory changes.
318 -- | Sets the targets for this session. Each target may be a module name
319 -- or a filename. The targets correspond to the set of root modules for
320 -- the program\/library. Unloading the current program is achieved by
321 -- setting the current set of targets to be empty, followed by load.
322 setTargets :: Session -> [Target] -> IO ()
323 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
325 -- | returns the current set of targets
326 getTargets :: Session -> IO [Target]
327 getTargets s = withSession s (return . hsc_targets)
329 -- | Add another target
330 addTarget :: Session -> Target -> IO ()
332 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
335 removeTarget :: Session -> TargetId -> IO ()
336 removeTarget s target_id
337 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
339 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
341 -- Attempts to guess what Target a string refers to. This function implements
342 -- the --make/GHCi command-line syntax for filenames:
344 -- - if the string looks like a Haskell source filename, then interpret
346 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
348 -- - otherwise interpret the string as a module name
350 guessTarget :: String -> IO Target
352 | isHaskellSrcFilename file
353 = return (Target (TargetFile file) Nothing)
355 = do exists <- doesFileExist hs_file
356 if exists then return (Target (TargetFile hs_file) Nothing) else do
357 exists <- doesFileExist lhs_file
358 if exists then return (Target (TargetFile lhs_file) Nothing) else do
359 return (Target (TargetModule (mkModule file)) Nothing)
361 hs_file = file ++ ".hs"
362 lhs_file = file ++ ".lhs"
364 -- -----------------------------------------------------------------------------
365 -- Loading the program
367 -- Perform a dependency analysis starting from the current targets
368 -- and update the session with the new module graph.
369 depanal :: Session -> [Module] -> IO ()
370 depanal (Session ref) excluded_mods = do
371 hsc_env <- readIORef ref
373 dflags = hsc_dflags hsc_env
374 gmode = ghcMode (hsc_dflags hsc_env)
375 targets = hsc_targets hsc_env
376 old_graph = hsc_mod_graph hsc_env
378 showPass dflags "Chasing dependencies"
379 when (gmode == BatchCompile) $
380 debugTraceMsg dflags 1 (showSDoc (hcat [
381 text "Chasing modules from: ",
382 hcat (punctuate comma (map pprTarget targets))]))
384 graph <- downsweep hsc_env old_graph excluded_mods
385 writeIORef ref hsc_env{ hsc_mod_graph=graph }
388 -- | The result of load.
390 = LoadOk Errors -- ^ all specified targets were loaded successfully.
391 | LoadFailed Errors -- ^ not all modules were loaded.
393 type Errors = [String]
395 data ErrMsg = ErrMsg {
396 errMsgSeverity :: Severity, -- warning, error, etc.
397 errMsgSpans :: [SrcSpan],
398 errMsgShortDoc :: Doc,
399 errMsgExtraInfo :: Doc
406 | LoadDependenciesOf Module
408 -- | Try to load the program. If a Module is supplied, then just
409 -- attempt to load up to this target. If no Module is supplied,
410 -- then try to load all targets.
411 load :: Session -> LoadHowMuch -> IO SuccessFlag
412 load session how_much =
413 loadMsgs session how_much ErrUtils.printErrorsAndWarnings
415 -- | Version of 'load' that takes a callback function to be invoked
416 -- on compiler errors and warnings as they occur during compilation.
417 loadMsgs :: Session -> LoadHowMuch -> (Messages-> IO ()) -> IO SuccessFlag
418 loadMsgs s@(Session ref) how_much msg_act
420 -- Dependency analysis first. Note that this fixes the module graph:
421 -- even if we don't get a fully successful upsweep, the full module
422 -- graph is still retained in the Session. We can tell which modules
423 -- were successfully loaded by inspecting the Session's HPT.
426 hsc_env <- readIORef ref
428 let hpt1 = hsc_HPT hsc_env
429 let dflags = hsc_dflags hsc_env
430 let mod_graph = hsc_mod_graph hsc_env
432 let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
433 let verb = verbosity dflags
435 -- The "bad" boot modules are the ones for which we have
436 -- B.hs-boot in the module graph, but no B.hs
437 -- The downsweep should have ensured this does not happen
439 let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
440 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
441 not (ms_mod s `elem` all_home_mods)]
442 ASSERT( null bad_boot_mods ) return ()
444 -- mg2_with_srcimps drops the hi-boot nodes, returning a
445 -- graph with cycles. Among other things, it is used for
446 -- backing out partially complete cycles following a failed
447 -- upsweep, and for removing from hpt all the modules
448 -- not in strict downwards closure, during calls to compile.
449 let mg2_with_srcimps :: [SCC ModSummary]
450 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
452 -- check the stability property for each module.
453 stable_mods@(stable_obj,stable_bco)
454 | BatchCompile <- ghci_mode = ([],[])
455 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
457 -- prune bits of the HPT which are definitely redundant now,
459 pruned_hpt = pruneHomePackageTable hpt1
460 (flattenSCCs mg2_with_srcimps)
465 debugTraceMsg dflags 2 (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
466 text "Stable BCO:" <+> ppr stable_bco))
468 -- Unload any modules which are going to be re-linked this time around.
469 let stable_linkables = [ linkable
470 | m <- stable_obj++stable_bco,
471 Just hmi <- [lookupModuleEnv pruned_hpt m],
472 Just linkable <- [hm_linkable hmi] ]
473 unload hsc_env stable_linkables
475 -- We could at this point detect cycles which aren't broken by
476 -- a source-import, and complain immediately, but it seems better
477 -- to let upsweep_mods do this, so at least some useful work gets
478 -- done before the upsweep is abandoned.
479 --hPutStrLn stderr "after tsort:\n"
480 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
482 -- Now do the upsweep, calling compile for each module in
483 -- turn. Final result is version 3 of everything.
485 -- Topologically sort the module graph, this time including hi-boot
486 -- nodes, and possibly just including the portion of the graph
487 -- reachable from the module specified in the 2nd argument to load.
488 -- This graph should be cycle-free.
489 -- If we're restricting the upsweep to a portion of the graph, we
490 -- also want to retain everything that is still stable.
491 let full_mg :: [SCC ModSummary]
492 full_mg = topSortModuleGraph False mod_graph Nothing
494 maybe_top_mod = case how_much of
496 LoadDependenciesOf m -> Just m
499 partial_mg0 :: [SCC ModSummary]
500 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
502 -- LoadDependenciesOf m: we want the upsweep to stop just
503 -- short of the specified module (unless the specified module
506 | LoadDependenciesOf mod <- how_much
507 = ASSERT( case last partial_mg0 of
508 AcyclicSCC ms -> ms_mod ms == mod; _ -> False )
509 List.init partial_mg0
515 | AcyclicSCC ms <- full_mg,
516 ms_mod ms `elem` stable_obj++stable_bco,
517 ms_mod ms `notElem` [ ms_mod ms' |
518 AcyclicSCC ms' <- partial_mg ] ]
520 mg = stable_mg ++ partial_mg
522 -- clean up between compilations
523 let cleanup = cleanTempFilesExcept dflags
524 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
526 (upsweep_ok, hsc_env1, modsUpswept)
527 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
528 pruned_hpt stable_mods cleanup msg_act mg
530 -- Make modsDone be the summaries for each home module now
531 -- available; this should equal the domain of hpt3.
532 -- Get in in a roughly top .. bottom order (hence reverse).
534 let modsDone = reverse modsUpswept
536 -- Try and do linking in some form, depending on whether the
537 -- upsweep was completely or only partially successful.
539 if succeeded upsweep_ok
542 -- Easy; just relink it all.
543 do debugTraceMsg dflags 2 "Upsweep completely successful."
545 -- Clean up after ourselves
546 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
548 -- Issue a warning for the confusing case where the user
549 -- said '-o foo' but we're not going to do any linking.
550 -- We attempt linking if either (a) one of the modules is
551 -- called Main, or (b) the user said -no-hs-main, indicating
552 -- that main() is going to come from somewhere else.
554 let ofile = outputFile dflags
555 let no_hs_main = dopt Opt_NoHsMain dflags
556 let mb_main_mod = mainModIs dflags
558 main_mod = mb_main_mod `orElse` "Main"
560 = any ((==main_mod).moduleUserString.ms_mod)
562 do_linking = a_root_is_Main || no_hs_main
564 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
565 debugTraceMsg dflags 1 ("Warning: output was redirected with -o, " ++
566 "but no output will be generated\n" ++
567 "because there is no " ++ main_mod ++ " module.")
569 -- link everything together
570 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
572 loadFinish Succeeded linkresult ref hsc_env1
575 -- Tricky. We need to back out the effects of compiling any
576 -- half-done cycles, both so as to clean up the top level envs
577 -- and to avoid telling the interactive linker to link them.
578 do debugTraceMsg dflags 2 "Upsweep partially successful."
581 = map ms_mod modsDone
582 let mods_to_zap_names
583 = findPartiallyCompletedCycles modsDone_names
586 = filter ((`notElem` mods_to_zap_names).ms_mod)
589 let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep)
592 -- Clean up after ourselves
593 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
595 -- there should be no Nothings where linkables should be, now
596 ASSERT(all (isJust.hm_linkable)
597 (moduleEnvElts (hsc_HPT hsc_env))) do
599 -- Link everything together
600 linkresult <- link ghci_mode dflags False hpt4
602 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
603 loadFinish Failed linkresult ref hsc_env4
605 -- Finish up after a load.
607 -- If the link failed, unload everything and return.
608 loadFinish all_ok Failed ref hsc_env
609 = do unload hsc_env []
610 writeIORef ref $! discardProg hsc_env
613 -- Empty the interactive context and set the module context to the topmost
614 -- newly loaded module, or the Prelude if none were loaded.
615 loadFinish all_ok Succeeded ref hsc_env
616 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
620 -- Forget the current program, but retain the persistent info in HscEnv
621 discardProg :: HscEnv -> HscEnv
623 = hsc_env { hsc_mod_graph = emptyMG,
624 hsc_IC = emptyInteractiveContext,
625 hsc_HPT = emptyHomePackageTable }
627 -- used to fish out the preprocess output files for the purposes of
628 -- cleaning up. The preprocessed file *might* be the same as the
629 -- source file, but that doesn't do any harm.
630 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
632 -- -----------------------------------------------------------------------------
636 CheckedModule { parsedSource :: ParsedSource,
637 renamedSource :: Maybe RenamedSource,
638 typecheckedSource :: Maybe TypecheckedSource,
639 checkedModuleInfo :: Maybe ModuleInfo
642 type ParsedSource = Located (HsModule RdrName)
643 type RenamedSource = HsGroup Name
644 type TypecheckedSource = LHsBinds Id
646 -- | This is the way to get access to parsed and typechecked source code
647 -- for a module. 'checkModule' loads all the dependencies of the specified
648 -- module in the Session, and then attempts to typecheck the module. If
649 -- successful, it returns the abstract syntax for the module.
650 checkModule :: Session -> Module -> (Messages -> IO ())
651 -> IO (Maybe CheckedModule)
652 checkModule session@(Session ref) mod msg_act = do
653 -- load up the dependencies first
654 r <- loadMsgs session (LoadDependenciesOf mod) msg_act
655 if (failed r) then return Nothing else do
657 -- now parse & typecheck the module
658 hsc_env <- readIORef ref
659 let mg = hsc_mod_graph hsc_env
660 case [ ms | ms <- mg, ms_mod ms == mod ] of
663 -- Add in the OPTIONS from the source file This is nasty:
664 -- we've done this once already, in the compilation manager
665 -- It might be better to cache the flags in the
666 -- ml_hspp_file field, say
667 let dflags0 = hsc_dflags hsc_env
668 hspp_buf = expectJust "GHC.checkModule" (ms_hspp_buf ms)
669 opts = getOptionsFromStringBuffer hspp_buf
670 (dflags1,leftovers) <- parseDynamicFlags dflags0 (map snd opts)
671 if (not (null leftovers))
672 then do let filename = fromJust (ml_hs_file (ms_location ms))
673 msg_act (optionsErrorMsgs leftovers opts filename)
677 r <- hscFileCheck hsc_env{hsc_dflags=dflags1} msg_act ms
681 HscChecked parsed renamed Nothing ->
682 return (Just (CheckedModule {
683 parsedSource = parsed,
684 renamedSource = renamed,
685 typecheckedSource = Nothing,
686 checkedModuleInfo = Nothing }))
687 HscChecked parsed renamed
688 (Just (tc_binds, rdr_env, details)) -> do
689 let minf = ModuleInfo {
690 minf_details = details,
691 minf_rdr_env = Just rdr_env
693 return (Just (CheckedModule {
694 parsedSource = parsed,
695 renamedSource = renamed,
696 typecheckedSource = Just tc_binds,
697 checkedModuleInfo = Just minf }))
699 -- ---------------------------------------------------------------------------
702 unload :: HscEnv -> [Linkable] -> IO ()
703 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
704 = case ghcMode (hsc_dflags hsc_env) of
705 BatchCompile -> return ()
706 JustTypecheck -> return ()
708 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
710 Interactive -> panic "unload: no interpreter"
712 other -> panic "unload: strange mode"
714 -- -----------------------------------------------------------------------------
718 Stability tells us which modules definitely do not need to be recompiled.
719 There are two main reasons for having stability:
721 - avoid doing a complete upsweep of the module graph in GHCi when
722 modules near the bottom of the tree have not changed.
724 - to tell GHCi when it can load object code: we can only load object code
725 for a module when we also load object code fo all of the imports of the
726 module. So we need to know that we will definitely not be recompiling
727 any of these modules, and we can use the object code.
729 NB. stability is of no importance to BatchCompile at all, only Interactive.
730 (ToDo: what about JustTypecheck?)
732 The stability check is as follows. Both stableObject and
733 stableBCO are used during the upsweep phase later.
736 stable m = stableObject m || stableBCO m
739 all stableObject (imports m)
740 && old linkable does not exist, or is == on-disk .o
741 && date(on-disk .o) > date(.hs)
744 all stable (imports m)
745 && date(BCO) > date(.hs)
748 These properties embody the following ideas:
750 - if a module is stable:
751 - if it has been compiled in a previous pass (present in HPT)
752 then it does not need to be compiled or re-linked.
753 - if it has not been compiled in a previous pass,
754 then we only need to read its .hi file from disk and
755 link it to produce a ModDetails.
757 - if a modules is not stable, we will definitely be at least
758 re-linking, and possibly re-compiling it during the upsweep.
759 All non-stable modules can (and should) therefore be unlinked
762 - Note that objects are only considered stable if they only depend
763 on other objects. We can't link object code against byte code.
767 :: HomePackageTable -- HPT from last compilation
768 -> [SCC ModSummary] -- current module graph (cyclic)
769 -> [Module] -- all home modules
770 -> ([Module], -- stableObject
771 [Module]) -- stableBCO
773 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
775 checkSCC (stable_obj, stable_bco) scc0
776 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
777 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
778 | otherwise = (stable_obj, stable_bco)
780 scc = flattenSCC scc0
781 scc_mods = map ms_mod scc
782 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
784 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
785 -- all imports outside the current SCC, but in the home pkg
787 stable_obj_imps = map (`elem` stable_obj) scc_allimps
788 stable_bco_imps = map (`elem` stable_bco) scc_allimps
795 and (zipWith (||) stable_obj_imps stable_bco_imps)
799 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
803 same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
805 Just hmi | Just l <- hm_linkable hmi
806 -> isObjectLinkable l && t == linkableTime l
807 -- why '>=' rather than '>' above? If the filesystem stores
808 -- times to the nearset second, we may occasionally find that
809 -- the object & source have the same modification time,
810 -- especially if the source was automatically generated
811 -- and compiled. Using >= is slightly unsafe, but it matches
815 = case lookupModuleEnv hpt (ms_mod ms) of
817 Just hmi | Just l <- hm_linkable hmi ->
818 not (isObjectLinkable l) &&
819 linkableTime l >= ms_hs_date ms
821 ms_allimps :: ModSummary -> [Module]
822 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
824 -- -----------------------------------------------------------------------------
825 -- Prune the HomePackageTable
827 -- Before doing an upsweep, we can throw away:
829 -- - For non-stable modules:
830 -- - all ModDetails, all linked code
831 -- - all unlinked code that is out of date with respect to
834 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
835 -- space at the end of the upsweep, because the topmost ModDetails of the
836 -- old HPT holds on to the entire type environment from the previous
839 pruneHomePackageTable
842 -> ([Module],[Module])
845 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
846 = mapModuleEnv prune hpt
848 | is_stable modl = hmi'
849 | otherwise = hmi'{ hm_details = emptyModDetails }
851 modl = mi_module (hm_iface hmi)
852 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
853 = hmi{ hm_linkable = Nothing }
856 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
858 ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
860 is_stable m = m `elem` stable_obj || m `elem` stable_bco
862 -- -----------------------------------------------------------------------------
864 -- Return (names of) all those in modsDone who are part of a cycle
865 -- as defined by theGraph.
866 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
867 findPartiallyCompletedCycles modsDone theGraph
871 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
872 chew ((CyclicSCC vs):rest)
873 = let names_in_this_cycle = nub (map ms_mod vs)
875 = nub ([done | done <- modsDone,
876 done `elem` names_in_this_cycle])
877 chewed_rest = chew rest
879 if notNull mods_in_this_cycle
880 && length mods_in_this_cycle < length names_in_this_cycle
881 then mods_in_this_cycle ++ chewed_rest
884 -- -----------------------------------------------------------------------------
887 -- This is where we compile each module in the module graph, in a pass
888 -- from the bottom to the top of the graph.
890 -- There better had not be any cyclic groups here -- we check for them.
893 :: HscEnv -- Includes initially-empty HPT
894 -> HomePackageTable -- HPT from last time round (pruned)
895 -> ([Module],[Module]) -- stable modules (see checkStability)
896 -> IO () -- How to clean up unwanted tmp files
897 -> (Messages -> IO ()) -- Compiler error message callback
898 -> [SCC ModSummary] -- Mods to do (the worklist)
900 HscEnv, -- With an updated HPT
901 [ModSummary]) -- Mods which succeeded
903 upsweep hsc_env old_hpt stable_mods cleanup msg_act mods
904 = upsweep' hsc_env old_hpt stable_mods cleanup msg_act mods 1 (length mods)
906 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
908 = return (Succeeded, hsc_env, [])
910 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
912 = do putMsg (showSDoc (cyclicModuleErr ms))
913 return (Failed, hsc_env, [])
915 upsweep' hsc_env old_hpt stable_mods cleanup msg_act
916 (AcyclicSCC mod:mods) mod_index nmods
917 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
918 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
919 -- (moduleEnvElts (hsc_HPT hsc_env)))
921 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods msg_act mod
924 cleanup -- Remove unwanted tmp files between compilations
927 Nothing -> return (Failed, hsc_env, [])
929 { let this_mod = ms_mod mod
931 -- Add new info to hsc_env
932 hpt1 = extendModuleEnv (hsc_HPT hsc_env)
934 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
936 -- Space-saving: delete the old HPT entry
937 -- for mod BUT if mod is a hs-boot
938 -- node, don't delete it. For the
939 -- interface, the HPT entry is probaby for the
940 -- main Haskell source file. Deleting it
941 -- would force .. (what?? --SDM)
942 old_hpt1 | isBootSummary mod = old_hpt
943 | otherwise = delModuleEnv old_hpt this_mod
945 ; (restOK, hsc_env2, modOKs)
946 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
947 msg_act mods (mod_index+1) nmods
948 ; return (restOK, hsc_env2, mod:modOKs)
952 -- Compile a single module. Always produce a Linkable for it if
953 -- successful. If no compilation happened, return the old Linkable.
954 upsweep_mod :: HscEnv
956 -> ([Module],[Module])
957 -> (Messages -> IO ())
959 -> Int -- index of module
960 -> Int -- total number of modules
961 -> IO (Maybe HomeModInfo) -- Nothing => Failed
963 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) msg_act summary mod_index nmods
966 this_mod = ms_mod summary
967 mb_obj_date = ms_obj_date summary
968 obj_fn = ml_obj_file (ms_location summary)
969 hs_date = ms_hs_date summary
971 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
972 compile_it = upsweep_compile hsc_env old_hpt this_mod
973 msg_act summary mod_index nmods
975 case ghcMode (hsc_dflags hsc_env) of
978 -- Batch-compilating is easy: just check whether we have
979 -- an up-to-date object file. If we do, then the compiler
980 -- needs to do a recompilation check.
981 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
983 findObjectLinkable this_mod obj_fn obj_date
984 compile_it (Just linkable)
991 _ | is_stable_obj, isJust old_hmi ->
993 -- object is stable, and we have an entry in the
994 -- old HPT: nothing to do
996 | is_stable_obj, isNothing old_hmi -> do
998 findObjectLinkable this_mod obj_fn
999 (expectJust "upseep1" mb_obj_date)
1000 compile_it (Just linkable)
1001 -- object is stable, but we need to load the interface
1002 -- off disk to make a HMI.
1005 ASSERT(isJust old_hmi) -- must be in the old_hpt
1007 -- BCO is stable: nothing to do
1009 | Just hmi <- old_hmi,
1010 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1011 linkableTime l >= ms_hs_date summary ->
1013 -- we have an old BCO that is up to date with respect
1014 -- to the source: do a recompilation check as normal.
1018 -- no existing code at all: we must recompile.
1020 is_stable_obj = this_mod `elem` stable_obj
1021 is_stable_bco = this_mod `elem` stable_bco
1023 old_hmi = lookupModuleEnv old_hpt this_mod
1025 -- Run hsc to compile a module
1026 upsweep_compile hsc_env old_hpt this_mod msg_act summary
1028 mb_old_linkable = do
1030 -- The old interface is ok if it's in the old HPT
1031 -- a) we're compiling a source file, and the old HPT
1032 -- entry is for a source file
1033 -- b) we're compiling a hs-boot file
1034 -- Case (b) allows an hs-boot file to get the interface of its
1035 -- real source file on the second iteration of the compilation
1036 -- manager, but that does no harm. Otherwise the hs-boot file
1037 -- will always be recompiled
1040 = case lookupModuleEnv old_hpt this_mod of
1042 Just hm_info | isBootSummary summary -> Just iface
1043 | not (mi_boot iface) -> Just iface
1044 | otherwise -> Nothing
1046 iface = hm_iface hm_info
1048 compresult <- compile hsc_env msg_act summary mb_old_linkable mb_old_iface
1052 -- Compilation failed. Compile may still have updated the PCS, tho.
1053 CompErrs -> return Nothing
1055 -- Compilation "succeeded", and may or may not have returned a new
1056 -- linkable (depending on whether compilation was actually performed
1058 CompOK new_details new_iface new_linkable
1059 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1060 hm_details = new_details,
1061 hm_linkable = new_linkable }
1062 return (Just new_info)
1065 -- Filter modules in the HPT
1066 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
1067 retainInTopLevelEnvs keep_these hpt
1068 = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
1070 , let mb_mod_info = lookupModuleEnv hpt mod
1071 , isJust mb_mod_info ]
1073 -- ---------------------------------------------------------------------------
1074 -- Topological sort of the module graph
1077 :: Bool -- Drop hi-boot nodes? (see below)
1081 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1082 -- The resulting list of strongly-connected-components is in topologically
1083 -- sorted order, starting with the module(s) at the bottom of the
1084 -- dependency graph (ie compile them first) and ending with the ones at
1087 -- Drop hi-boot nodes (first boolean arg)?
1089 -- False: treat the hi-boot summaries as nodes of the graph,
1090 -- so the graph must be acyclic
1092 -- True: eliminate the hi-boot nodes, and instead pretend
1093 -- the a source-import of Foo is an import of Foo
1094 -- The resulting graph has no hi-boot nodes, but can by cyclic
1096 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1097 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1098 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1099 = stronglyConnComp (map vertex_fn (reachable graph root))
1101 -- restrict the graph to just those modules reachable from
1102 -- the specified module. We do this by building a graph with
1103 -- the full set of nodes, and determining the reachable set from
1104 -- the specified node.
1105 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1106 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1108 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1109 | otherwise = throwDyn (ProgramError "module does not exist")
1111 moduleGraphNodes :: Bool -> [ModSummary]
1112 -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
1113 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1115 -- Drop hs-boot nodes by using HsSrcFile as the key
1116 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1117 | otherwise = HsBootFile
1119 -- We use integers as the keys for the SCC algorithm
1120 nodes :: [(ModSummary, Int, [Int])]
1121 nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)),
1122 out_edge_keys hs_boot_key (ms_srcimps s) ++
1123 out_edge_keys HsSrcFile (ms_imps s) )
1125 , not (isBootSummary s && drop_hs_boot_nodes) ]
1126 -- Drop the hi-boot ones if told to do so
1128 key_map :: NodeMap Int
1129 key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
1132 lookup_key :: HscSource -> Module -> Maybe Int
1133 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1135 out_edge_keys :: HscSource -> [Module] -> [Int]
1136 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1137 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1138 -- the IsBootInterface parameter True; else False
1141 type NodeKey = (Module, HscSource) -- The nodes of the graph are
1142 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1144 msKey :: ModSummary -> NodeKey
1145 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
1147 emptyNodeMap :: NodeMap a
1148 emptyNodeMap = emptyFM
1150 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1151 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1153 nodeMapElts :: NodeMap a -> [a]
1154 nodeMapElts = eltsFM
1156 -- -----------------------------------------------------------------
1157 -- The unlinked image
1159 -- The compilation manager keeps a list of compiled, but as-yet unlinked
1160 -- binaries (byte code or object code). Even when it links bytecode
1161 -- it keeps the unlinked version so it can re-link it later without
1164 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
1166 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
1167 findModuleLinkable_maybe lis mod
1168 = case [LM time nm us | LM time nm us <- lis, nm == mod] of
1171 many -> pprPanic "findModuleLinkable" (ppr mod)
1173 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1174 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1176 -----------------------------------------------------------------------------
1177 -- Downsweep (dependency analysis)
1179 -- Chase downwards from the specified root set, returning summaries
1180 -- for all home modules encountered. Only follow source-import
1183 -- We pass in the previous collection of summaries, which is used as a
1184 -- cache to avoid recalculating a module summary if the source is
1187 -- The returned list of [ModSummary] nodes has one node for each home-package
1188 -- module, plus one for any hs-boot files. The imports of these nodes
1189 -- are all there, including the imports of non-home-package modules.
1192 -> [ModSummary] -- Old summaries
1193 -> [Module] -- Ignore dependencies on these; treat them as
1194 -- if they were package modules
1196 downsweep hsc_env old_summaries excl_mods
1197 = do rootSummaries <- mapM getRootSummary roots
1198 checkDuplicates rootSummaries
1199 loop (concatMap msDeps rootSummaries)
1200 (mkNodeMap rootSummaries)
1202 roots = hsc_targets hsc_env
1204 old_summary_map :: NodeMap ModSummary
1205 old_summary_map = mkNodeMap old_summaries
1207 getRootSummary :: Target -> IO ModSummary
1208 getRootSummary (Target (TargetFile file) maybe_buf)
1209 = do exists <- doesFileExist file
1210 if exists then summariseFile hsc_env file maybe_buf else do
1211 throwDyn (CmdLineError ("can't find file: " ++ file))
1212 getRootSummary (Target (TargetModule modl) maybe_buf)
1213 = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False
1214 modl maybe_buf excl_mods
1215 case maybe_summary of
1216 Nothing -> packageModErr modl
1219 -- In a root module, the filename is allowed to diverge from the module
1220 -- name, so we have to check that there aren't multiple root files
1221 -- defining the same module (otherwise the duplicates will be silently
1222 -- ignored, leading to confusing behaviour).
1223 checkDuplicates :: [ModSummary] -> IO ()
1224 checkDuplicates summaries = mapM_ check summaries
1229 many -> multiRootsErr modl many
1230 where modl = ms_mod summ
1232 [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1233 | summ' <- summaries, ms_mod summ' == modl ]
1235 loop :: [(FilePath,Module,IsBootInterface)]
1236 -- Work list: process these modules
1237 -> NodeMap ModSummary
1240 -- The result includes the worklist, except
1241 -- for those mentioned in the visited set
1242 loop [] done = return (nodeMapElts done)
1243 loop ((cur_path, wanted_mod, is_boot) : ss) done
1244 | key `elemFM` done = loop ss done
1245 | otherwise = do { mb_s <- summarise hsc_env old_summary_map
1246 (Just cur_path) is_boot
1247 wanted_mod Nothing excl_mods
1249 Nothing -> loop ss done
1250 Just s -> loop (msDeps s ++ ss)
1251 (addToFM done key s) }
1253 key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1255 msDeps :: ModSummary -> [(FilePath, -- Importing module
1256 Module, -- Imported module
1257 IsBootInterface)] -- {-# SOURCE #-} import or not
1258 -- (msDeps s) returns the dependencies of the ModSummary s.
1259 -- A wrinkle is that for a {-# SOURCE #-} import we return
1260 -- *both* the hs-boot file
1261 -- *and* the source file
1262 -- as "dependencies". That ensures that the list of all relevant
1263 -- modules always contains B.hs if it contains B.hs-boot.
1264 -- Remember, this pass isn't doing the topological sort. It's
1265 -- just gathering the list of all relevant ModSummaries
1266 msDeps s = concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s]
1267 ++ [(f,m,False) | m <- ms_imps s]
1269 f = msHsFilePath s -- Keep the importing module for error reporting
1272 -----------------------------------------------------------------------------
1273 -- Summarising modules
1275 -- We have two types of summarisation:
1277 -- * Summarise a file. This is used for the root module(s) passed to
1278 -- cmLoadModules. The file is read, and used to determine the root
1279 -- module name. The module name may differ from the filename.
1281 -- * Summarise a module. We are given a module name, and must provide
1282 -- a summary. The finder is used to locate the file in which the module
1285 summariseFile :: HscEnv -> FilePath
1286 -> Maybe (StringBuffer,ClockTime)
1288 -- Used for Haskell source only, I think
1289 -- We know the file name, and we know it exists,
1290 -- but we don't necessarily know the module name (might differ)
1291 summariseFile hsc_env file maybe_buf
1292 = do let dflags = hsc_dflags hsc_env
1294 (dflags', hspp_fn, buf)
1295 <- preprocessFile dflags file maybe_buf
1297 (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1299 -- Make a ModLocation for this file
1300 location <- mkHomeModLocation dflags mod file
1302 -- Tell the Finder cache where it is, so that subsequent calls
1303 -- to findModule will find it, even if it's not on any search path
1304 addHomeModuleToFinder hsc_env mod location
1306 src_timestamp <- case maybe_buf of
1307 Just (_,t) -> return t
1308 Nothing -> getModificationTime file
1310 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1312 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1313 ms_location = location,
1314 ms_hspp_file = Just hspp_fn,
1315 ms_hspp_buf = Just buf,
1316 ms_srcimps = srcimps, ms_imps = the_imps,
1317 ms_hs_date = src_timestamp,
1318 ms_obj_date = obj_timestamp })
1320 -- Summarise a module, and pick up source and timestamp.
1322 -> NodeMap ModSummary -- Map of old summaries
1323 -> Maybe FilePath -- Importing module (for error messages)
1324 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1325 -> Module -- Imported module to be summarised
1326 -> Maybe (StringBuffer, ClockTime)
1327 -> [Module] -- Modules to exclude
1328 -> IO (Maybe ModSummary) -- Its new summary
1330 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1331 | wanted_mod `elem` excl_mods
1334 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1335 = do -- Find its new timestamp; all the
1336 -- ModSummaries in the old map have valid ml_hs_files
1337 let location = ms_location old_summary
1338 src_fn = expectJust "summarise" (ml_hs_file location)
1340 -- return the cached summary if the source didn't change
1341 src_timestamp <- case maybe_buf of
1342 Just (_,t) -> return t
1343 Nothing -> getModificationTime src_fn
1345 if ms_hs_date old_summary == src_timestamp
1346 then do -- update the object-file timestamp
1347 obj_timestamp <- getObjTimestamp location is_boot
1348 return (Just old_summary{ ms_obj_date = obj_timestamp })
1350 -- source changed: re-summarise
1351 new_summary location src_fn maybe_buf src_timestamp
1354 = do found <- findModule hsc_env wanted_mod True {-explicit-}
1357 | not (isHomePackage pkg) -> return Nothing
1358 -- Drop external-pkg
1359 | isJust (ml_hs_file location) -> just_found location
1361 err -> noModError dflags cur_mod wanted_mod err
1364 dflags = hsc_dflags hsc_env
1366 hsc_src = if is_boot then HsBootFile else HsSrcFile
1368 just_found location = do
1369 -- Adjust location to point to the hs-boot source file,
1370 -- hi file, object file, when is_boot says so
1371 let location' | is_boot = addBootSuffixLocn location
1372 | otherwise = location
1373 src_fn = expectJust "summarise2" (ml_hs_file location')
1375 -- Check that it exists
1376 -- It might have been deleted since the Finder last found it
1377 maybe_t <- modificationTimeIfExists src_fn
1379 Nothing -> noHsFileErr cur_mod src_fn
1380 Just t -> new_summary location' src_fn Nothing t
1383 new_summary location src_fn maybe_bug src_timestamp
1385 -- Preprocess the source file and get its imports
1386 -- The dflags' contains the OPTIONS pragmas
1387 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1388 (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1390 when (mod_name /= wanted_mod) $
1391 throwDyn (ProgramError
1392 (showSDoc (text src_fn
1393 <> text ": file name does not match module name"
1394 <+> quotes (ppr mod_name))))
1396 -- Find the object timestamp, and return the summary
1397 obj_timestamp <- getObjTimestamp location is_boot
1399 return (Just ( ModSummary { ms_mod = wanted_mod,
1400 ms_hsc_src = hsc_src,
1401 ms_location = location,
1402 ms_hspp_file = Just hspp_fn,
1403 ms_hspp_buf = Just buf,
1404 ms_srcimps = srcimps,
1406 ms_hs_date = src_timestamp,
1407 ms_obj_date = obj_timestamp }))
1410 getObjTimestamp location is_boot
1411 = if is_boot then return Nothing
1412 else modificationTimeIfExists (ml_obj_file location)
1415 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1416 -> IO (DynFlags, FilePath, StringBuffer)
1417 preprocessFile dflags src_fn Nothing
1419 (dflags', hspp_fn) <- preprocess dflags src_fn
1420 buf <- hGetStringBuffer hspp_fn
1421 return (dflags', hspp_fn, buf)
1423 preprocessFile dflags src_fn (Just (buf, time))
1425 -- case we bypass the preprocessing stage?
1427 local_opts = getOptionsFromStringBuffer buf
1429 (dflags', errs) <- parseDynamicFlags dflags (map snd local_opts)
1433 | Unlit _ <- startPhase src_fn = True
1434 -- note: local_opts is only required if there's no Unlit phase
1435 | dopt Opt_Cpp dflags' = True
1436 | dopt Opt_Pp dflags' = True
1439 when needs_preprocessing $
1440 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1442 return (dflags', src_fn, buf)
1445 -----------------------------------------------------------------------------
1447 -----------------------------------------------------------------------------
1449 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1450 -- ToDo: we don't have a proper line number for this error
1451 noModError dflags cur_mod wanted_mod err
1452 = throwDyn $ ProgramError $ showSDoc $
1453 vcat [cantFindError dflags wanted_mod err,
1454 nest 2 (parens (pp_where cur_mod))]
1456 noHsFileErr cur_mod path
1457 = throwDyn $ CmdLineError $ showSDoc $
1458 vcat [text "Can't find" <+> text path,
1459 nest 2 (parens (pp_where cur_mod))]
1461 pp_where Nothing = text "one of the roots of the dependency analysis"
1462 pp_where (Just p) = text "imported from" <+> text p
1465 = throwDyn (CmdLineError (showSDoc (text "module" <+>
1466 quotes (ppr mod) <+>
1467 text "is a package module")))
1469 multiRootsErr mod files
1470 = throwDyn (ProgramError (showSDoc (
1471 text "module" <+> quotes (ppr mod) <+>
1472 text "is defined in multiple files:" <+>
1473 sep (map text files))))
1475 cyclicModuleErr :: [ModSummary] -> SDoc
1477 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1478 2 (vcat (map show_one ms))
1480 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1481 nest 2 $ ptext SLIT("imports:") <+>
1482 (pp_imps HsBootFile (ms_srcimps ms)
1483 $$ pp_imps HsSrcFile (ms_imps ms))]
1484 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1485 pp_imps src mods = fsep (map (show_mod src) mods)
1488 -- | Inform GHC that the working directory has changed. GHC will flush
1489 -- its cache of module locations, since it may no longer be valid.
1490 -- Note: if you change the working directory, you should also unload
1491 -- the current program (set targets to empty, followed by load).
1492 workingDirectoryChanged :: Session -> IO ()
1493 workingDirectoryChanged s = withSession s $ \hsc_env ->
1494 flushFinderCache (hsc_FC hsc_env)
1496 -- -----------------------------------------------------------------------------
1497 -- inspecting the session
1499 -- | Get the module dependency graph.
1500 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1501 getModuleGraph s = withSession s (return . hsc_mod_graph)
1503 isLoaded :: Session -> Module -> IO Bool
1504 isLoaded s m = withSession s $ \hsc_env ->
1505 return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1507 getBindings :: Session -> IO [TyThing]
1508 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1510 getPrintUnqual :: Session -> IO PrintUnqualified
1511 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1514 -- | Parses a string as an identifier, and returns the list of 'Name's that
1515 -- the identifier can refer to in the current interactive context.
1516 parseName :: Session -> String -> IO [Name]
1517 parseName s str = withSession s $ \hsc_env -> do
1518 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1519 case maybe_rdr_name of
1520 Nothing -> return []
1521 Just (L _ rdr_name) -> do
1522 mb_names <- tcRnLookupRdrName hsc_env rdr_name
1524 Nothing -> return []
1525 Just ns -> return ns
1526 -- ToDo: should return error messages
1529 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
1530 -- entity known to GHC, including 'Name's defined using 'runStmt'.
1531 lookupName :: Session -> Name -> IO (Maybe TyThing)
1532 lookupName s name = withSession s $ \hsc_env -> do
1533 case lookupTypeEnv (ic_type_env (hsc_IC hsc_env)) name of
1534 Just tt -> return (Just tt)
1536 eps <- readIORef (hsc_EPS hsc_env)
1537 return $! lookupType (hsc_HPT hsc_env) (eps_PTE eps) name
1539 -- | Container for information about a 'Module'.
1540 data ModuleInfo = ModuleInfo {
1541 minf_details :: ModDetails,
1542 minf_rdr_env :: Maybe GlobalRdrEnv
1544 -- ToDo: this should really contain the ModIface too
1545 -- We don't want HomeModInfo here, because a ModuleInfo applies
1546 -- to package modules too.
1548 -- | Request information about a loaded 'Module'
1549 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1550 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1551 case lookupModuleEnv (hsc_HPT hsc_env) mdl of
1552 Nothing -> return Nothing
1554 return (Just (ModuleInfo {
1555 minf_details = hm_details hmi,
1556 minf_rdr_env = mi_globals $! hm_iface hmi
1559 -- ToDo: we should be able to call getModuleInfo on a package module,
1560 -- even one that isn't loaded yet.
1562 -- | The list of top-level entities defined in a module
1563 modInfoTyThings :: ModuleInfo -> [TyThing]
1564 modInfoTyThings minf = typeEnvElts (md_types (minf_details minf))
1566 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1567 modInfoTopLevelScope minf
1568 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1570 modInfoExports :: ModuleInfo -> [Name]
1571 modInfoExports minf = nameSetToList $! (md_exports $! minf_details minf)
1573 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1574 modInfoPrintUnqualified minf = fmap unQualInScope (minf_rdr_env minf)
1576 isDictonaryId :: Id -> Bool
1578 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1584 | BinaryCode FilePath
1586 -- ToDo: typechecks abstract syntax or renamed abstract syntax. Issues:
1587 -- - typechecked syntax includes extra dictionary translation and
1588 -- AbsBinds which need to be translated back into something closer to
1589 -- the original source.
1590 -- - renamed syntax currently doesn't exist in a single blob, since
1591 -- renaming and typechecking are interleaved at splice points. We'd
1592 -- need a restriction that there are no splices in the source module.
1595 -- - Data and Typeable instances for HsSyn.
1598 -- - things that aren't in the output of the renamer:
1599 -- - the export list
1603 -- - things that aren't in the output of the typechecker right now:
1604 -- - the export list
1606 -- - type signatures
1607 -- - type/data/newtype declarations
1608 -- - class declarations
1610 -- - extra things in the typechecker's output:
1611 -- - default methods are turned into top-level decls.
1612 -- - dictionary bindings
1614 -- ToDo: check for small transformations that happen to the syntax in
1615 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1617 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1618 -- to get from TyCons, Ids etc. to TH syntax (reify).
1620 -- :browse will use either lm_toplev or inspect lm_interface, depending
1621 -- on whether the module is interpreted or not.
1623 -- various abstract syntax types (perhaps IfaceBlah)
1627 -- This is for reconstructing refactored source code
1628 -- Calls the lexer repeatedly.
1629 -- ToDo: add comment tokens to token stream
1630 getTokenStream :: Session -> Module -> IO [Located Token]
1633 -- -----------------------------------------------------------------------------
1634 -- Interactive evaluation
1638 -- | Set the interactive evaluation context.
1640 -- Setting the context doesn't throw away any bindings; the bindings
1641 -- we've built up in the InteractiveContext simply move to the new
1642 -- module. They always shadow anything in scope in the current context.
1643 setContext :: Session
1644 -> [Module] -- entire top level scope of these modules
1645 -> [Module] -- exports only of these modules
1647 setContext (Session ref) toplevs exports = do
1648 hsc_env <- readIORef ref
1649 let old_ic = hsc_IC hsc_env
1650 hpt = hsc_HPT hsc_env
1652 mapM_ (checkModuleExists hsc_env hpt) exports
1653 export_env <- mkExportEnv hsc_env exports
1654 toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1655 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1656 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1657 ic_exports = exports,
1658 ic_rn_gbl_env = all_env } }
1660 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1661 checkModuleExists hsc_env hpt mod =
1662 case lookupModuleEnv hpt mod of
1663 Just mod_info -> return ()
1664 _not_a_home_module -> do
1665 res <- findPackageModule hsc_env mod True
1667 Found _ _ -> return ()
1668 err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1669 throwDyn (CmdLineError (showSDoc msg))
1671 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1672 mkTopLevEnv hpt modl
1673 = case lookupModuleEnv hpt modl of
1675 throwDyn (ProgramError ("mkTopLevEnv: not a home module "
1676 ++ showSDoc (pprModule modl)))
1678 case mi_globals (hm_iface details) of
1680 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1681 ++ showSDoc (pprModule modl)))
1682 Just env -> return env
1684 -- | Get the interactive evaluation context, consisting of a pair of the
1685 -- set of modules from which we take the full top-level scope, and the set
1686 -- of modules from which we take just the exports respectively.
1687 getContext :: Session -> IO ([Module],[Module])
1688 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1689 return (ic_toplev_scope ic, ic_exports ic))
1691 -- | Returns 'True' if the specified module is interpreted, and hence has
1692 -- its full top-level scope available.
1693 moduleIsInterpreted :: Session -> Module -> IO Bool
1694 moduleIsInterpreted s modl = withSession s $ \h ->
1695 case lookupModuleEnv (hsc_HPT h) modl of
1696 Just details -> return (isJust (mi_globals (hm_iface details)))
1697 _not_a_home_module -> return False
1699 -- | Looks up an identifier in the current interactive context (for :info)
1700 {-# DEPRECATED getInfo "we should be using parseName/lookupName instead" #-}
1701 getInfo :: Session -> String -> IO [GetInfoResult]
1702 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1704 -- | Returns all names in scope in the current interactive context
1705 getNamesInScope :: Session -> IO [Name]
1706 getNamesInScope s = withSession s $ \hsc_env -> do
1707 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1709 -- -----------------------------------------------------------------------------
1710 -- Getting the type of an expression
1712 -- | Get the type of an expression
1713 exprType :: Session -> String -> IO (Maybe Type)
1714 exprType s expr = withSession s $ \hsc_env -> do
1715 maybe_stuff <- hscTcExpr hsc_env expr
1717 Nothing -> return Nothing
1718 Just ty -> return (Just tidy_ty)
1720 tidy_ty = tidyType emptyTidyEnv ty
1721 dflags = hsc_dflags hsc_env
1723 -- -----------------------------------------------------------------------------
1724 -- Getting the kind of a type
1726 -- | Get the kind of a type
1727 typeKind :: Session -> String -> IO (Maybe Kind)
1728 typeKind s str = withSession s $ \hsc_env -> do
1729 maybe_stuff <- hscKcType hsc_env str
1731 Nothing -> return Nothing
1732 Just kind -> return (Just kind)
1734 -----------------------------------------------------------------------------
1735 -- cmCompileExpr: compile an expression and deliver an HValue
1737 compileExpr :: Session -> String -> IO (Maybe HValue)
1738 compileExpr s expr = withSession s $ \hsc_env -> do
1739 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1741 Nothing -> return Nothing
1742 Just (new_ic, names, hval) -> do
1744 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1746 case (names,hvals) of
1747 ([n],[hv]) -> return (Just hv)
1748 _ -> panic "compileExpr"
1750 -- -----------------------------------------------------------------------------
1751 -- running a statement interactively
1754 = RunOk [Name] -- ^ names bound by this evaluation
1755 | RunFailed -- ^ statement failed compilation
1756 | RunException Exception -- ^ statement raised an exception
1758 -- | Run a statement in the current interactive context. Statemenet
1759 -- may bind multple values.
1760 runStmt :: Session -> String -> IO RunResult
1761 runStmt (Session ref) expr
1763 hsc_env <- readIORef ref
1765 -- Turn off -fwarn-unused-bindings when running a statement, to hide
1766 -- warnings about the implicit bindings we introduce.
1767 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1768 hsc_env' = hsc_env{ hsc_dflags = dflags' }
1770 maybe_stuff <- hscStmt hsc_env' expr
1773 Nothing -> return RunFailed
1774 Just (new_hsc_env, names, hval) -> do
1776 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1777 either_hvals <- sandboxIO thing_to_run
1779 case either_hvals of
1781 -- on error, keep the *old* interactive context,
1782 -- so that 'it' is not bound to something
1783 -- that doesn't exist.
1784 return (RunException e)
1787 -- Get the newly bound things, and bind them.
1788 -- Don't need to delete any shadowed bindings;
1789 -- the new ones override the old ones.
1790 extendLinkEnv (zip names hvals)
1792 writeIORef ref new_hsc_env
1793 return (RunOk names)
1796 -- We run the statement in a "sandbox" to protect the rest of the
1797 -- system from anything the expression might do. For now, this
1798 -- consists of just wrapping it in an exception handler, but see below
1799 -- for another version.
1801 sandboxIO :: IO a -> IO (Either Exception a)
1802 sandboxIO thing = Exception.try thing
1805 -- This version of sandboxIO runs the expression in a completely new
1806 -- RTS main thread. It is disabled for now because ^C exceptions
1807 -- won't be delivered to the new thread, instead they'll be delivered
1808 -- to the (blocked) GHCi main thread.
1810 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1812 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1813 sandboxIO thing = do
1814 st_thing <- newStablePtr (Exception.try thing)
1815 alloca $ \ p_st_result -> do
1816 stat <- rts_evalStableIO st_thing p_st_result
1817 freeStablePtr st_thing
1819 then do st_result <- peek p_st_result
1820 result <- deRefStablePtr st_result
1821 freeStablePtr st_result
1822 return (Right result)
1824 return (Left (fromIntegral stat))
1826 foreign import "rts_evalStableIO" {- safe -}
1827 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1828 -- more informative than the C type!
1831 -- ---------------------------------------------------------------------------
1832 -- cmBrowseModule: get all the TyThings defined in a module
1834 {-# DEPRECATED browseModule "we should be using getModuleInfo instead" #-}
1835 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1836 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1837 mb_decls <- getModuleContents hsc_env modl exports_only
1839 Nothing -> return [] -- An error of some kind
1840 Just ds -> return ds
1843 -----------------------------------------------------------------------------
1844 -- show a module and it's source/object filenames
1846 showModule :: Session -> ModSummary -> IO String
1847 showModule s mod_summary = withSession s $ \hsc_env -> do
1848 case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1849 Nothing -> panic "missing linkable"
1850 Just mod_info -> return (showModMsg obj_linkable mod_summary)
1852 obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))